如何编写准备好的插入语句?

时间:2016-02-10 12:12:42

标签: php pdo

我试图学习如何编写PDO插入语句,如果代码不太好,请道歉,它会出现错误:

SQLSTATE [42000]:语法错误或访问冲突:1064 在第3行

但我不明白为什么它不起作用。

注意:我试图将html输入数据传递到数据库,并在网上准备好的语句中说出如下内容:

$firstname = "John";
$lastname = "Doe";
$email = "john@example.com";

$ variable与数据库字段名称有关,但是如何在html输入字段中引用该名称?

代码可以在这里和下面找到:http://pastebin.com/fjAy1Fvn

<?php
include_once 'dbconnect.php';  
   if(isset($_POST["update_vacancies"])){       

    try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // begin the transaction
    $conn->beginTransaction();
    // our SQL statements
   $conn->exec("INSERT INTO vacancies (vac_id, vac_post_date, vac_job_title, vac_comp_name, vac_ess_one, vac_ess_two, vac_ess_three, vac_ess_four, vac_ess_five, vac_ess_six, vac_ess_seven, vac_ess_eight, vac_ess_nine, vac_ess_ten,  vac_des_one, vac_des_two, vac_des_three, vac_des_four, vac_des_five, vac_des_six, vac_des_seven, vac_des_eight, vac_des_nine, vac_des_ten, add_info) 

   VALUES ('vacData', 'postaDate', 'jobTitle', 'companyNanme', 'vac_ess_one', 'vac_ess_two', 'vac_ess_three', 'vac_ess_four', 'vac_ess_five', 'vac_ess_six', 'vac_ess_seven', 'vac_ess_eight', 'vac_ess_nine', 'vac_ess_ten', ,'vac_des_one' ,'vac_des_two' ,'vac_des_three' ,'vac_des_four' ,'vac_des_five' ,'vac_des_six' ,'vac_des_seven' ,'vac_des_eight' ,'vac_des_nine' ,'vac_des_ten' ,'add_info'  )");


// commit the transaction
$conn->commit();
echo "New vacancy created successfully";
}
catch(PDOException $e)
{
// roll back the transaction if something failed
$conn->rollback();
echo "Error: " . $e->getMessage();
}
}

$conn = null;
?>

真的很感激任何帮助。

1 个答案:

答案 0 :(得分:1)

你可以编写一个这样的预备插入语句:

<?php
$queryInsert = $conn->query('INSERT tableName (`example`, `exampleInt`) VALUES  (:example, :exampleInt)');

try{
    $queryInsert->execute([
         ':example'    => $example,
         ':exampleInt' => (int)$exampleInt
    ]);
}
catch(PDOException $e){
    echo $e->getMessage(); //Remove this when done testing and put your own error message here.
}
?>