bubble
bubble

Reputation: 3526

Why MySQL is changing the column name with value?

I have the following piece of code written somewhere in PHP:

$sql="UPDATE drivers ".
"SET Location=$lo ".
"WHERE DriverId=$id";

echo $sql;

The outcome of echo is

UPDATE drivers SET Location=locA WHERE DriverId=3

However when I run

$result = mysqli_query($con2,$sql);
echo $result;
echo mysqli_error($con2);

I get

Unknown column 'locA' in 'field list'

Why am I getting 'locA' instead of Location as column name ?

Upvotes: 2

Views: 72

Answers (4)

Erik
Erik

Reputation: 4105

At least you must

$sql="UPDATE drivers ". "SET Location='$lo' ". "WHERE DriverId=$id";

but go to mysqli and use prepared statements instead. If you do what I suggest you are wide open to SQL-injections.

Upvotes: 1

James
James

Reputation: 11

MySQL is trying to evaluate locA as a field as it's not a string value. Try something more like:

$sql="UPDATE drivers ".
"SET Location='".$lo."' ".
"WHERE DriverId=$id";

Which should result in:

UPDATE drivers SET Location='locA' WHERE DriverId=3

PDO and prepared statements would be the way to go though as others have mentioned.

Upvotes: 1

Robbert
Robbert

Reputation: 6592

locA is a string and needs to be quoted.

$sql="UPDATE drivers ".
"SET Location='$lo' ".
"WHERE DriverId=$id";

You should look into using PDO and prepared statements to do the quoting for you.

Upvotes: 3

undone
undone

Reputation: 7888

you need to put $lo inside single quotes:

$sql="UPDATE drivers ".
"SET Location='$lo' ".
"WHERE DriverId='$id'";

Upvotes: 2

Related Questions