Jump to content

SQL query fails when using bindValue, but works when value is explicitly stated


Twinbird
Go to solution Solved by mac_gyver,

Recommended Posts

Hello,

 

I have the following code:

$sql = 'SELECT id, name, research_interests FROM students ORDER BY name ASC';
$s = $pdo->prepare($sql);
$s->execute();

This code works with no problems. But when I change it to use bindValue(), it fails.

$sql = 'SELECT id, name, research_interests FROM students ORDER BY name :order';
$s = $pdo->prepare($sql);
$s->bindValue(':order', 'ASC');
$s->execute();

What could be causing the problem?

 

This is the error I receive:

exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?' at line 1' in /var/www/grad/support/myMeetings.php:146 Stack trace: #0 /var/www/grad/support/myMeetings.php(146): PDO->prepare('SELECT id, name...') #1 /var/www/grad/controllers/myMeetings.php(73): listStudents() #2 /var/www/grad/index.php(36): include('/var/www/grad/c...') #3 {main}

Thanks,

 

Twin

 

Link to comment
Share on other sites

The default type for bindValue() is String. As mac_gyver said, the order orientation ASC is a keyword, not a string. (You wouldn't want quotes around it, right?) Since it isn't a string, you don't need to escape it or anything, so you can simply concatenate the variable to your query string without worrying about binding it:

$sql = 'SELECT id, name, research_interests FROM students ORDER BY name '.$order;

Make sure $order isn't generated directly from the user or you could create an injection vulnerability.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.