如何通过PHP将数据插入嵌套表?

时间:2014-02-06 11:59:49

标签: php pdo

我认为这与PDO有关。

这是我的patientinfo表

patientid | name | age | email | address

这是我的备注表

patientid | remarksid | date | description

我想将数据INSERT到patientinfo和备注表,其中两个表的patientid将被同步。

问题是我不知道如何查询。这就是我所做的,但它给了我一个错误。

$query = "INSERT INTO patientinfo (name, age, email, address)
              VALUES (:name, :age, :email, :address);";

    $query_params = array(
            ':name'     => $_POST['name'],
            ':age'      => $_POST['age'],
            ':email'    => $_POST['email'],
            ':address'  => $_POST['address'],
    );

    $query = "INSERT INTO remarks (patient_id, description) VALUES (:patient_id, :remarks) WHERE remarks.patient_id = patientinfo.patient_id;";
    $query_params = array(':remarks' => $_POST['remarks']);

    try{
        $stmt = $dbname->prepare($query);
        $result = $stmt->execute($query_params);
    }

    catch(PDOException $ex){
            $response["success"] = 0;
            $response["message"] = $ex ;

            die(json_encode($response));
    }

我在patientinfo AUTOINCREMENT中做了patientid。 请!非常感谢你的帮助!

1 个答案:

答案 0 :(得分:1)

$query = "INSERT INTO patientinfo (name, age, email, address)
              VALUES (:name, :age, :email, :address);";

$query_params = array(
        ':name'     => $_POST['name'],
        ':age'      => $_POST['age'],
        ':email'    => $_POST['email'],
        ':address'  => $_POST['address'],
);

try{
    $stmt = $dbname->prepare($query);
    $stmt->execute($query_params);

    $patient_id = $dbname->lastInsertId();

    $query = "INSERT INTO remarks (patientid, description) VALUES (:patient_id, :remarks)";
    $query_params = array(':remarks' => $_POST['remarks'],':patient_id'=>$patient_id);

    $q = $dbname->prepare($query); 
    $q->execute($query_params);

}catch(PDOException $ex){
        $response["success"] = 0;
        $response["message"] = $ex ;

        die(json_encode($response));
}

你应该写那样的东西。请检查列名(patientid或patient_id?)