Page 1 of 1

MySQL Select Statement Not Working

Posted: Wed Jan 26, 2011 5:28 pm
by BillBillJr
Hey guys,

The following PHP / MySQL code...

Code: Select all

<?php
    $username = mysql_real_escape_string($_POST['username']);
    $password = mysql_real_escape_string($_POST['password']);

    $connection = mysql_connect('localhost', 'username', 'password');
    
    if (!$connection){
        die('Cannot connect to MySQL: ' . mysql_error() . '.');
    }
    
    $select = mysql_select_db('database', $connection);
    
    if (!$select){
        die('Cannot select database: ' . mysql_error() . '.');
    }
    
    $query = mysql_query("SELECT * FROM table WHERE username = '$username'");
    
    if (!$query){
        die('Cannot execute SQL: ' . mysql_error() . '.');
    }
    
    while ($row = mysql_fetch_assoc($query)){
        echo $row['username'] . '<br>';
        echo $row ['password'];
    }
?>
...produces this error...
Cannot execute SQL: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'table WHERE username = ''' at line 1.
Any ideas as how I can fix this?

Re: MySQL Select Statement Not Working

Posted: Wed Jan 26, 2011 5:54 pm
by VladSun
You are using MySQL keywords in your query ("table" is a keyword)
Put every table/field name in ``:

Code: Select all

SELECT * FROM `table` WHERE `username` = '$username'

Re: MySQL Select Statement Not Working

Posted: Wed Jan 26, 2011 11:11 pm
by BillBillJr
VladSun wrote:Put every table/field name in ``
I'm also using mysql_fetch_assoc on the results, how should I call the row's name?
i.e. $row[`username`], $row['username'], or $row["username"]?

Re: MySQL Select Statement Not Working

Posted: Thu Jan 27, 2011 5:07 am
by VladSun
The last 2.

Re: MySQL Select Statement Not Working

Posted: Thu Jan 27, 2011 10:18 pm
by BillBillJr
VladSun wrote:The last 2.
Thanks for your patience. Unfortunately, no matter which of the two I use, they still do not work.