Gul Amed Gul Amed - 4 months ago 7
PHP Question

Why does this piece of code not work, when I pass value through input text?

I don't know why this piece of code did not work, when I pass value through input text?if i am violating the rules then what is it,s correct format.

<?php

$id1 = $_POST["id1"];
$name = $_POST["name"];
$update = $_POST["update"];
echo $id1; //working
echo $name; //working
echo $update; //working



mysqli_query($conn , 'update insert1 set '.$name.' = '.$update.'
where id-1 = '.$id1.'' ); //not working
// but if I manually use this as follows it works correctly
mysqli_query($conn , 'update insert1 set name = "new" where id-1 = '1'' );

?>

Answer

I'd wrap $update with single quotes (notice that I flipped the quotations) and changed id1 into $id1:

mysqli_query($conn , "update insert1 set  ".$name." = '".$update."'
where id-1 = ".$id1 );

If id-1 is a string column type in the database then I'd wrap $id1 with single quotes. like this:

mysqli_query($conn , "update insert1 set  ".$name." = '".$update."'
where id-1 = '".$id1."'" );

Notes:

  • I'd double check if id-1 is a correct column name, it seems unlikely since hyphens tend to cause trouble in column names for MySQL.
  • As mentioned in another answer, your code is vulnerable for SQL injection, I'd check this: http://stackoverflow.com/a/16282269/4283725