Skip to content
Advertisement

Μysql – Ηow to get first value from array after fetch in php

Hello i want to get the first value (uid) from the object that i fetch.

Here is the syntax

 $sql2 = "SELECT **uid,**notification_created,username,name,profile_pic,tour,email, api_signature,first_name,last_name, artisticBehaviour,location,bio,last_login,first_login,updates_count,friend_count,profile_views,group_count,password
        FROM users WHERE username=:username ";
        $stmt2 = $db->prepare($sql2);
        $stmt2->bindParam("username", $username, PDO::PARAM_STR);
        $stmt2->execute();
        $userData = $stmt2->fetch(PDO::FETCH_OBJ);
        $uid = ????????

I want to retrieve the first value (uid) so i may use it as a variable

Advertisement

Answer

First bind the result and then fetch them

you should test if the username is empty before using it

$sql2 = "SELECT uid,notification_created,username,name,profile_pic,tour,email, api_signature,first_name,last_name, artisticBehaviour,location,bio,last_login,first_login,updates_count,friend_count,profile_views,group_count,password
        FROM users WHERE username=:username ";
        $stmt2 = $db->prepare($sql2);
        $stmt2->bindParam("username", $username, PDO::PARAM_STR);
        $stmt2->execute();

$result = $stmt2->get_result();
if ($result->num_rows>0) {
    while ($row = $result->fetch_assoc()) {
        echo $row['uid'];
    }
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement