0

I have a page named details.php. Here is its code:

<?
$id = $_GET['id'];
?>

<?
$q = mysql_query("SELECT * FROM `db` WHERE id = $id ");
while($db = mysql_fetch_array($q)) {
?>

<p><?=$db['title']?> <br /> <?=$db['desc']?></p>
<? } ?>

So when I open in browser /details.php?id=1 it works. The paragraph tag shows me the information from id 1. So...

If I replace id with title, it will look like:

<?
$title = $_GET['title'];
?>

<?
$q = mysql_query("SELECT * FROM `db` WHERE title = $title ");
while($db = mysql_fetch_array($q)) {
?>

<p><?=$db['title']?> <br /> <?=$db['desc']?></p>
<? } ?>

If I type in browser /details.php?title=M (M is an existing column in mysql), it doesn't work. I got this error in paragraph: Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\mario\game.php on line 51

Where am I wrong?

Agi Hammerthief
  • 2,114
  • 1
  • 22
  • 38
John Smith
  • 99
  • 1
  • 1
  • 9
  • Firstly, don't use short open tags as this can confuse your server (eg, when you start working with XML) and is non-standard. Secondly, sanitise your input. – Agi Hammerthief Mar 13 '14 at 16:55
  • possible duplicate of [mysql\_fetch\_array() expects parameter 1 to be resource, boolean given in select](http://stackoverflow.com/questions/2973202/mysql-fetch-array-expects-parameter-1-to-be-resource-boolean-given-in-select) – John Conde Mar 18 '14 at 17:36

1 Answers1

2

Try

$q = mysql_query("SELECT * FROM `db` WHERE title = '" . $title . "'");

$title is a string so in query you have to wrap it in single quotes

This(mysql_*) extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. Switching to PreparedStatements is even more better to ward off SQL Injection attacks !

nanobash
  • 5,419
  • 7
  • 38
  • 56