PHP如果不是空行,请更新其他插入

时间:2013-02-11 10:54:02

标签: php mysqli

此代码有什么问题。如果表为空,我不能进入插入函数,它总是在进行更新。谁能帮我解决这个问题?

  while ($row = $result->fetch_object()) {

         if ($result->num_rows > 0) {

               $updatequery = sprintf("UPDATE stat_mailings SET cat_id='%s', mailing_name='%s', mailing_unique_id='%s', segment_id='%s', 
                                                                        campaign_id='%s', landing_page='%s', total_sent='%s' WHERE mailing_id='%s'",
                                        $row->category_id,
                                        mysqli_real_escape_string($mysqli, $row->mailing_naam),
                                        $row->unique_id,
                                        $row->mailing_segment,
                                        mysqli_real_escape_string($mysqli, $row->utm_campaign),
                                        mysqli_real_escape_string($mysqli, $row->landing_page),
                                        $row->mailing_total_sent, 
                                        $row->id                                           
                );

                 $mysqli->query($updatequery);
                 echo $error = $mysqli->error;   


        } else {

           $insertquery = sprintf("INSERT INTO stat_mailings SET mailing_id='%s', cat_id='%s', mailing_name='%s', mailing_unique_id='%s', segment_id='%s', 
                                                                        campaign_id='%s', landing_page='%s', total_sent='%s'",
                                        $row->id,
                                        $row->category_id,
                                        mysqli_real_escape_string($mysqli, $row->mailing_naam),
                                        $row->unique_id,
                                        $row->mailing_segment,
                                        mysqli_real_escape_string($mysqli, $row->utm_campaign),
                                        mysqli_real_escape_string($mysqli, $row->landing_page),
                                        $row->mailing_total_sent                                                                                       
                );

                 $mysqli->query($insertquery);
                 echo $error = $mysqli->error;      

        }

1 个答案:

答案 0 :(得分:4)

Mysql具有完全用于此目的的强大功能 - ON DUPLICATE查询 它看起来像

INSERT INTO t SET f1=val,f2=val2 ON DUPLICATE KEY UPDATE f1=val,f2=val2

等等。
只确保您在关键字段上有一个独特的索引 因此,您可以摆脱SELECT查询并进行结果检查。