开发者

Error when printing results of SELECT FROM WHERE with PHP variable

EDIT: I had a typo in my original post....the issue is a bit more complicated...i had a 开发者_JAVA百科variable passed in not a raw string.

I want to print out stories from a mysql database that are specific to a certain person: so i have code that is similar to:

$stuff ="jamie"
    $query = "SELECT * FROM person_stories WHERE person =$stuff";
    $result = mysql_query($query) or die ("didnt work");
    while($row = mysql_fetch_array($result))
    {
    echo "<a href = 'PersonStoryPage.php?pid=$row[id]'>" .$row['title']. " </a>";
    }

I keep on getting "didnt work" ...I know that my table person_stories is empty but is this the same thing as an error? The table will obviously not always be empty so I need to be able to use this block of code to go about business.

Help is appreciated!

EDIT 2: The actual error is:

Unknown column 'jamie' in 'where clause'

This is bizzare since it shouldn't be interpreting jamie as the column!


You didn't put single quotes around jamie. Try this:

$query = "SELECT * FROM person_stories WHERE person = 'jamie'"

Edit:

I see the post has been edited. It should now change from this:

$stuff ="jamie"
$query = "SELECT * FROM person_stories WHERE person =$stuff";

to something like this:

$stuff ="jamie"
$query = "SELECT * FROM person_stories WHERE person='" . mysql_real_escape_string($stuff) . "'";

This will not only solve your SQL syntax error, but also protect your app from a nasty SQL injection vulnerability.


You need to quote the criteria value for the person field (notice apostrophes around jamie):

$query = "SELECT * FROM person_stories WHERE person = 'jamie'";

Edit:

Updated to match your update. If you use variables that may come from user input, then you will want to use mysql_real_escape_string to escape the value properly for the SQL query (helps prevent SQL injection).

$query = "SELECT * FROM person_stories WHERE person = '" . mysql_real_escape_string($stuff) . "'";


If you comparing with string, you have to enclose it with ''

try change

$query = "SELECT * FROM person_stories WHERE person =jamie";

to

$query = "SELECT * FROM person_stories WHERE person = 'jamie'";

and in my opinion, is better to modify this line:

echo "<a href = 'PersonStoryPage.php?pid=$row[id]'>" .$row['title']. " </a>";

to

echo "<a href = 'PersonStoryPage.php?pid=".$row['id']."'>" .$row['title']. " </a>";


You have an error in your query. You are missing double quotes new jamie try this

$query = 'SELECT * FROM person_stories WHERE person ="jamie"';
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜