开发者

sprintf() Versus mysql_query()

Having trouble formatting my code to execute without error using sprintf() When I run the code I get this error: Parse error: syntax error, unexpected T_VARIABLE in /location on line 16

 $query = sprintf('UPDATE `%s` SET `stock` = :amount WHERE `itemname` = '$q'', $tablename);

Above is line 16 in my code. I'm assuming it is syntax related.

I am now receiving the following error:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1065 Query was empty' in /home/content/63/6563663/html/inventory/pg.php:19 Stack trace: #0 /home/content/63/6563663/html/inventory/pg.php(19): PDOStatement->execute() #1 {main} thrown in /home/content/63/6563663/html/inventory/pg.php on line 19

This is my entire code block:

 <?php

 $u=$_GET["u"];

 if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "form2")) {
 $amount = isset($_POST['amount']) ? $_POST['amount'] : null;
 if (null != $amount) {

 $user = 'username';
 $pass = 'password';
 $pdo = new PDO('mysql:localhost', $user, $pass);
 $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
 session_start();
 $tablename = $_SESSION['MM_Username'];
 $query = sprintf('UPDATE %s SET stock= :amount WHERE itemname= '.$u, $tablename);
 $stmt = $pdo-开发者_JAVA百科>prepare($UpdateQuery);
 $stmt->bindParam('amount', $amount);
 $stmt->execute();
 }
 }

 ?>

Thank you, seems my error is dealing with the PDO execution, not the query itself. If anyone has any ideas on that it would be great. Alan, I used your method for the quotes and also am running the query through mysql_real_escape_string().


Please do not build SQL queries out of variables. Use bind variables.

See http://bobby-tables.com/php.html


Try this:

$query = sprintf('UPDATE%sSETstock= :amount WHEREitemname= '.$q, $tablename);

You need to put a concatenation operator between strings and variables to combine them together. You also can get rid of the '' after $q because it is not changing the string at all.

Edit:

I believe I misread what you are trying to do. Try this instead:

$query = sprintf("UPDATE%sSETstock= :amount WHEREitemname= '$q'", $tablename);

By changing your PHP string to be within double quotes, you do not need to escape your single quotes, and $q will be expanded to its value.

Also, be sure that you run $q and $tablename through mysql_real_escape_string() to prevent SQL injection.


Like so:

$query = sprintf('UPDATE `%s` SET `stock` = :amount WHERE `itemname` = \'$q\'', $tablename);

or

$query = sprintf("UPDATE `%s` SET `stock` = :amount WHERE `itemname` = \'$q\'", $tablename);

You can't have unescaped 's in strings delimited by '. Either unescaped "s in strings delimited by ". To escape the string delimiter you need to prepend a \ character.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜