1

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.

2
  • 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? Commented Jun 17, 2014 at 2:33
  • Is $result meant to be a single contact, or an array of contacts? Commented Jun 17, 2014 at 2:44

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments