-2

The following error occurs when i run the following query:

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;
    }
}
AGS
  • 14,118
  • 5
  • 48
  • 65
saad
  • 1

2 Answers2

2

You need quotations around the input in your where clause, and you cannot mix mysqli and 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;
    }
 }

Also you should put $subject_id through mysql_real_escape_string() or else your code may be vulnerable to SQL injection attacks.

(Disclaimer) The method you are using and my suggestion are very outdated and have been depreciated in php5.5 I suggest you look into prepared statements.

KHMKShore
  • 1,475
  • 9
  • 16
1

You can't mix the mysql and mysqli extensions. If you use mysqli_query, you have to use mysqli_fetch_assoc, not mysql_fetch_assoc.

Barmar
  • 669,327
  • 51
  • 454
  • 560