2015-06-26 105 views
-1

我已经得到了正确插入的代码,但是我没有让它给我一个成功的消息。它总是返回无法将设备添加到数据库,但是然后我去检查数据库,它实际上是成功的。有任何想法吗?PDO插入验证

<?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

混合'pdo'和'mysql'in代码 – Saty

+0

'mysql_query' <=杀伤 –

+0

'PDOEException' <=错字 –

回答

1

您正在混合使用PDO和mysql扩展。不要这样做。

如果您要使用PDO,请正确使用prepare语句。你不应该把你的变量放到原始的SQL字符串中,而应该使用'?'您希望插入一个值。然后将一个变量数组传递给语句的执行。这是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)); 
+0

''?','<=那些会失败。 *“不要这样做。”*你正在传递字符串“?”。 –

+0

你是正确的弗雷德...我已编辑纠正,现在是时间喝咖啡。 – Omnilord