如何在 PHP 中显示 MySQL Select 语句结果

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2668624/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 07:16:39  来源:igfitidea点击:

How to display MySQL Select statement results in PHP

phpsqlmysqlselect

提问by Vonder

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.

我有以下代码,它应该只从 mysql 表返回一个值(id)。以下代码不起作用。如何在不创建数组和所有这些东西的情况下输出它,只是一个值的简单输出。

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

回答by Levi Hackwith

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.

您必须进行某种形式的对象创建。没有办法解决这个问题。

回答by codaddict

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.

回答by Nazrul Muhaimin

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.

上面已经回答了很多方法,这只是我的简单示例。它将回显已执行的第一行,您也可以使用另一个选项(如限制子句)来执行与上面其他人回答相同的结果。

回答by AlexanderMP

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

你所拥有的只是一个资源,如果你想要输出,你仍然需要让它构造一个结果数组。

Check out ADOif you want to write less.

如果你想写得更少,请查看ADO

回答by Mikk

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