-2

当我运行以下查询时发生以下错误:

Warning: mysql_fetch_assoc() expects parameter 1 to be resource

function get_subject_by_id( $subject_id ) {
    global $connection;
    $query  = "SELECT * ";
    $query .= "FROM subjects ";
    $query .= "WHERE id=" . $subject_id ." ";
    $query .= "LIMIT 1"; 
    $result_set = mysqli_query( $connection, $query );
    confirm_query( $result_set );
    /* @var $subject type */
    if ( $subject = mysql_fetch_assoc( $result_set ) ) {
       return $subject;
    } else {
       return NULL;
    }
}
4

2 回答 2

2

您需要在 where 子句中的输入周围加上引号,并且不能混合使用 mysqli 和 mysql。

function get_subject_by_id($subject_id) {
    global $connection;
    $query  = "SELECT * ";
    $query .= "FROM subjects ";
    $query .= "WHERE id='" . $subject_id ."' "; //The problem is here, you need quotations around your variable
    $query .= "LIMIT 1"; 
    $result_set = mysql_query( $connection, $query ); //Edit: Barmar is right, you can't mix mysqli and mysql
    confirm_query($result_set);
    /* @var $subject type */
    if ($subject == mysql_fetch_assoc($result_set)) {
        return $subject;
    } else {
        return NULL;
    }
 }

此外,您应该通过 mysql_real_escape_string() 输入 $subject_id,否则您的代码可能容易受到SQL 注入攻击

(免责声明)您使用的方法和我的建议非常过时,并且在 php5.5 中已贬值,我建议您查看准备好的语句

于 2013-10-10T00:38:14.603 回答
1

您不能混合使用mysqlmysqli扩展名。如果你使用mysqli_query,你必须使用mysqli_fetch_assoc,而不是mysql_fetch_assoc

于 2013-10-10T00:36:52.003 回答