andreaem
andreaem

Reputation: 1655

PHP - MySQLi INSERT not working

I must to send an INSERT query to MySQL database, assuming all the variables are correctly setted, I'm using this code:

 $check_alrd_sent = $mysqli -> query("SELECT * FROM reviews WHERE id_prod =" . $id_prod . " AND id_user = " . $current_usr . " LIMIT 1");
$check = mysqli_fetch_all($check_alrd_sent);

if ($check != NULL) {
    $check_err = 1;
} else {
    $ins_rev = $mysqli -> query("INSERT INTO `reviews` (`ID` ,`ID_prod` ,`ID_user` ,`review` ,`stars`) VALUES (NULL , " . $id_prod .",  " . $current_usr . ", " . $review . ",  " . $rating . ");");
    $ins_result = 1;
}
mysqli_free_result($check_alrd_sent);

The $ins_result variable is correcly set as result, as I can see using var_dump() but now rows are insert in database.

The strange thing is that if I call the MySQL error log can clearly see that the insert is sent to the database correctly as:

42 Query     INSERT INTO `reviews` (`ID` ,`ID_prod` ,`ID_user` ,`review` ,`stars`) VALUES (NULL , 11,  1, asd,  4)

But it doesn't appear in the table.

Any suggestions? Thanks

Upvotes: 2

Views: 4255

Answers (3)

devpro
devpro

Reputation: 16117

You have two issues in your INSERT Statement:

  1. Value of review column is a string so you need to use quotes around review VALUE.
  2. I think ID is an AUTO INCREMENT NOT NULL field. So no need to use in INSERT Query.

Modified query:

INSERT INTO `reviews` 
( `ID_prod`, `ID_user` ,`review` ,`stars`) 
VALUES (11, 1, "asd", 4)

Upvotes: 0

Source Matters
Source Matters

Reputation: 1221

In your output, "asd" is not in single quotes. That would be invalid SQL. Should also think about converting to non-deprecated SQL functions such as PDO.

Upvotes: 0

Gouda Elalfy
Gouda Elalfy

Reputation: 7023

varchar fields must be in 2 quota, so review field must be in 2 ':

$ins_rev = $mysqli -> query("INSERT INTO `reviews` (`ID` ,`ID_prod` ,`ID_user`
,`review` ,`stars`) VALUES (NULL , '" . $id_prod ."', ' " . $current_usr . "', '" .
$review . "',  '" . $rating . "');");

Upvotes: 1

Related Questions