-1

I have a list (category) from table "courses". I want when user will choose the catery he wants, he will see the list of news (from table "news") with this category. So what i need is to save the name of category, so i can search in table "news" news with this category. but fuction mysql_query doesnt want to work, i dont know where is the problem here, it shows warning:

mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in list with categories:

 $conn = mysql_connect ("localhost", "root", "") or die ("Соединение не установлено!");
 mysql_select_db('university'); 
 mysql_query("SET NAMES 'utf8'"); 
 $res = mysql_query("SELECT * FROM courses");
 while($course = mysql_fetch_assoc($res)) {?>
 <tr>
 <td><?=$course['id']?></td>
 <td><a href="category_courses_detail.php?id=<?=$course['name']?>"><?=$course['name']?>     </td>
 </tr><?
 }?>
 </tbody></table>

list with results (with warning)

 <?php
 $conn = mysql_connect ("localhost", "root", "") or die ("Соединение не установлено!");
 mysql_select_db('university'); // выбор БД
 mysql_query("SET NAMES 'utf8'"); // кодировка
 $res = mysql_query("SELECT * FROM news WHERE course = {$_GET['id']}"); /* MISTAKE IS HERE*/
 var_dump($res) ;
 echo $_GET['id'];
 mysql_error();
 while($news = mysql_fetch_assoc($res)) {?>
 <table border="1" align="center" style="word-wrap: break-word;" width="80%"  cellspacing="0" cellpadding="1">
 <tr><th width="30">ID</th><th>Название</th></tr>
 <tr>
 <td><a href="detail.php?id=<?=$news['id']?>"><?=$news['id']?></td>
 <td><a href="detail.php?id=<?=$news['id']?>"><?=$news['program']?></td>
 </tr><?
 }?>
 </tbody></table>

because i'm using echo $_GET['id']; i see that it gets what i need (the name of category, but still doesn't work)

and yes, i know that use mysqli or pdo is more better

Thank u, it works now.

Vladlena
  • 17
  • 5
  • 1
    Missing quotes around {$_GET['id']} in your query? Also, never EVER create sql queries like this :) – mlask Jun 05 '14 at 08:14
  • omg yes, it works now – Vladlena Jun 05 '14 at 08:17
  • why u dont like my sql queries? – Vladlena Jun 05 '14 at 08:18
  • @Vladlena - it's because you're putting data from `$_GET` directly into your query. It's massively unsafe - you're not checking the data at all, so someone could effectively run whatever SQL they want in your database. You need to use bound parameters instead. – andrewsi Jun 06 '14 at 01:45

2 Answers2

1

If course is a string, it should be:

$id = mysql_real_escape_string($_GET['id']);
$res = mysql_query("SELECT * FROM news WHERE course = '$id'"); /* MISTAKE IS HERE*/

You need quotes around the string value, and you should escape the parameter to prevent SQL injection.

Barmar
  • 669,327
  • 51
  • 454
  • 560
0

Perform the SELECT Query like Below

 $res = mysql_query("SELECT * FROM news WHERE course = '{$_GET['id']}'");
Chirag Patel
  • 121
  • 6