【问题标题】:Insert values to 2 or more mysql tables using PDO使用 PDO 将值插入 2 个或更多 mysql 表
【发布时间】:2013-12-13 05:58:26
【问题描述】:

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

我正在使用 PDO。

所以我的问题有两个:

  1. [A](调用插入表格)是有效代码吗?
  2. 如何使 [B] 有效以将相应的值保存到第二个表(电子邮件发送)中的相应键/列?

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();
    }

【问题讨论】:

    标签: php mysql pdo insert


    【解决方案1】:

    对我来说,我更喜欢使用这个...

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

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

    【讨论】:

    • 我还没有测试过,但是如果表单用户将字段留空,这段代码可以工作吗?那么在所有领域都使用默认值是一个好习惯吗?还有,会不会影响[B]?
    • 这有助于最小化sql查询的过程。只要您记住您的字段,就可以使用它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-25
    • 2013-06-13
    • 2014-08-08
    • 2011-08-06
    • 1970-01-01
    • 2020-11-07
    • 1970-01-01
    相关资源
    最近更新 更多