在 PHP/MySQL 中只获取一行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13791514/
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
Fetch only one row in PHP/MySQL
提问by wiredmark
Possible Duplicate:
mysql_fetch_array() expects parameter 1 to be resource, boolean given in select
simple question here.
简单的问题在这里。
I have a SELECT query
我有一个 SELECT 查询
SELECT FROM friendzone WHERE ID = '$editID'"
I am sure this is going to give me only one row as result, cause ID's can't be duplicate in my DB.
我确信这只会给我一行结果,因为 ID 在我的数据库中不能重复。
How can I access the column values?
如何访问列值?
$row = mysql_fetch_array($query);
I think this is useless since I don't have to make any array.. I have only one row!
我认为这是无用的,因为我不必制作任何数组..我只有一行!
If I don't put it into a While cicle, and try to do e.g.
如果我不把它放在一个 While cicle 中,并尝试做例如
.$row['ID'].
I get:
我得到:
mysql_fetch_array() expects parameter 1 to be resource, boolean given
Thanks in advance everyone.
提前谢谢大家。
回答by jan267
Please, don't use
mysql_*functions in new code. They are no longer maintained and the deprecation processhas begun on it. See the red box? Learn about prepared statementsinstead, and use PDOor MySQLi- this articlewill help you decide which. If you choose PDO, here is a good tutorial.
请不要
mysql_*在新代码中使用函数。它们不再被维护, 弃用过程已经开始。看到 红框了吗?了解准备好的语句,并使用 PDO或MySQLi-本文将帮助您决定哪个。如果您选择 PDO,这里有一个很好的教程。
Try with:
尝试:
$query = mysql_query("SELECT * FROM friendzone WHERE ID = '$editID'");
$row = mysql_fetch_array($query);
print_r($row);
MySQLi code:
MySQLi 代码:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli('host', 'username', 'password', 'database');
$stmt = $conn->prepare("SELECT * FROM friendzone WHERE ID = ?");
$stmt->bind_param("s", $editID);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
print_r($row);
回答by lupatus
Probably your $queryis equal falsebecause something went wrong, try mysql_error()to see whats wrong.
可能你$query是平等的,false因为出了问题,试着mysql_error()看看出了什么问题。
And 2 small advices:
以及 2 个小建议:
would be better to use
PDOodmysqlias mysql_* functions are deprecated.use at least
mysql_real_escape_string()to escape the value before putting it into SQL string
最好使用
PDOod,mysqli因为 mysql_* 函数已被弃用。在
mysql_real_escape_string()将值放入 SQL 字符串之前至少使用转义值
回答by DrinkJavaCodeJava
Since I don't know what columns your trying to select the general syntax for select is
因为我不知道您尝试选择 select 的一般语法是什么列
"SELECT column1, column2, column3 FROM friendzone WHERE ID ='$editID'"
Or if you want to select all columns just type
或者,如果您想选择所有列,只需键入
"SELECT * FROM friendzone WHERE ID = '$editID'"

