0

I am converting an old MySQL query to use PHP PDO and need some insight on how to go about it. Here's the example of the old code.

$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;

And here is my PDO example that I am trying to create to do the same job. Note: in both examples $catId value could be an array or an (int) value. How do I go about creating the sql statement and handing of the bindParam and 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;
Carl Barrett
  • 209
  • 5
  • 16
  • https://phpdelusions.net/pdo#in – RiggsFolly Dec 04 '17 at 15:14
  • You might make life easier for yourself if `$catId` was always an array. If there's a single value, just have one entry in the array (`...WHERE cat_id IN (5)...` is perfectly valid SQL equivalent to `...WHERE cat_id = 5...`.) – Matt Gibson Dec 04 '17 at 15:14
  • 1
    btw, your loop approach is outdated as well. with PDO you can do `foreach ($stmt as $row) {` right after execute, without fetchAll, count, while and each – Your Common Sense Dec 04 '17 at 15:15

0 Answers0