2

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

  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;      

        }
4

1 回答 1

4

Mysql 正是为此目的而具有强大的功能 - ON DUPLICATE 查询。
看起来像

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

等等。
只需确保您在关键字段上有一个唯一索引。
因此,您可以摆脱 SELECT 查询和结果检查。

于 2013-02-11T11:11:25.993 回答