我有一个应用程序从MySQL数据库中获取数据并将数据插入其中(用户正在编写正在插入的数据),老实说,我对php很新,并且对安全知之甚少和消毒字符串, 我想让php文件更安全,我不知道要做什么,如果有人可以发送教程,那就太棒了。
这里是选择和插入代码
<?php
header('Content-Type: text/html; charset=utf-8');
$db = "*********";
$username = "*********";
$password = "*******";
$host = "************";
$sql = "select * from sample;";
$conn = mysqli_connect($host,$username,$password,$db);
$conn->set_charset('utf8');
$result = mysqli_query($conn,$sql);
$response = array();
while($row = mysqli_fetch_array($result))
{
array_push($response,array($row[0],$row[1],$row[2]));
}
$str = json_encode(array($response),JSON_UNESCAPED_UNICODE);
$str = clean($str);
echo $str;
mysqli_close($conn);
function clean($string) {
$string = str_replace(' ', ' ', $string);
$string = preg_replace('/[^a-zA-Z0-9,×-×–, : . -]/', '', $string);
return preg_replace('/-+/', '-', $string);
}
?>
和插入:
<?php
$db = "*********";
$username = "*********";
$password = "*******";
$host = "************";
$conn = mysqli_connect($server_name,$mysql_username,$mysql_password,$db_name);
$name =$_POST["name"];
$publisher=$_POST["publisher"];
$date=$_POST["date"];
$sql_query = "insert into sample(name,publisher,date)
values('$name','$publisher','$date');";
if(mysqli_query($conn,$sql_query))
{
echo "data inserted";
}
else
{
echo "error";
}
?>
答案 0 :(得分:0)
随时使用准备好的陈述:
$sql_query = "insert into sample(name,publisher,date) values(?,?,?);";
$stmt = mysqli_prepare($conn,$sql_query);
mysqli_stmt_bind_param( $stmt , "sss" , $name,$publisher,$date);
mysqli_stmt_execute($stmt);
并尝试仅使用对象样式,而不是mysqli扩展的程序。
你在这里混合:
$conn = mysqli_connect($host,$username,$password,$db);//procedural style
$conn->set_charset('utf8');//oject style
答案 1 :(得分:0)
您可以使用PDO。构建安全的SELECT和INSERT查询非常简单。虽然,你必须小心一些命令,如ORDER BY。
<?php
$pdo = new PDO('mysql:host=localhost;dbname=databasename;charset=utf8', 'username', 'password');
$statement = $pdo->prepare("SELECT * FROM users WHERE firstname = :firstname AND lastname = :lastname");
$statement->execute(array(':firstname' => 'Max', ':lastname' => 'Mustermann'));
if( $statement->rowCount() > 0 ) {
$row = $statement->fetch();
echo "Hello " . $row['firstname'];
}
?>
也可以使用Mysqli,但请查看mysqli_real_escape_string。