0

I want to insert name, description and image to my db. What is wrong with this code?

<?php
$host="localhost";
$user="root";
$password="";
$database="jin";
$sql = mysqli_connect($host,$user,$password,$database) or die("cannot connect");

if(isset($_POST['submit']))
{
    $file = addslashes(file_get_contents($_FILES["image"]["tmp_name"])); 
    $name = $_POST['name'];
    $description = $_POST['description'];
    $query = "INSERT INTO cai(name,description,image,) VALUES ('$name','$description','$file')";
    if(mysqli_query($sql,$query))
    {
        echo"uploaded";
    }
    else {
        echo"not inserted";
    }
}
?>
Matt McDonald
  • 4,791
  • 2
  • 34
  • 55
ben
  • 11

2 Answers2

3

1)

Do not use root to connect to your database in PHP. Use a new -specialist- SQL user intended for PHP and with minimum privileges. Otherwise, it's bad practise and a potential security hole.

2)

Remove the final comma from the column name list ...image,)

3)

Encase your column names in backticks (these guys: " ` "; usually next to number 1 on latin keyboards).

3b)

Avoid using Reserved words.

4)

Read the PHP error log

5)

Correctly output MySQLi errors with

 mysqli_query($sql,$query) or error_log(print_r(mysqli_error($sql),true));

which will output to your error log file the precise MySQLi error.

6)

Use Prepared Statements. Huh?

Community
  • 1
  • 1
Martin
  • 22,212
  • 11
  • 70
  • 132
-2

The input parameters insert into a string. If this is the case it is not correct because I think in the db you have declared the column name, description, file is varchar or text.

You can correct the following:

$query = "INSERT INTO cai(name,description,image,) VALUES ('".$name."','".$description."','".$file."')"; 
Qirel
  • 25,449
  • 7
  • 45
  • 62
TuChiDo
  • 53
  • 5
  • What is the difference between this line and the one in the original post? When you have a string in double quotes PHP will parse it and expand the variables. Although it can be more clear and easier to read if you don't mix variables into your string, the resulting strings in **$query** for these cases will be identical. The trailing comma in the column list might be an issue though, but you have that in your answer too. – inquam Feb 11 '19 at 10:59