Php 此代码是否可以防止SQL注入攻击&;为什么不起作用?

Php 此代码是否可以防止SQL注入攻击&;为什么不起作用?,php,mysql,Php,Mysql,我是PHP新手,不确定我的代码是否能阻止任何SQL攻击。而且,我也不明白为什么我不能登录。它没有给我任何错误 <?php $host="localhost"; // Host name $username="*****"; // Mysql username $password="****"; // Mysql password $db_name="***"; // Database name $tbl_name="electoral"; // Table name // Con

我是PHP新手,不确定我的代码是否能阻止任何SQL攻击。而且,我也不明白为什么我不能登录。它没有给我任何错误

    <?php
$host="localhost"; // Host name
$username="*****"; // Mysql username
$password="****"; // Mysql password
$db_name="***"; // Database name
$tbl_name="electoral"; // Table name

// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

// username and password sent from form
$username=$_POST['username'];
$password=$_POST['password'];

// To protect MySQL injection (more detail about MySQL injection)
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);

$sql="SELECT * FROM $tbl_name WHERE username='$username' and password= md5('$password')";
$result=mysql_query($sql);

// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row

if($count==1){
// Register $myusername, $mypassword and redirect to file "_____"

session_register("username");
session_register("password");
header("location:electoralcommission.php");
}

?>
stripslahes()<代码>mysql\u real\u escape\u string()
是首选,如果您要对字符串进行转义以防止注入


就个人而言,我建议您将PDO用于参数化查询。参数化查询比试图记住是否正确转义字符串要干净得多,再加上它至少与一些数据库和驱动程序组合(不确定具体是PHP),它将允许SQL服务器缓存查询的一部分,以获得更好的性能(另外,我怀疑mysql是否接近于快速!)。有关更多信息(或许多其他问题),请参阅。

这是您写的还是从某个地方复制的?您的代码是否真的在刚刚选中之前有空格all@Michael您甚至可以在哪里看到
会话\u start()
?这段代码是一堆乱七八糟的碎片。但是会发生什么呢?你有没有得到一个空白页面,相同的登录表单,等等?我不完全确定,但是MySQL的一些版本根本无法缓存准备好的语句。PDO默认情况下会模拟准备。叹气