简体   繁体   中英

Using PDO Prepared Statements With MySQL Query Variable

I am trying to increment rows in a table using PHP PDO and i have come up with this query

UPDATE users SET log = ? 

I am trying to make an update based on the previous value on each column of the log

So, if my table was like this earlier

+----+------+------+-----------+--------+ | id | name | age | eye_color | log | +----+------+------+-----------+--------+ | 21 | OLa | 19 | black | 1 | | 22 | OLa | 19 | Green | 2 | | 23 | OLa | 19 | Grey | 3 | +----+------+------+-----------+--------+

Am expecting to get this result

+----+------+------+-----------+--------+ | id | name | age | eye_color | log | +----+------+------+-----------+--------+ | 21 | OLa | 19 | black | 2 | | 22 | OLa | 19 | Green | 3 | | 23 | OLa | 19 | Grey | 4 | +----+------+------+-----------+--------+

I found out i could make the value of my placeholder to be

log + 1

There by making the full query

UPDATE users SET log = log + 1

This works well when i use the PDO's query method and also from my terminal, the problem comes when I try updating this using prepared statements, If i did

$stmt = $this->pdo->prepare("UPDATE users SET log = ?");
$stml->execute(['height + 1']);

Then all the log columns becomes 0.

Is there anything am doing wrong? I also know i can just make the query plain

$stmt = $this->pdo->prepare("UPDATE users SET log = log + 1");
$stmt->execute(['log + 1']);

But i would prefer my initial approach, i am working with some constraints.

Since you are not getting information from the user, and is to sum 1 to a column you are safe executing a regular query.

UPDATE users SET log = log + 1

If you use a prepare statement you will have to query the column get the current value and then on the second query do the update and add 1 to it.

You can't use query parameters to insert expressions to your syntax. Parameters are not just string-interpolation. If they were, there would be no benefit to using them, because you can do string-interpolation easily in PHP already.

The whole point of query parameters is that the value is combined with the query on the server, after the SQL syntax has been parsed, so it's too late for you to insert any new syntax, like an expression.

Query parameters are always treated as a single scalar value. You can't use a parameter for:

  • Table identifiers
  • Column identifiers
  • SQL keywords
  • Expressions
  • Lists of values

As others have explained, in this case, you have no need to use a query parameter anyway. Using the literal expression log + 1 directly in your query is safe. There's no untrusted content (from users or other sources) being inserted into the query, so there's no risk of SQL injection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM