[英]Inserting PHP variables into MySQL database using foreach loop
I have an array: $product_counts = array_count_values($product_array);
我有一个数组: $product_counts = array_count_values($product_array);
The keys for this array are merchant ID's and the values are integers (product counts). 此数组的键是商家ID,值是整数(产品计数)。 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. $ value变量的值不会进入MerchantID = $ key ....的字段,而是元组只是默认为null,这就是我设置它们要做的事情。 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. 您不能在insert语句中使用where子句。 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
而不是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) 无论如何使用PDO和准备声明会更好(至少更安全)
$stmt = $pdo->prepare("UPDATE merchantinfo set ProductCount=? WHERE MerchantID=?");
foreach($product_counts as $key => $value){
$stmt->execute(array($value, $key));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.