2

I am using following query

$abilityPts = xxx;
$statement = $conn->prepare('UPDATE players SET ability = (ability + $abilityPts) WHERE id = :myPlayerId');

However it is giving mer error..

$abilityPts column not found

How can i resolve this issue?

{"error":"SQLSTATE[42S22]: Column not found: 1054 Unknown column '$abilityPts' in 'field list'"}
kapa
  • 77,694
  • 21
  • 158
  • 175
Muhammad Umar
  • 11,391
  • 21
  • 91
  • 193
  • 1
    Everyone's who's suggesting string concatenation should read [How to prevent SQL injection in PHP?](http://stackoverflow.com/questions/60174/how-to-prevent-sql-injection-in-php) – Álvaro González Mar 07 '13 at 08:43

5 Answers5

6
  1. You are using prepared statements. So use prepared statements. Use :abilityPts and bind $abilityPts the same way you are binding :myPlayerId.

    $conn->prepare('UPDATE players SET ability = (ability + :abilityPts) WHERE id = :myPlayerId');
    

    Creating SQL queries through concatenation and embedding PHP variables in strings is a very bad practice, it can leave your code open to SQL Injection which is serious business. Prepared statements are much cleaner, more secure and generally are accepted as best practice by the community. If you are already using prepared statements, you are doing well, just keep using them.

  2. You should do what I've described in 1., but also notice the difference between ' and " in PHP.

    ' (Single quoted):

    Unlike the double-quoted and heredoc syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.

    This basically means the following:

    $a = 15;
    echo 'My favorite is $a.'; //My favorite is $a.
    echo "My favorite is $a."; //My favorite is 5.
    

    For further information, please read the PHP manual on Strings.

kapa
  • 77,694
  • 21
  • 158
  • 175
-2

Putting a variable in single quotes will not have the variable evaluated. Either use double quotes or string concatenation.

To avoid further punishment for my rather generic answer: You should not use variables directly in queries to the database in general and especially when using prepared statements.

Christoph Grimmer
  • 4,210
  • 4
  • 40
  • 64
-2
$statement = $conn->prepare(sprintf('UPDATE players SET ability = (ability + %d) WHERE id = :myPlayerId', $abilityPts));

try this

zkanoca
  • 9,664
  • 9
  • 50
  • 94
-2

try doing the below:

$statement = $conn->prepare("UPDATE players SET ability = (ability + " . $abilityPts . ") WHERE id = :myPlayerId");
-2

Please try below code:

$abilityPts = xxx;
$statement = $conn->prepare("UPDATE players SET ability = (ability + ".$abilityPts.") WHERE id = :myPlayerId");
Kevin G Flynn
  • 231
  • 4
  • 14