使用PDO将值插入2个或更多mysql表

时间:2013-12-13 05:58:27

标签: php mysql pdo insert

我有这段代码,其目的是在mysql中将值插入两个表(propects,emailsent)。我已按照Insert into 2 tables with PDO MySQL中的答案。但是,我很难在第二个表中保存相应的值。保存到第一个表(前景)似乎工作。我在这个网站上搜索答案,但无济于事。

我正在使用PDO。

所以我的问题是双重的:

  1. 是[A](调用插入表格中)有效代码吗?
  2. 如何使[B]有效将各自的值保存到第二个表(emailsent)中的相应键/列?
  3. if(isset($_POST['senderEmail'])) 
    {
          try
          {
        ...
    
    [A]      $q= "INSERT INTO 'prospects'('senderName', 'senderEmail', 'offer', 'dateTimeSent') 
            VALUES (:senderName, :senderEmail, :offer, :dateTimeSent);    
    
            INSERT INTO 'emailsent'('call_timeSched', 'call_time', 'contactTelSched', 'contactTel', 'fileAttach', 'emailTextbox') 
                VALUES (:call_timeSched, :call_time, :contactTelSched, :contactTel, :fileAttach, :emailTextbox)"; // inserting into EMAILSENT table 
    
            $query    = $dbh  ->prepare($q);
    
    [B]        $results  = $query->execute(array(
                ":senderName"=>$senderName,
                ":senderEmail"=>$senderEmail,
                ":offer"=>$offer,
                ":dateTimeSent"=>$dateTimeSent,
                ":call_timeSched"=>$call_timeSched,
                ":call_time"=>$call_time,
                ":contactTelSched"=>$contactTelSched,
                ":contactTel"=>$contactTel,
                ":fileAttach"=>$fileAttach,
                ":emailTextbox"=>$emailTextbox,
            ));
    
          }
            catch (PDOException $e)
          {
            $error = 'Error adding elements to database: ' . $e->getMessage();
            include 'error.html.php';
            exit();
          }
    
          exit();
        }
    

1 个答案:

答案 0 :(得分:0)

对我而言,我更喜欢使用它......

    "INSERT INTO emailsent VALUES (:call_timeSched, :call_time, :contactTelSched, :contactTel, :fileAttach, :emailTextbox)"; // inserting into EMAILSENT table 

注意U必须将所有数据库字段放在值中。