0
我在我的網站上有註冊表單,我想我應該保護SQL注入。我不能讓那張桌子被惡意地丟棄。數據庫中沒有顯示SQL Real Escape字符串
使用POST,我從窗體收集輸入,檢查它,然後將它添加到數據庫中。我的代碼如下。我一直在測試表單,雖然表單已成功提交,但表格中填充了一個空行...而不是表單中的數據。
這是怎麼回事?
<?php
$type = $_POST['type']; // a dropdown
$color = $_POST['color']; // a dropdown
$name = mysql_real_escape_string($_POST['name']);
$address = mysql_real_escape_string($_POST['address']);
$city = mysql_real_escape_string($_POST['city']);
$state = $_POST['state']; // a dropdown
$zip = mysql_real_escape_string($_POST['zip']);
$phone = mysql_real_escape_string($_POST['phone']);
$email = mysql_real_escape_string($_POST['email']);
$where = mysql_real_escape_string($_POST['where']);
$price = mysql_real_escape_string($_POST['price']);
$use = mysql_real_escape_string($_POST['use']);
include 'php/Connect.php';
$ct = new Connect();
$con = $ct->connect();
if(check($email, $con)) {
if(register($type, $color, $name, $address, $city, $state, $zip, $phone, $email, $where, $price, $use, $con)) {
echo '<h1>Success!</h1><p>Thanks for registering your product. A confirmation email has been sent to '.$email.'.</p>';
}
else {
echo '<h1>Error!</h1><p>There were errors processing your registration. Please try again.</p>';
}
}
else {
echo '<h1>Error!</h1><p>This product has already been registered.</p>';
}
function check($email, $con) {
$query = "SELECT * FROM registrations WHERE email='$email'";
$res = mysql_query($query, $con);
if ($con) {
$row = mysql_fetch_assoc($res);
if($row) {
return false; // product registration exists
}
else {
return true; // product registration does not exist
}
}
else {
return false;
}
}
function register($type, $color, $name, $address, $city, $state, $zip, $phone, $email, $where, $price, $use, $con) {
$query = "INSERT INTO registrations VALUES ('$type', '$color', '$name', '$address', '$city', '$state', '$zip', '$phone', '$email', '$where', '$price', '$use')";
$res = mysql_query($query, $con);
if (!$con) {
return false;
}
else {
mysql_close($con);
return true;
}
}
?>
請不要使用'mysql_ *'函數獲取新代碼。他們不再被維護,社區已經開始[棄用流程](http://goo.gl/KJveJ)。請參閱[**紅框**](http://goo.gl/GPmFd)?相反,您應該瞭解[準備好的語句](http://goo.gl/vn8zQ)並使用[PDO](http://php.net/pdo)或[MySQLi](http://php.net/ mysqli的)。如果你不能決定,[本文](http://goo.gl/3gqF9)將有助於選擇。如果你關心學習,[這是一本很好的PDO教程](http://goo.gl/vFWnC)。 – PeeHaa 2012-07-12 15:59:12
^使用預準備語句和綁定參數,您不必擔心SQLi。 – PeeHaa 2012-07-12 16:00:00
試着迴應你正在生成的SQL,以確保它看起來像你所期望的。您還應該嘗試直接在數據庫中運行該SQL,以查看發生了什麼。 – andrewsi 2012-07-12 16:01:16