user3055501 user3055501 - 11 months ago 53
MySQL Question

PHP and MySQL Select a Single Value

Sorry for such a basic question, but I haven't found a simple answer anywhere. I'd like to know how to select a single value from my mysql table. The table includes columns 'username' and 'id' amongst others ('id' is auto-increment and 'username' is unique). Given the username, I want to set a session variable

equal to the value in the 'id' column that corresponds to the given username. Here's the code that I've already tried:

$name = $_GET["username"];
$sql = "SELECT 'id' FROM Users WHERE username='$name'";
$result = mysql_query($sql);
$value = mysql_fetch_object($result);
$_SESSION['myid'] = $value;

So far I'm getting "Catchable fatal error: Object of class stdClass could not be converted to string." Casting
to type string does not fix the problem.

Answer Source

1) Don't use quotation in a field name or table name inside query.

2) After fetching object you need to access object attributes/properties (in your case id ) by attributes/properties name.

It should work
Bonus tips: Use limit 1 for this type of question will save execution time :)

$name = $_GET["username"];
$sql = "SELECT id FROM Users WHERE username='$name' limit 1";
$result = mysql_query($sql);
$value = mysql_fetch_object($result);
$_SESSION['myid'] = $value->id;

One note: please use mysqli_* or PDO since mysql_* deprecated.