Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

This question already has an answer here:

I've been trying to convert my application from the old mysql syntax to PDO and it's been a real pain. Right now i'm having trouble as it seems like the same query using PDO is coming up empty as one that returned a full array using mysql_fetch_array

Here is the code for one of my functions:

//Get all contacts from DB
public function getContacts($regId) {
    try {
        $sql = "SELECT contacts FROM gcm_users WHERE gcm_regid = '$regId'";
        $resource = $this->db->query($sql);
        //$resource = mysql_query("SELECT contacts FROM gcm_users WHERE gcm_regid = '$regId'");      
        $resultArray = $resource->fetch(PDO::FETCH_ASSOC);
        $result = $resultArray[0];
        }

    catch (SQLException $e) {
        $output = 'Error fetching contacts: ' . $e->getMessage();
    }
    return $result;
}

The original mysql_query which worked fine is commented out. The error i'm currently receiving with this is:

Notice: Undefined offset: 0 in C:\xampp\htdocs\gcm\db_functions.php on line 197

Which leads to my

$result = $resultArray[0];

I looked up the error and it seems to be because the $resultArray is empty. I'm not used to using the PDO::FETCH_ASSOC instead of mysql_fetch_array, so i'm assuming the problem is in there somewhere.

share|improve this question

marked as duplicate by mario Jun 17 at 2:39

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1  
Why did you assume an indexed [0] array, instead of an associative ["contacts"]? And why aren't you using print_r() to verify your assumptions? –  mario Jun 17 at 2:33
    
Is $result meant to be a single contact, or an array of contacts? –  Mark M Jun 17 at 2:44

1 Answer 1

up vote 2 down vote accepted

You're using PDO::FETCH_ASSOC, which retrieves your result set row into an associative array (that is, an array with named elements like $resultArray['contacts'].

You seem to want a numbered array. Use PDO::FETCH_NUM instead to get that.

share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.