帮助将此mysql查询转换为PDO查询

时间:2011-03-24 17:29:04

标签: php pdo

我已经使用了一段时间,但从那时起升级到PDO而不是mysql查询。但我似乎无法让这个特定的片段完全起作用。

$query = mysql_query ($sql) or die (mysql_error());
while ($records = @mysql_fetch_array ($query)) {
    $alpha[$records['alpha']] += 1;
    ${$records['alpha']}[$records['id_clients']] = array(
        $records['first_name'],       //item[0]
    );
}

我试过这个

while ($records = $this->db->fetch_row_assoc($sql)) {
    $alpha[$records['alpha']] += 1;
    ${$records['alpha']}[$records['id_clients']] = array(
        $records['first_name'],       //item[0]
    );
}

我的PDO代码是

public function query($statement)
    {
        return self::$PDO->query($statement);
    }
public function fetch_row_assoc($statement) {
    self::$PDO->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
        try
        {
            $stmt = self::$PDO->query($statement); 
            $result = $stmt->fetch();
            return $result;
        }catch(PDOException $e){
            echo $e->getMessage();
        }
        return false;
        //return self::$PDO->query($statement)->fetch(PDO::FETCH_ASSOC);

    }

查询功能有效,但我已经介绍了我的fetch_row_assoc函数,希望我能用mysql_fetch_asso做同样的事情。

$sql = "SELECT 
                    SUBSTRING(`last_name`, 1, 1) AS alpha,
                    SUBSTRING(`middle_name`, 1, 1) AS subMiddleName,
                    `id_clients`,
                    `type`,
                    `first_name`,
                    `middle_name`,
                    `last_name`,
                    `address`,
                    `primary_number`,
                    `secondary_number`,
                    `home_number`,
                    `office_number`,
                    `cell_number`,
                    `fax_number`,
                    `ext_number`,
                    `other_number`,
                    `comments`
                FROM `clients`
                WHERE `user_id` = 1
                AND `is_sub` = 0
                AND `prospect` = 1
                ORDER BY `last_name`";

1 个答案:

答案 0 :(得分:0)

试试这个:

public function query($statement)
    {
        return self::$PDO->query($statement);
    }
public function fetch_row_assoc($statement) {
    self::$PDO->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
        try
        {
            $stmt = self::$PDO->query($statement); 
            $stmt->setFetchMode(PDO::FETCH_ASSOC);
            $result = $stmt->fetch();
            return $result;
        }catch(PDOException $e){
            echo $e->getMessage();
        }
        return false;
    }