MYSQLI query to get one single result [duplicate]

2019-02-15 22:26发布

问题:

This question already has an answer here:

  • Single Value Mysqli 8 answers

I need to get only the id of member who's username is X from the mysql database. Can this only be done with a while loop or is there any other way around this?

What I'm thinking of is something like:

$id = mysqli_query($con,'SELECT id FROM membrs WHERE username = '$username' LIMIT 1)

Thanks,

回答1:

You can use:

mysqli_fetch_array();

// For Instance

$id_get = mysqli_query($con, "SELECT id FROM membrs WHERE username='$username' LIMIT 1");

$id = mysqli_fetch_array($id_get);

echo $id['id']; // This will echo the ID of that user

// What I use is the following for my site:

$user_get = mysqli_query($con, "SELECT * FROM members WHERE username='$username'");

$user = mysqli_fetch_array($user);

echo $user['username']; // This will echo the Username

echo $user['fname']; // This will echo their first name (I used this for a dashboard)


回答2:

without while loop we can do it by the following code, if you are selecting more than 1 record you need to loop it

$row = mysqli_fetch_array($id);
echo $row['id'];