Search code examples
phpmysqlsqldatabaseuser-accounts

PHP and MySQL Select a Single Value


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 $_SESSION['myid'] equal to the value in the id column that corresponds to the given username. Here's the code that I've already tried:

session_start();
$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 $value to type string does not fix the problem.


Solution

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

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

    One note: please use mysqli_* or PDO since mysql_* deprecated. Here it is using mysqli:

    session_start();
    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
    $link = new mysqli('localhost', 'username', 'password', 'db_name');
    $link->set_charset('utf8mb4'); // always set the charset
    $name = $_GET["username"];
    $stmt = $link->prepare("SELECT id FROM Users WHERE username=? limit 1");
    $stmt->bind_param('s', $name);
    $stmt->execute();
    $result = $stmt->get_result();
    $value = $result->fetch_object();
    $_SESSION['myid'] = $value->id;
    

    Bonus tips: Use limit 1 for this type of scenario, it will save execution time :)