MySQL Select Statement Not Working

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
BillBillJr
Forum Newbie
Posts: 9
Joined: Tue Aug 19, 2008 7:43 pm
Location: U.S.A.

MySQL Select Statement Not Working

Post 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?
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Re: MySQL Select Statement Not Working

Post 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'
There are 10 types of people in this world, those who understand binary and those who don't
BillBillJr
Forum Newbie
Posts: 9
Joined: Tue Aug 19, 2008 7:43 pm
Location: U.S.A.

Re: MySQL Select Statement Not Working

Post 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"]?
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Re: MySQL Select Statement Not Working

Post by VladSun »

The last 2.
There are 10 types of people in this world, those who understand binary and those who don't
BillBillJr
Forum Newbie
Posts: 9
Joined: Tue Aug 19, 2008 7:43 pm
Location: U.S.A.

Re: MySQL Select Statement Not Working

Post 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.
Post Reply