简体   繁体   中英

Inserting PHP variables into MySQL database using foreach loop

I have an array: $product_counts = array_count_values($product_array);

The keys for this array are merchant ID's and the values are integers (product counts). So if I was to write the following code:

foreach($product_counts as $key => $value){
    echo "key: $key";
    echo "value: $value";
        }

I would get the following (which is what I want):

key: 26816928 value: 13
key: 26816931 value: 2 ... 
X the amount of indexes in the array. 

However if I was to write the following code:

foreach($product_counts as $key => $value){
    mysql_query("INSERT INTO merchantinfo(ProductCount) VALUES $value WHERE MerchantID = $key"); 
}

The values of the $value variable don't go into the field where MerchantID = $key....instead the tuples just default to null, which is what I've set them to do. I believe this could be a case of needing to type cast the variable as integers .... but I'm in general quite lost with this.

Thanks in advance

You cannot use a where clause in an insert statement. I think you want to use update instead.

mysql_query("update merchantinfo set ProductCount= $value WHERE MerchantID = $key");

Take values in () too, like:

INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);

And in your case you must use UPDATE instead of INSERT

UPDATE merchantinfo SET ProductCount = $value WHERE MerchantID = $key

It looks like you want to update value not insert: That should work for you:

$query = "UPDATE merchantinfo set ProductCount='$value' WHERE MerchantID='$key'";

If you want insert new row then:

$query = "INSERT INTO merchantinfo(ProductCount,MerchantID) VALUES('$value','$key')";

Anyway would be much better to use PDO and prepare statement (at least safer)

$stmt = $pdo->prepare("UPDATE merchantinfo set ProductCount=? WHERE MerchantID=?");
foreach($product_counts as $key => $value){
    $stmt->execute(array($value, $key));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM