Php code to add a record to the database

I am working on a dashboard (admin pages) for a website. All pages have the same code with slight changes in the name and columns of the database table. They all work fine, but one page doesn't work.

This is his code ....

<?php include('connect.php'); // read the input data $KTitle = $_POST['Title']; $Kcontent = $_POST['content']; $ImgName = $_FILES["file"]["name"]; //get img extension $ImgExtension = substr($ImgName, (strlen($ImgName) - 4), strlen($ImgName)); //check if it Gif, Bng, Jpg if ($ImgExtension == ".gif" || $ImgExtension == ".jpg" || $ImgExtension == ".png") { //get img name to rename it then readd the extinsion $ImgName = substr($ImgName, 0, (strlen($ImgName) - 4)); $storyImgName = $ImgName . "_" . $Title; $target = "../CharacterImgs/" . $storyImgName . $ImgExtension; $target = str_replace(" ", "_", $target); move_uploaded_file($_FILES['file']['tmp_name'], $target); mysql_query("INSERT INTO CharactersN (name,desc,img) VALUES ('$KTitle', '$Kcontent','$target')"); echo "<meta http-equiv=\"refresh\" content=\"3;URL=AddCharacterForm.php\">"; } ?> 
+4
source share
2 answers

You have a problem:

 INSERT INTO CharactersN (name,desc,img) 

desc is a reserved word, so you should use a β€œnotation” that looks like this:

 INSERT INTO CharactersN (`name`,`desc`,`img`) 

It is recommended that you use this notation for field names each time (or never use reserved words for field names in your database design).


Also, read SQL Injection because your code indicates that you are not aware of this. You insert values ​​into your request that come from outside (POST in this case).

 VALUES ('$KTitle', '$Kcontent','$target')") 

You should avoid these values ​​first mysql_real_escape_string() , or even better to use PDO to interact with the database.

enter image description here from xkcd

+1
source

If you use desc as the column name in MySQL, you must surround it in backticks because it is a reserved word .

 "INSERT INTO CharactersN (name, `desc`, img) ..." 
+4
source

Source: https://habr.com/ru/post/1382946/


All Articles