简体   繁体   中英

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;

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.

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.

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.

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);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM