Monday 3 September 2018

The mysqli query does not work when the variable is inserted


I need an extra pair of eyes! I have a super-simple query:


$result = $mysqli->query("SELECT post_id FROM blog_posts WHERE post_uri = 'the-test-post' LIMIT 1");
$row = $result->fetch_array();

and this gives me the post_id. However, if I insert a variable for post_uri, the result is empty. Ways I tried of which none worked:
$result = $mysqli->query("SELECT post_id FROM blog_posts WHERE post_uri = '".$post_uri."' LIMIT 1");

$result = $mysqli->query("SELECT post_id FROM blog_posts WHERE post_uri = ".$post_uri." LIMIT 1");

$result = $mysqli->query("SELECT post_id FROM blog_posts WHERE post_uri = $post_uri LIMIT 1");

I have similar query on another page working just right, so that confuses me even more. Help appreciated.

You are slapping a variable directly into a query. This is error prone (as you are discovering) and has a high risk that you'll fail to sufficiently sanitise it (and thus cause an SQL injection vulnerability).

0 comments:

Post a Comment