2012-09-27 12:18
浏览 248


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

图片转代码服务由CSDN问答提供 功能建议

我有一个数组: $ product_counts = array_count_values($ product_array);

此阵列的键是商家ID,值是整数(产品计数)。 所以,如果我要编写以下代码:

  foreach($ product_counts as $ key => $ value){
 echo“key:$ key”; 
  echo“value:$ value”; 

我会得到以下内容(这就是我想要的): < pre> key:26816928 value:13 key:26816931 value:2 ... X数组中的索引数量。


  foreach($ product_counts as $ key =&gt;  ; $ value){
 mysql_query(“INSERT INTO merchantinfo(ProductCount)VALUES $ value WHERE MerchantID = $ key”);  

$ value变量的值不会进入MerchantID = $ key ....的字段,而是元组默认为null 这就是我设定他们要做的事情。 我相信这可能是需要将变量类型转换为整数的情况....但我总体上对此非常失败。


  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dongqiu9018
    dongqiu9018 2012-09-27 12:22

    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");
    点赞 评论
  • duanqi6274
    duanqi6274 2012-09-27 12:21

    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
    点赞 评论
  • duanniu3385
    duanniu3385 2012-09-27 12:26

    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));
    点赞 评论