"Only process the first value of the MySQL IN array"
P粉921165181
P粉921165181 2023-09-01 12:53:15
0
2
491
<p>I am using PHP programming to create a PDO statement. </p> <p>The PDO preprocessing statement is as follows: </p> <p><code>Update `log` SET `id` = ? WHERE `id` IN ( ? );</code></p> <p><code>IN</code>The variable contents in the array are integers. </p> <p>The first <code>?</code> is a single integer. The second <code>?</code> is an array of integers, so I concatenate them into the string <code>1,2,3</code>, this string usually works for <code> IN</code>array. </p> <p>So the complete code is as follows: </p> <pre class="brush:php;toolbar:false;">public function mergeIDs($newID,$changeTheseIDs){ // (integer and array of integers, respectively) $inSet = implode(',',$changeTheseIDs); $query = $this->connect()->prepare("UPDATE `log` SET `id` = ? WHERE `id` IN ( ? );"); $query->execute([$newID,$changeTheseIDs]); }</pre> <p><strong>The problem seems to be that SQL only processes the first integer ID inserted into the <code>IN</code> array. </strong>Any ID that matches an integer in the <code>IN</code> array should be changed. </p> <p>If I run the SQL in the SQL tool on my server like this: </p> <p><code>UPDATE `log` SET `id` = 5 WHERE `id` IN (1,2,3);</code></p> <p>It works fine, I change all the ID's 1, 2 or 3 to 5. </p> <p>But my PDO version only changes 1 to 5, 2 and 3 remain the same. </p> <p>Any ideas? </p>
P粉921165181
P粉921165181

reply all(2)
P粉216203545

Try code like this:

public function mergeIDs($newID,$changeTheseIDs){ //(分别为整数和整数数组)
$mergeSet = array_merge([$newID],$changeTheseIDs);
$marks = array_fill(0, count($changeTheseIDs), '?');
$query = $this->connect()->prepare("UPDATE `log` SET `id` = ? WHERE `id` IN (". implode(',',  $marks) .");");
$query->execute($mergeSet);
}
P粉446800329

You need to prepare one ? for each integer in the IN clause, not just one.

public function mergeIDs($newID,$changeTheseIDs){ //(分别是整数和整数数组)
    $inPH = implode(',', array_fill(0, count($changeTheseIDs), '?'));
    $query = $this->connect()->prepare("UPDATE `log` SET `id` = ? WHERE `id` IN ( {$inPH} );");
    $query->execute([$newID, ...$changeTheseIDs]);
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template