【发布时间】:2014-04-29 21:09:44
【问题描述】:
我提前为这段代码道歉,这实际上是我第一次尝试 PHP 和 SQL。我有两张桌子:
table contacts(
contact_id int(10)
contact_first_name varchar(30)
contact_last_name varchar(30)
contact_phone_number varchar(30)
contact_email_address varchar(255)
contact_comments text
contact_date_added datetime
);
table submissions(
submission_id int(10)
contact_id int(10)
submission_date datetime
);
联系人的主键是contact_id 提交的主键是 submit_id 提交的外键是contact_id
用户在表单中输入简单的联系人数据,表单被解析并将数据插入到联系人表中。我按照我想要的方式进行了这项工作,但是对于第二个表,没有可以从表单中插入的内容,并且我需要在插入到联系人表时使用最近提交的内容进行更新。
我正在使用 PDO,这就是我所在的位置:
class Contact
{
public $first_name;
public $last_name;
public $phone;
public $email;
public $comments;
function __construct($data)
{
$this->first_name = $data['firstName'];
$this->last_name = $data['lastName'];
$this->phone = $data['phone'];
$this->email = $data['email'];
$this->comments = $data['comments'];
}
}
$contact = new Contact($_POST);
try
{
$db_connection = new PDO('mysql:host=localhost:3306;dbname=userdata','root','');
$db_connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $exception)
{
$exception->getMessage();
}
$sql = "INSERT INTO contacts(contact_first_name, contact_last_name, contact_phone_number, contact_email_address, contact_comments) VALUES (:first_name, :last_name, :phone, :email, :comments)";
$query = $db_connection->prepare($sql);
$query->execute(array(':first_name'=> $contact->first_name, ':last_name'=> $contact->last_name, ':phone'=> $contact->phone, ':email'=> $contact->email, ':comments'=>$contact->comments));
【问题讨论】:
-
我会为这种类型的事情使用插入后触发器。不是php代码。我会举个例子,但我所有的东西都是 SQL Server。