我已经有正确插入的代码,但我没有让它给我一个成功的消息。它总是返回无法将设备添加到数据库,但后来我去检查数据库,它实际上是成功的。有什么想法吗?
<?php
// Start or resume the session
session_start();
//Check to ensure the user is authorized to view this page
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) {
// Include Header
include("includes/header.php");
echo "
<div class='form_description'>
<h2>French Lick Resort</h2>
<p>STATUS - Add Ingenico Device to Inventory</p>
</div>
<form id='update' class='fieldset' method='post' action=''>";
$serial=$_POST['serial'];
$model=$_POST['model'];
$deviceCondition=$_POST['deviceCondition'];
$sealCondition=$_POST['sealCondition'];
$location=$_POST['location'];
$deployDate=$_POST['deployDate'];
$weight=$_POST['weight'];
$notes=$_POST['notes'];
//NEW PDO connection
try{
$conn = new PDO("mysql:host=$sql_server;dbname=$sql_db", $sql_user, $sql_pass);
$sql = "INSERT INTO web01dev4s2.ingenicoInfo (serial, model, deviceCondition, sealCondition, location, deployDate, weight, notes) VALUES ('".$serial."', '".$model."', '".$deviceCondition."', '".$sealCondition."', '".$location."', '".$deployDate."', '".$weight."', '".$notes."')";
$q = $conn->prepare($sql);
$result_1=mysql_query($sql);
$q->execute();
}
catch (PDOEException $pe) {
die("Could not connect to the database" . $pe->getMessage());
}
//End pdo connection
// Display "GO" or "NO GO"
if($result_1){
echo "Device successfully added to the database.";
header( "refresh:2;url=devicelist.php" );
}
else {
echo "Failed to add the device to the database. Please ensure that the device is not already in the database and that all fields are filled out. Notes should be NA if there are no notes to add. Also, ensure the name does not containt any special characters such as quotes.<br />";
Echo "<a href=create.php>Back</a>" ;
}
}
else {
header('Location:login.php');
}
echo "
</form>
</div>
</body>
</html>";
?>
答案 0 :(得分:1)
您正在混合使用PDO和mysql扩展。别这么做。
如果您要使用PDO,请正确使用prepare语句。您不应该将变量放入原始SQL字符串中,而应使用&#39;?&#39;您希望插入值的位置。然后将一组变量传递给语句的执行。这是PDO方式,它将有助于防止SQL注入您的代码。
$sql = "INSERT INTO web01dev4s2.ingenicoInfo (serial, model, deviceCondition, sealCondition, location, deployDate, weight, notes) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
$q = $conn->prepare($sql);
// This line should fix your problem
$result_1 = $q->execute(array($serial, $model, $deviceCondition, $sealCondition, $location, $deployDate, $weight, $notes));