James Chen
James Chen

Reputation: 873

How to select a single value in DB

I want to select a single value not an array, so I use

$user = "SELECT Name FROM Manager WHERE Statue = 1";
echo "<ul id='man-nav' class='navline pull-right'><li><a href='#'>".$user."</a></li></ul>";

or I tried

$user = mysqli_query($con,"SELECT Name FROM Manager WHERE Statue = 1");
echo "<ul id='man-nav' class='navline pull-right'><li><a href='#'>".$user."</a></li></ul>";

both are not correct, I am just not sure which function to take this value.

Could someone help me? Thanks

Upvotes: 2

Views: 123

Answers (3)

juco
juco

Reputation: 6342

As per the docs on mysqli_query(), you will get a mysql_result upon success, so you can either use mysqli_result::fetch_array() or mysqli_result::fetch_assoc(). Something similar to:

$res = mysqli_query($con, 'SELECT Name FROM manager WHERE Statue = 1');
while($row = $res->fetch_assoc()) {
   echo $row['Name'];
}

Upvotes: 0

Rudie
Rudie

Reputation: 53871

You should use PDO instead of mysql(i) functions and then you can use fetchcolumn.

Obviously this is just my opinion.

I say should because PDO is very safe (no more SQL injection!) and it's one interface for all drivers: easy. It also adds easy features like fetchColumn() and the class is easily extendable. Using 1 object for all db access is so much easier. Invest 20 minutes now and forever enjoy.

Upvotes: 1

Mitesh Ashar
Mitesh Ashar

Reputation: 153

Your second example is closer to being correct.

After running the query, you need to retrieve the values.

I strongly suggest that you go through the documentation and examples at http://www.php.net/manual/en/mysqli-result.fetch-object.php

Upvotes: 0

Related Questions