2

I just can't get this query to work when updating records in a mySQL database:

In my update script I POST the contents of two variables, and I can see the contents when I print them:

$orderno =$_POST['order_no'][$i];
$status =$_POST['order_status'][$i];

My SQL query looks like:

<?php
if(isset($_POST['order_status']))
{
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$orderno =$_POST['order_no'][$i];
$status =$_POST['order_status'][$i];
print_r($_POST['order_no']);
$sql = 'UPDATE Orders SET status="' . '$status'. '" WHERE   Orderno="' .'$orderno' . '"';
echo $sql;
mysql_select_db('PurchaseOrders');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully\n";
mysql_close($conn);
}
?>

This is inserting the variable name itself into the database and not the value of the variable which is printed? Many thanks

m1243
  • 159
  • 2
  • 15
  • 1
    Please do not use the `mysql` functions as they're deprecated. Instead, use prepared statements with [`mysqli`](http://php.net/manual/en/book.mysqli.php) or [`PDO`](http://php.net/manual/en/book.pdo.php). – h2ooooooo Sep 21 '12 at 09:02

3 Answers3

1

Try the following:

$sql = 'UPDATE Orders SET status="' . $status. '" WHERE   Orderno="' .$orderno . '"';

As well take into consideration security. You are not validating string (order number or status) in any shape or form.

As well mysql functions are deprecated, consider using mysqli

Miroslav
  • 1,960
  • 1
  • 13
  • 26
1
$sql = "UPDATE Orders SET status='" . $status . "' WHERE   Orderno= '" . $orderno . "' ";

When you encapsulate a variable in single quotes, PHP will take it "as is". It won't evaluate any variables found inside the quotes.

Have a look at the difference between single quotes and double quotes.

Community
  • 1
  • 1
Wayne Whitty
  • 19,513
  • 7
  • 44
  • 66
0

use the query like this

$sql = "UPDATE Orders SET status='$status' WHERE  Orderno='$orderno'";

you are using variable inside single quotes. Inside single quotes variable name is not resolving, you have to use double quotes for this. In double quotes variable value is coming.

Yogesh Suthar
  • 30,424
  • 18
  • 72
  • 100