Max
Max

Reputation: 37

PHP, MySQL table query syntax error?

I hope someone can help see what's wrong here: I have a form with two field EMAIL and PASSWORD that opens a php page where I intend to run a simple query on a table. I get an error message that makes no sense:
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 '@gmail.com' at line 1.
The email address I entered in this case did end with '@gmail.com'
Here's the code:

<?php
$dbhost = 'somewhere.net';
$dbuser = 'someUser';
$dbpass = 'pass';

$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');

$dbname = 'medreunten_db1';
mysql_select_db($dbname) or die(mysql_error($conn)); 

$email = mysql_real_escape_string($_POST['email']);

$query = "SELECT * FROM employee WHERE email = $email";
$result = mysql_query($query, $conn) or die (mysql_error($conn));
extract(mysql_fetch_assoc($result));  


while ($row = mysql_fetch_array($result)) {
extract($row);
echo $row['name'];
echo $row['surname'];
echo $row['age'];
}
?>

Any advice would be appreciated.

Upvotes: 2

Views: 7581

Answers (5)

Olli
Olli

Reputation: 752

Full fixed code:

<?php
$dbhost = 'somewhere.net';
$dbuser = 'someUser';
$dbpass = 'pass';

$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');

$dbname = 'medreunten_db1';
mysql_select_db($dbname) or die(mysql_error($conn)); 

$email = mysql_real_escape_string($_POST['email']);

$query = "SELECT * FROM employee WHERE email = '$email'";
$result = mysql_query($query, $conn) or die (mysql_error($conn));
extract(mysql_fetch_assoc($result));  


while ($row = mysql_fetch_array($result)) {
extract($row);
echo $row['name'];
echo $row['surname'];
echo $row['age'];
}
?>

Upvotes: 0

Bajrang
Bajrang

Reputation: 8629

Just single quote the variable '$email' because it varchar type value and field . As wrote, Darhazer :)

Upvotes: 0

klaustopher
klaustopher

Reputation: 6941

Your query translates to:

SELECT * FROM emloyee WHERE email = [email protected]

This doesn't work, you have to put strings in quotes. Change your code to the following and it will work:

$query = "SELECT * FROM employee WHERE email = '$email'";

Upvotes: 0

johannes
johannes

Reputation: 15969

You have to put the value in quotes inside SQL string.

$email = mysql_real_escape_string($_POST['email']);

$query = "SELECT * FROM employee WHERE email = '$email'";

(mind the extra '' around $email)

Upvotes: 0

Maxim Krizhanovsky
Maxim Krizhanovsky

Reputation: 26699

You are missing quotes around string fields:

$query = "SELECT * FROM employee WHERE email = '$email'";

Additionally,

extract(mysql_fetch_assoc($result));  

will fetch the first row from the database, so your while loop will start from the second row.

Upvotes: 6

Related Questions