0

before open this i check in internet, try on my own, but without results, so i'm here.

I need to delete row from database using php script, but i can't use regex, like because this get also the value contain in my query (Example if i use like and said LIKE '%34%' query find values as 34 but also 340, 3445 so on every time there's 34 in a value).

So i find DELETE FROM ps_category_product WHERE ps_category_product.id_category = 1633 AND ps_category_product.id_product = 13018;

This query delete only id 13018 inside the category id 1633 and for me this is perfect, but i have 9000 id to delete so in simply impossible also try to insert this query direct inside DB sql.

So i think about a php script. that's it's my horror script: i insert in csv 2 column id category and id products but i don't know how insert this dynamic in script.

<?php
$hostname = "localhost";
    $dbname = "name";
    $user = "user";
    $pass = "50gSx!2j";
$csvData = file_get_contents('https://dev.campoelettrico.it/csv-update/test.csv');
$csvDelimiter = ';';

$csvLines = str_getcsv($csvData, "\n");
foreach($csvLines as &$row) {
    $row = str_getcsv($row, $csvDelimiter);
}
$pairings = [
    // sql field -> csv column
    'id_category' => 0,
    'id_product' => 1,
];

$pdo = new PDO("mysql:host=$hostname;dbname=$dbname", $user, $pass); // Connect to your database

$linesToImport = [];
foreach ($csvLines as $line) {
    $currentLine = [];
    foreach ($pairings as $sqlField => $csvColumn) {
        $currentLine[] = isset($line[$csvColumn]) ? $pdo->quote($line[$csvColumn]) : 'null';
    }
    $linesToImport[] = implode(', ', $currentLine);
}

**if (sizeof($linesToImport)) {
    $query = 'DELETE FROM `ps_category_product` (`' . implode('`, `', array_keys($pairings)) . '`) VALUES (' . implode('), (', $linesToImport) . ')';
    $pdo->exec($query);
}** **//this is the part that is wrong**
?>

How can i fix the last part of script to delete ONLY the id i insert and not all id that contain this value, only in correct id category?

Please save me. Enrico.

  • One option is to just run 9,000 DELETE statements. Another option is to use [`IN`](https://stackoverflow.com/a/15504114/231316) – Chris Haas May 19 '22 at 12:01
  • Hi, any idea about the code? I mean the theory it's ok but how? Thanks from Enrico. – Enrico Casadei May 19 '22 at 14:07
  • Here's [one version](https://3v4l.org/Ksc3B), and some more [here](https://stackoverflow.com/a/45905752/231316) and [here](https://stackoverflow.com/a/58355651/231316) using prepared statements. – Chris Haas May 19 '22 at 14:17
  • Hi, perfect but i need to know how implement on the script i post :) – Enrico Casadei May 19 '22 at 14:28

0 Answers0