php mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows 等...期望参数 1 是资源
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/2973202/
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
mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows etc... expects parameter 1 to be resource
提问by iamjonesy
I am trying to select data from a MySQL table, but I get one of the following error messages:
我正在尝试从 MySQL 表中选择数据,但收到以下错误消息之一:
mysql_fetch_array() expects parameter 1 to be resource, boolean given
mysql_fetch_array() 期望参数 1 是资源,布尔值给定
This is my code:
这是我的代码:
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query('SELECT * FROM Users WHERE UserName LIKE $username');
while($row = mysql_fetch_array($result)) {
    echo $row['FirstName'];
}
采纳答案by Edward Dale
A query may fail for various reasons in which case both the mysql_* and the mysqli extension will return falsefrom their respective query functions/methods. You need to test for that error condition and handle it accordingly.
查询可能因各种原因而失败,在这种情况下,mysql_* 和 mysqli 扩展都false将从各自的查询函数/方法返回。您需要测试该错误情况并相应地处理它。
NOTEThe mysql_ functions are deprecatedand have been removed in php version 7.
注:该mysql_功能已被弃用,并在PHP版本7已被删除。
Check $resultbefore passing it to mysql_fetch_array. You'll find that it's falsebecause the query failed. See the mysql_querydocumentation for possible return values and suggestions for how to deal with them.
$result在将其传递给 之前检查mysql_fetch_array。你会发现这是false因为查询失败了。有关mysql_query可能的返回值和如何处理它们的建议,请参阅文档。
$username = mysql_real_escape_string($_POST['username']);
$password = $_POST['password'];
$result = mysql_query("SELECT * FROM Users WHERE UserName LIKE '$username'");
if($result === FALSE) { 
    die(mysql_error()); // TODO: better error handling
}
while($row = mysql_fetch_array($result))
{
    echo $row['FirstName'];
}
mysqli extension
procedural style:
mysqli 扩展
程序风格:
$username = mysqli_real_escape_string($mysqli, $_POST['username']);
$result = mysqli_query($mysqli, "SELECT * FROM Users WHERE UserName LIKE '$username'");
// mysqli_query returns false if something went wrong with the query
if($result === FALSE) { 
    yourErrorHandler(mysqli_error($mysqli));
}
else {
    // as of php 5.4 mysqli_result implements Traversable, so you can use it with foreach
    foreach( $result as $row ) {
        ...
oo-style:
oo风格:
$username = $mysqli->escape_string($_POST['username']);
$result = $mysqli->query("SELECT * FROM Users WHERE UserName LIKE '$username'");
if($result === FALSE) { 
    yourErrorHandler($mysqli->error); // or $mysqli->error_list
}
else {
    // as of php 5.4 mysqli_result implements Traversable, so you can use it with foreach
    foreach( $result as $row ) {
      ...
using a prepared statement:
使用准备好的语句:
$stmt = $mysqli->prepare('SELECT * FROM Users WHERE UserName LIKE ?');
if ( !$stmt ) {
    yourErrorHandler($mysqli->error); // or $mysqli->error_list
}
else if ( !$stmt->bind_param('s', $_POST['username']) ) {
    yourErrorHandler($stmt->error); // or $stmt->error_list
}
else if ( !$stmt->execute() ) {
    yourErrorHandler($stmt->error); // or $stmt->error_list
}
else {
    $result = $stmt->get_result();
    // as of php 5.4 mysqli_result implements Traversable, so you can use it with foreach
    foreach( $result as $row ) {
      ...
These examples only illustrate whatshould be done (error handling), not how to do it. Production code shouldn't use or diewhen outputting HTML, else it will (at the very least) generate invalid HTML. Also, database error messages shouldn't be displayed to non-admin users, as it discloses too much information.
这些例子只是说明了什么应该做的(错误处理),而不是如何去做。or die输出 HTML 时不应使用生产代码,否则它会(至少)生成无效的 HTML。此外,不应向非管理员用户显示数据库错误消息,因为它会泄露太多信息。
回答by John Conde
This error message is displayed when you have an error in your query which caused it to fail. It will manifest itself when using:
当您的查询出现错误导致查询失败时,会显示此错误消息。它会在使用时表现出来:
- mysql_fetch_array/- mysqli_fetch_array()
- mysql_fetch_assoc()/- mysqli_fetch_assoc()
- mysql_num_rows()/- mysqli_num_rows()
- mysql_fetch_array/- mysqli_fetch_array()
- mysql_fetch_assoc()/- mysqli_fetch_assoc()
- mysql_num_rows()/- mysqli_num_rows()
Note: This error does notappear if no rows are affected by your query. Only a query with an invalid syntax will generate this error.
注意:如果您的查询没有影响任何行,则不会出现此错误。只有具有无效语法的查询才会产生此错误。
Troubleshooting Steps
故障排除步骤
- Make sure you have your development server configured to display all errors. You can do this by placing this at the top of your files or in your config file: - error_reporting(-1);. If you have any syntax errors this will point them out to you.
- Use - mysql_error().- mysql_error()will report any errors MySQL encountered while performing your query.- Sample usage: - mysql_connect($host, $username, $password) or die("cannot connect"); mysql_select_db($db_name) or die("cannot select DB"); $sql = "SELECT * FROM table_name"; $result = mysql_query($sql); if (false === $result) { echo mysql_error(); }
- Run your query from the MySQL command line or a tool like phpMyAdmin. If you have a syntax error in your query this will tell you what it is. 
- Make sure your quotes are correct. A missing quote around the query or a value can cause a query to fail. 
- Make sure you are escaping your values. Quotes in your query can cause a query to fail (and also leave you open to SQL injections). Use - mysql_real_escape_string()to escape your input.
- Make sure you are not mixing - mysqli_*and- mysql_*functions. They are not the same thing and cannot be used together. (If you're going to choose one or the other stick with- mysqli_*. See below for why.)
- 确保您已将开发服务器配置为显示所有错误。您可以通过在你的文件的顶部或在您的配置文件放上做到这一点: - error_reporting(-1);。如果您有任何语法错误,这将向您指出。
- 使用 - mysql_error().- mysql_error()将报告 MySQL 在执行查询时遇到的任何错误。- 示例用法: - mysql_connect($host, $username, $password) or die("cannot connect"); mysql_select_db($db_name) or die("cannot select DB"); $sql = "SELECT * FROM table_name"; $result = mysql_query($sql); if (false === $result) { echo mysql_error(); }
- 从 MySQL 命令行或类似phpMyAdmin的工具运行您的查询。如果您的查询中有语法错误,这将告诉您它是什么。 
- 确保您的报价是正确的。查询或值周围缺少引号可能会导致查询失败。 
- 确保你在逃避你的价值观。查询中的引号可能会导致查询失败(并且还会使您容易受到 SQL 注入的影响)。使用 - mysql_real_escape_string()逃脱你的输入。
- 确保你没有混合 - mysqli_*和- mysql_*功能。它们不是一回事,不能一起使用。(如果您要选择一个或另一个坚持使用- mysqli_*。请参阅下文了解原因。)
Other tips
其他提示
mysql_*functions should not be used for new code. They are no longer maintained and the community has begun the deprecation process.  Instead you should learn about prepared statementsand use either PDOor MySQLi. If you can't decide, this articlewill help to choose. If you care to learn, here is good PDO tutorial.
mysql_*函数不应用于新代码。它们不再被维护,社区已经开始弃用过程。相反,您应该了解准备好的语句并使用PDO或MySQLi。如果您无法决定,本文将帮助您做出选择。如果您想学习,这里有很好的 PDO 教程。
回答by nik
Error occurred here was due to the use of single quotes ('). You can put your query like this:
这里发生的错误是由于使用了单引号 ( ')。您可以像这样输入您的查询:
mysql_query("
SELECT * FROM Users 
WHERE UserName 
LIKE '".mysql_real_escape_string ($username)."'
");
It's using mysql_real_escape_stringfor prevention of SQL injection. 
Though we should use MySQLi or PDO_MYSQL extension for upgraded version of PHP (PHP 5.5.0 and later), but for older versions mysql_real_escape_stringwill do the trick.
它mysql_real_escape_string用于防止 SQL 注入。虽然我们应该使用 MySQLi 或 PDO_MYSQL 扩展来升级 PHP 版本(PHP 5.5.0 及更高版本),但对于旧版本mysql_real_escape_string就可以了。
回答by 2ndkauboy
As scompt.comexplained, the query might fail. Use this code the get the error of the query or the correct result:
正如scompt.com 所解释的,查询可能会失败。使用此代码获取查询错误或正确结果:
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query("
SELECT * FROM Users 
WHERE UserName LIKE '".mysql_real_escape_string($username)."'
");
if($result)
{
    while($row = mysql_fetch_array($result))
    {
        echo $row['FirstName'];
    }
} else {
    echo 'Invalid query: ' . mysql_error() . "\n";
    echo 'Whole query: ' . $query; 
}
See the documentation for mysql_query()for further information.
有关更多信息,请参阅文档mysql_query()。
The actual error was the single quotes so that the variable $usernamewas not parsed. But you should really use mysql_real_escape_string($username)to avoid SQL injections.
实际错误是单引号,因此$username未解析变量。但是你真的应该使用mysql_real_escape_string($username)来避免 SQL 注入。
回答by Matteo Riva
Put quotes around $username. String values, as opposed to numeric values, must be enclosed in quotes.
在 周围加上引号$username。与数字值相反,字符串值必须用引号括起来。
$result = mysql_query("SELECT * FROM Users WHERE UserName LIKE '$username'");
Also, there is no point in using the LIKEcondition if you're not using wildcards: if you need an exact match use =instead of LIKE.
此外,还有在使用没有意义LIKE,如果你不使用通配符条件:如果你需要一个精确匹配使用=,而不是LIKE。
回答by yasin
Please check once the database selected are not because some times database is not selected
请检查一次选择的数据库是不是因为有时没有选择数据库
Check
查看
mysql_select_db('database name ')or DIE('Database name is not available!');
before MySQL query and then go to next step
在 MySQL 查询之前,然后转到下一步
$result = mysql_query('SELECT * FROM Users WHERE UserName LIKE $username');
f($result === FALSE) {
    die(mysql_error());
回答by Chaitannya
Your code should be something like this
你的代码应该是这样的
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM Users WHERE UserName LIKE '$username'";
echo $query;
$result = mysql_query($query);
if($result === FALSE) {
    die(mysql_error("error message for the user")); 
}
while($row = mysql_fetch_array($result))
{
    echo $row['FirstName'];
}
Once done with that, you would get the query printed on the screen. Try this query on your server and see if it produces the desired results. Most of the times the error is in the query. Rest of the code is correct.
完成后,您将在屏幕上打印查询。在您的服务器上试试这个查询,看看它是否产生了想要的结果。大多数时候错误都在查询中。其余代码是正确的。
回答by derokorian
$result = mysql_query('SELECT * FROM Users WHERE UserName LIKE $username');
You define the string using single quotes and PHP does not parse single quote delimited strings. In order to obtain variable interpolation you will need to use double quotes OR string concatenation (or a combination there of). See http://php.net/manual/en/language.types.string.phpfor more information.
您使用单引号定义字符串,PHP 不会解析单引号分隔的字符串。为了获得变量插值,您需要使用双引号或字符串连接(或它们的组合)。有关更多信息,请参阅http://php.net/manual/en/language.types.string.php。
Also you should check that mysql_query returned a valid result resource, otherwise fetch_*, num_rows, etc will not work on the result as is not a result! IE:
此外,您应该检查 mysql_query 是否返回了有效的结果资源,否则 fetch_*、num_rows 等将不会对结果起作用,因为它不是结果!IE:
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query('SELECT * FROM Users WHERE UserName LIKE $username');
if( $result === FALSE ) {
   trigger_error('Query failed returning error: '. mysql_error(),E_USER_ERROR);
} else {
   while( $row = mysql_fetch_array($result) ) {
      echo $row['username'];
   }
}
http://us.php.net/manual/en/function.mysql-query.phpfor more information.
回答by Enis P. Agini?
This query should work:
此查询应该有效:
$result = mysql_query("SELECT * FROM Users WHERE UserName LIKE '%$username%'");
while($row = mysql_fetch_array($result))
{
    echo $row['FirstName'];
}
The problem is single quotes, thus your query fails and returns FALSE and your WHILE loop can't execute. Using % allows you to match any results containing your string (such as SomeText-$username-SomeText).
问题是单引号,因此您的查询失败并返回 FALSE 并且您的 WHILE 循环无法执行。使用 % 允许您匹配包含您的字符串的任何结果(例如 SomeText-$username-SomeText)。
This is simply an answer to your question, you should implement stuff mentioned in the other posts: error handling, use escape strings (users can type anything into the field, and you MUST make sure it is not arbitrary code), use PDOinstead mysql_connect which is now depricated.
这只是您问题的答案,您应该实现其他帖子中提到的内容:错误处理,使用转义字符串(用户可以在该字段中输入任何内容,并且您必须确保它不是任意代码),使用PDO代替 mysql_connect现在被贬低了。
回答by Dip Pokhrel
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query("SELECT * FROM Users WHERE UserName LIKE '%$username%'") or die(mysql_error());
while($row = mysql_fetch_array($result))
{
    echo $row['FirstName'];
}
Sometimes suppressing the query as @mysql_query(your query);
有时将查询抑制为 @mysql_query(your query);

