phpmysqldrupaldrupal-7zen-cart

Drupal to zen cart sql query conversion


I'm in the process of porting a Drupal module to Zen Cart and need to convert some sql queries. Due to the number of items that need to be converted I can't simply change one item and then test I've done it correctly, but I don't want to do them all and then find I made an error on every one. I've done a fair few OSCommerce to Zen Cart ports in the past, but this is my first attempt at a Drupal port.

The original Drupal code is

function getCustomerData($customerId) {

    $sql = "SELECT " . $this->fields['customer_firstname'] . " AS firstname, " . 
        $this->fields['customer_lastname'] . " AS lastname, " .
        $this->fields['customer_email'] . " AS email" .
        " FROM " . $this->tables['customers'] .
        " WHERE " . $this->fields['customer_id'] . " = '$customerId'";

    $query = $this->dbQuery($sql);

    if ($this->dbNumRows($query)) {
        $row = $this->dbFetchArray($query);
        $customerData = array(
            'firstname' => $row['firstname'],
            'lastname'  => $row['lastname'],
            'email'     => $row['email']
        );

    } else {
        $customerData = false;
    }

    return $customerData;
}

My best guess at a converted code would be

function getCustomerData($customerId) {
    global $db;

    $query = $db->Execute("SELECT customers_firstname AS firstname, customers_lastname AS lastname, customers_email AS email
                           FROM " . TABLE_CUSTOMERS . "
                           WHERE customers_id = ". $customerId ."");

    if ($query->RecordCount()){
        $customerData = array(
            'firstname' => $query->fields['firstname'],
            'lastname'  => $query->fields['lastname'],
            'email'     => $query->fields['email']
        );

    } else {
        $customerData = false;
    }

    return $customerData;
}

Any Drupal and Zen Cart experts here that can confirm if this is correct, or point me in the right direction if it isn't?


Solution

  • You're close - just tweaking the field names and casting the customer id as int. You also don't have to SELECT AS if you don't want to - you could just use the field names as they are and change them when setting up your array.

    function getCustomerData($customerId) { global $db;

    $query = $db->Execute("SELECT customers_firstname, customers_lastname, customers_email_address 
                           FROM " . TABLE_CUSTOMERS . "
                           WHERE customers_id = '". (int)$customerId ."'");
    
    if ($query->RecordCount()){
        $customerData = array(
            'firstname' => $query->fields['customers_firstname'],
            'lastname'  => $query->fields['customers_lastname'],
            'email'     => $query->fields['customers_email_address']
        );
    
    } else {
        $customerData = false;
    }
    
    return $customerData;
    

    }