PHP PDO bindParam和PDOBindArray与MySQL IN条件

时间:2017-12-04 15:11:52

标签: php mysql pdo

我正在转换一个旧的MySQL查询以使用PHP PDO,并需要一些有关如何实现它的见解。 这是旧代码的示例。

$deleted = false;

// get the image(s)
$sql = "SELECT cat_image 
        FROM category
        WHERE cat_id ";

if (is_array($catId)) 
{
    $sql .= " IN (" . implode(',', $catId) . ")";
} 
else 
{
    $sql .= " = $catId";
}   

$result = dbQuery($sql);

if (dbNumRows($result)) 
{
    while ($row = dbFetchAssoc($result)) 
    {
        // delete the image file
        $deleted = @unlink(CATEGORY_IMAGE_DIR . $row['cat_image']);
    }   
}

return $deleted;

这是我的PDO示例,我正在努力创建同样的工作。 注意:在两个示例中,$ catId值可以是数组或(int)值。 如何创建sql语句并处理bindParam和PDOBindArray?

$deleted = false;

// get the image(s)
$sql = "SELECT cat_image 
        FROM category
        WHERE cat_id ";

if (is_array($catId)) 
{
    $sql .= " IN (" . implode(',', $catId) . ")";
} 
else 
{
    $sql .= " = $catId";
}   

$_stmt = $this->_dbConn->prepare($sql);
$_stmt->bindParam(":catId", $catId, PDO::PARAM_INT);  
$_stmt->execute();

$res = $_stmt->fetchAll(PDO::FETCH_ASSOC);    

if (count($res)) {
    while ($row = each($res)) {

        // delete the image file
        $deleted = @unlink(CATEGORY_IMAGE_DIR . $row['cat_image']);
    }   
}

return $deleted;

0 个答案:

没有答案