0

I am trying to fetch a single value (the id) from a mysql database in PHP. I know this can be done in the following way:

$q = "SELECT * FROM users WHERE email ='" . $email . "'";
$result = $conn->query($q);
$row = $result->fetch_assoc();
echo $row["id"];

However, I would think that I could speed up the query by instead of querying the entire row, I would only make a query for the id, which I would do like so:

$q = "SELECT 'id' FROM users WHERE email ='" . $email . "'";
$result = $conn->query($q);
$row = $result->fetch_assoc();
echo $row["id"];

But for some reason, this returns the string "id", instead of the actual value. I have looked at a couple other similar questions, and the answers that I've tried from those gave the exact same result.

  • 1
    remove single quotes arround column name . if use single quotes .it consider as string . column name and table name should be enclosed by back ticks – JYoThI May 06 '17 at 12:28
  • Remove the single quotes around `id` in the query string – Clive May 06 '17 at 12:28
  • 1
    Use backticks instead of quotes to escape the identifier. – Sirko May 06 '17 at 12:28
  • They should be backticks instead, i.e .\`id\`. 'id' and \`id\` are two very different things. Also you should be [using parametric queries to avoid SQL injection attacks](http://bobby-tables.com/php). – Luke Briggs May 06 '17 at 12:28

3 Answers3

2

But for some reason, this returns the string "id", instead of the actual value.

That's because you're wrapping the column id in single quotes. Use backticks instead, like this:

$q = "SELECT `id` FROM users WHERE email ='" . $email . "'";
Rajdeep Paul
  • 16,887
  • 3
  • 18
  • 37
1

use back-tick instead of single'or double"` quotes

$q = "SELECT `id` FROM users WHERE email ='" . $email . "'";

Check this for more detail : When to use single quotes, double quotes, and backticks in MySQL

Community
  • 1
  • 1
Niklesh Raut
  • 34,013
  • 16
  • 75
  • 109
0

Remove single quotes arround column name . if use single quotes .it consider as string . column name and table name should be enclosed by back ticks

"SELECT `id` FROM users WHERE email ='" . $email . "'"
JYoThI
  • 11,977
  • 1
  • 11
  • 26