我对 php 很陌生,我只是尝试写一个脚本,但它写得并不恰当,因为它很容易受到 SQL 注入(inject)的攻击。我打算对此进行改进,但这只有当我在 PHP 方面取得进展时才有可能。当我尝试从 Java (Android) 发布变量并使用它们查询数据库时,我当前遇到一个问题。但是该脚本执行了两次,我在数据库中发现了重复的记录。以下是脚本:
<?php
require 'DbConnect.php';
$Make = $_POST["Make"];
$Model = $_POST["Model"];
$Version= $_POST["Version"];
$FuelType= $_POST["FuelType"];
$Kilo = $_POST["Kilo"];
$Price= $_POST["Price"];
$Reg= $_POST["Reg"];
$Color= $_POST["Color"];
$Mdate= $_POST["Mdate"];
$Desc= $_POST["Desc"];
$Loc= $_POST["Loc"];
$Owners = $_POST["Owners"];
$Negot= $_POST["Negot"];
$Trans= $_POST["Trans"];
$AC= $_POST["AC"];
$car_lockk= $_POST["Lockk"];
$Sunroof= $_POST["Sunroof"];
$Window= $_POST["Window"];
$Seat= $_POST["Seats"];
$Stearing= $_POST["Stearing"];
$Music= $_POST["Player"];
$Wheels= $_POST["Wheel"];
$Sound= $_POST["Sound"];
$Drive= $_POST["Drive"];
$ID = $_POST["Seller_ID"];
$query2 = "INSERT INTO used_cars (make, model, version, color, \
manufacturing_date, km_driven, fuel_type, expected_price, \
negotiable, registration_place, no_of_owners, description, \
current_location, transmission, ac, sunroof, window, seats, \
stearing, player, wheels, sound_system, drive, car_lockk, seller_id) \
VALUES ('$Make', '$Model', '$Version', '$Color', '$Mdate', '$Kilo', \
'$FuelType', '$Price', '$Negot', '$Reg', '$Owners', '$Desc', '$Loc', \
'$Trans', '$AC', '$Sunroof', '$Window', '$Seat', '$Stearing', \
'$Music', '$Wheels', '$Sound', '$Drive', '$car_lockk', '$ID')";
if(mysql_query($query2)){
echo 'success';
//echo $Img
}else{
echo 'Fail';
}
?>
最佳答案
代码没有理由执行两次,除非您正在刷新页面,或者连接脚本中的某些内容导致它发生。
我的建议是放慢速度,你的脚本只有几行,但按照你原来的格式,它几乎可读。你在不同的位置有等号,无用的空白和不稳定的间距,我试图为SO观众编辑掉这些。
尝试第一次就把事情做好。放弃 mysql
语法,查找 mysqli
( documentation & examples ) 并使用面向对象的接口(interface)实现代码 - 这要简单得多。
您的固定代码将类似于:
<?php
// Create DB connection object
$mysqli = new mysqli("localhost","username","password","database");
// Get our POST variables
$make = $_POST["Make"];
... put them here ...
$id = $_POST["Seller_ID"];
// Create our base query and bind parameters
$query = $mysqli->prepare("INSERT INTO used_cars (make, ..., id) VALUES (?, ..., ?)");
$query->bind_param('s...i', $make, ..., $id);
if($query->execute()) { // Will return true on success
echo "Success";
} else {
echo "Fail";
}
?>
bind_param
的第一个参数是数据类型列表:s = string、i = int 等。您需要以正确的顺序正确列出这些数据类型。如果您需要帮助,请参阅文档。绑定(bind)参数完全消除了 SQL 注入(inject)攻击的可能性,是传递用户输入值时使用 MySQL 的首选方式。
在一个不相关的注释中,通常在 PHP 中我们以小写字母开头变量名称。大写字母保留用于类名称。
关于PHP - mySql 查询执行两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16236493/