在我的MYSQL表上意外插入了一行

时间:2012-03-31 12:39:29

标签: php sql database wordpress

我在桌面上插入值时遇到问题。

--------------------------------------------
|   products_id   |   related_products_ids |
| -----------------------------------------
|                |   1,2,3,4,6,            |
| -----------------------------------------
|    2            |   1,2,3,6,             |
| -----------------------------------------
|    3            |   1,2,4,               |
-------------------------------------------

有一个空白products_id值,其中每个产品ID上的所有插入值都在其related_products_ids值上。

我使用此代码,

for ($i=0; $i<count($_POST['rp_product']);$i++) {
    $check_val .= $_POST['rp_product'][$i];
    $check_val .=","; 
}

$insert_rp_ids1 = explode(',', $check_val);

foreach($insert_rp_ids1 as $rp_ids) {

    $related_query = "SELECT related_products_ids, products_id 
                      FROM ".TABLE_RELATED_PRODUCTS." 
                      WHERE products_id = '" . $rp_ids ."'";

    $result_rp = mysql_query($related_query);
    $related_products_value = mysql_fetch_assoc($result_rp);

    if(mysql_num_rows(mysql_query("SELECT products_id FROM ".TABLE_RELATED_PRODUCTS." WHERE products_id = '$rp_ids'"))){

        $rp_values = $related_products_value['related_products_ids'].$products_id.',';
        $rps_each1 = array('related_products_ids' => $rp_values);

        $wpdb->update( TABLE_RELATED_PRODUCTS, $rps_each1, array( 'products_id' => $rp_ids ));

     } else {

         $rps_each2 = array('products_id' => $rp_ids,
                   'related_products_ids' => $products_id.',');

         $wpdb->insert(TABLE_RELATED_PRODUCTS, $rps_each2);
     }
 }

我的代码有问题吗?我找不到它。那一行是没有必要的,没用。

请帮忙。

2 个答案:

答案 0 :(得分:2)

这是一团糟,但这应避免将来出现问题..

for ($i=0; $i<count($_POST['rp_product']); $i++)
{
  $check_val1 .= $_POST['rp_product'][$i] .","; //gather data
}
$check_val = trim($check_val1, ',');  //clean last ,
unset($check_val1); //flush

$insert_rp_ids1 = explode(',', $check_val);

foreach($insert_rp_ids1 as $rp_ids)
{

 if($result_rp = mysql_query("SELECT related_products_ids, products_id FROM ".TABLE_RELATED_PRODUCTS." where products_id = '" . $rp_ids ."'"))
 {
    if($products_id > 0)
   {
  $related_products_value = mysql_fetch_assoc($result_rp);
  $rp_values = $related_products_value['related_products_ids'] . "," . $products_id;

  $rps_each1 = array('related_products_ids' => $rp_values);
  $wpdb->update( TABLE_RELATED_PRODUCTS, $rps_each1, array( 'products_id' => $rp_ids ));
   }
  }
  else
  {
   if($rp_ids > 0 && $products_id > 0)
   {
   $rps_each2 = array('products_id' => $rp_ids, 'related_products_ids' => $products_id);
   $wpdb->insert(TABLE_RELATED_PRODUCTS, $rps_each2);
   }
  }
 }

答案 1 :(得分:0)

我在perl上看到这个数组初始化。初始化数组时,有时会使用null zeroeth元素创建它,具体取决于数组的声明方式。

尝试使用perl调试器(perl -D)运行并检查插入数组,或者包含Data :: Dumper并打印整个数组。