Vonder
Vonder

Reputation: 4059

How to display MySQL Select statement results in PHP

I have the following code and it should return just one value (id) from mysql table. The following code doesnt work. How can I output it without creating arrays and all this stuff, just a simple output of one value.

$query = "SELECT id FROM users_entity WHERE username = 'Admin' ";
$result = map_query($query);
echo $result;

Upvotes: 0

Views: 26833

Answers (5)

Nazrul Muhaimin
Nazrul Muhaimin

Reputation: 373

if you wish to execute only one row you can do like this.

$query = "SELECT id FROM users_entity WHERE username = 'Admin' ";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
echo $row[0];

there have been many ways as answered above and this is just my simple example. it will echo the first row that have been executed, you can also use another option like limit clause to do the same result as answered by others above.

Upvotes: 0

codaddict
codaddict

Reputation: 455440

You can try:

$query = "SELECT id FROM users_entity WHERE username = 'Admin' ";
//$result = map_query($query);
//echo $result;
$result = mysql_query($query); // run the query and get the result object.
if (!$result) { // check for errors.
    echo 'Could not run query: ' . mysql_error();
    exit;
}
$row = mysql_fetch_row($result); // get the single row.
echo $row['id']; // display the value.

Upvotes: 1

Mikk
Mikk

Reputation: 2229

Not sure I exactly understood, what you want, but you could just do

$result = mysql_query('SELECT id FROM table WHERE area = "foo" LIMIT 1');
list($data) = mysql_fetch_assoc($result);

Upvotes: 0

Alex
Alex

Reputation: 14648

all you have is a resource, you would still have to make it construct a result array if you want the output.

Check out ADO if you want to write less.

Upvotes: 0

Levi Hackwith
Levi Hackwith

Reputation: 9322

I do something like this:

<?php
    $data = mysql_fetch_object($result);
    echo $data->foo();
?>

You have to do some form of object creation. There's no real way around that.

Upvotes: 1

Related Questions