-3

I need some help on a project I am working on. I am trying to make a 'simple' message system.

There is most likely a silly stupid little bug, but I cannot find it thanks in advance and here is my code:

<?

session_start();
require_once('connect.php');

$name = $_SESSION['name'];

$q = "SELECT * FROM pm WHERE to = '$name'";

$r = mysqli_query($link,$q);

if(mysqli_num_rows($r)>0) {

while($row = mysqli_fetch_array($r,MYSQLI_ASSOC)){
echo $row['to'];
echo $row['from'];
echo $row['message'];

}
}

?>

1 Answers1

3

You have an sql injection: see this question: How can I prevent SQL injection in PHP?

also, the quotation marks on the SELECT statement are wrong

"SELECT * FROM pm WHERE to = '$name"';

should be, and using ticks around the column name:

"SELECT * FROM pm WHERE `to` = '$name'";

Since you're using a MySQL reserved word being "to". More on that below.

You should probably get a better editor / IDE that supports syntax highlighting - as in your question, the highlighting is all messed up: What is the best IDE for PHP?

Also, you probably shouldn't use the word 'to' as a column name: its a reserved word: http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html (thanks :)

And we end up with

"SELECT * FROM pm WHERE recipient = '$name'";
Community
  • 1
  • 1
Jonathan
  • 1,554
  • 3
  • 16
  • 23
  • 1
    [Read my comment to the OP...](http://stackoverflow.com/questions/28201094/how-to-private-message-system-in-php#comment44768464_28201094) – Funk Forty Niner Jan 28 '15 at 19:53
  • Thank you everyone for your help but the page still comes out with this error:- Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in /home/u184691447/public_html/inbox.php on line 30 – Caolan Maguire Jan 28 '15 at 19:57
  • 1
    You're welcome @Jonathan - Ah, now the plot thickens. ^ – Funk Forty Niner Jan 28 '15 at 19:58
  • What that means @CaolanMaguire is that your query is not returning what you think it is, maybe not even running at all. You need to add some [MySQLi Error Checking](http://php.net/manual/en/mysqli.error.php) – Jay Blanchard Jan 28 '15 at 20:00
  • @CaolanMaguire -- http://php.net/manual/en/mysqli.query.php - your mysql query returns a bool – Jonathan Jan 28 '15 at 20:00
  • 1
    Oh! Fixed it! it seems the word 'to' in the database was reserved thanks everyone , you guys are great! – Caolan Maguire Jan 28 '15 at 20:02
  • 2
    @CaolanMaguire Always happy to help in any way we possibly can. You can now accept the answer. – Funk Forty Niner Jan 28 '15 at 20:04