php mysql update rows where sku not in array
Get the solution ↓↓↓Solution:
Your query won't be correct, it will all be like a single value inWHERE
clause:
UPDATE `table` set status = "0" WHERE sku NOT IN ('452BA,7fDF-39r73,263941');
But you need quotes on both sides like:
UPDATE `table` set status = "0" WHERE sku NOT IN ('452BA','7fDF-39r73','263941');
Try like this:
$sql = 'UPDATE `table` set status = "0" WHERE sku NOT IN ("' . implode( '","', array_keys( $array) ) . '")';
Answer
Solution:
Alright, I think I understood your question :). You have a database with missing values in some of the rows. Where ever the rows are missing in the database, you would like to place the respective value from your array into the empty (NULL) cell in your database correct?
I recommend you first obtain an array of your table (only two columns needed). From that array you can create a foreach loop that will check if the value inside each specific sku slot is === NULL, and if so, run an SQL statement to fill in that slot.
1) Get the array:
$sql = "SELECT id, sku FROM table";
Im callingid
the value that corresponds to thekey
values of your array:Array ( [0] => 452BA [1] => 7fDF-39r73 [2] => 263941)
From there you fetch the array (lets call it$myArray
). Lets also call your previous array$myOtherArray
(Array ( [0] => 452BA [1] => 7fDF-39r73 [2] => 263941)
)
Then you create the following loop in php:
<?php
foreach ($myArray as $key => $value)
{
if ($myOtherArray[$key] === NULL)
{
$sql = "UPDATE table SET sku =".$value." WHERE id = ".$key;
//run the query
}
}
?>
let me know if that helped! :)
Answer
Solution:
@Michael, I think you are logically right but a slightly changes are required. Please see the following code:
$imp_arr = "'".implode( "','", array_keys( $array) )."'";
$sql = 'UPDATE `table` set status = "0" WHERE sku NOT IN (' . $imp_arr . ')';
Because at IN if any item is string then it would be surround by single / double quotation.
And one thing I was little bit confused, array_keys( $array) would be only $array.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: php undefined array key
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.