开发者

mysqli query not working when variable 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");

开发者_JAVA百科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).

Use the PDO layer and bound variables.


If you put that query in a string and echo it, you can check what happens. There might be something wrong with that variable!

echo "SELECT post_id FROM blog_posts WHERE post_uri = '".$post_uri."' LIMIT 1";

And so on. I'll bet there's either nothing, or something you're not expecting in that $post_uri, because it shouldn't matter to mysql how you've build your query.


I had a similar problem. Your syntax looks fine. Try to use a simple version of the db connection call. Below are compared the version that worked (above) to the one that failed (below).

$sqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
$mysqli->real_connect('localhost', 'my_user', 'my_password', 'my_db')

I had use a variable in my query and had a $mysqli->real_connect db connection. That would not work. But when I switched to the new mysqli type I was surprised that the variable query did work.

I hope that works out for you.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜