使用mysql_real_esacape_string后sql查询无法正常工作

时间:2014-07-15 10:55:42

标签: php sql

这段代码不起作用:

$un_name=$_POST[name];
$un_idno=$_POST[idno];
$un_hostel=$_POST[hostel];
$un_mode=$_POST[mode];
$un_date=$_POST[date];  
$un_time=$_POST[time];
$un_tfno=$_POST[tfno];
$un_contact=$_POST[contact];

$sa_name=mysql_real_escape_string ($un_name);   
$sa_idno=mysql_real_escape_string ($un_idno);
$sa_hostel=mysql_real_escape_string ($un_hostel);
$sa_mode=mysql_real_escape_string ($un_mode);
$sa_date=mysql_real_escape_string ($un_date);
$sa_time=mysql_real_escape_string ($un_time);
$sa_tfno=mysql_real_escape_string ($un_tfno);
$sa_contact=mysql_real_escape_string ($un_contact);

$sql="INSERT INTO cabs (NAME,IDNO,HOSTEL,MODE,DATE,TIME,TFNO,CONTACT)
VALUES
('$sa_name','$sa_idno','$sa_hostel','$sa_mode','$sa_date','$sa_time','$sa_tfno','$sa_contact')";

虽然正常插入的代码相同但是.....

$sql="INSERT INTO cabs (NAME,IDNO,HOSTEL,MODE,DATE,TIME,TFNO,CONTACT)
VALUES
 ('$_POST[name]','$_POST[idno]','$_POST[hostel]','$_POST[mode]','$_POST[date]','$_POST[time]','$_POST[tfno]','$_POST[contact]')";

我只是尝试了第一步来阻止 sql注入 ..但似乎有些问题......

注意:我的主机似乎不支持mysqli,所以我必须使用不推荐使用的msql。

2 个答案:

答案 0 :(得分:2)

为什么不使用PDO?

$host = "localhost";
$user = "root";
$pass = "";
$dbname = "dbname";

$link = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));      

$foo_var = 3;

$query_result = $link->prepare("SELECT * FROM modules
                                WHERE id = :foo
                                LIMIT 1");
$query_result->bindValue(":foo", $foo_var);
$query_result->setFetchMode(PDO::FETCH_ASSOC);
$query_result->execute();

while($row = $query_result->fetch()) {

    return $row;
} 

答案 1 :(得分:0)

试试这个

$con=mysql_connect("localhost","username","password","dbname");//connection string
$sa_name=mysql_real_escape_string($con,$un_name);
.
.
.