为精选查询

时间:2018-05-30 20:29:09

标签: php prepared-statement

在响应Ajax请求的php文件中,我尝试使用预处理语句而不是这样做(实际工作):



<?php
$q = intval($_GET['q']);

$con = mysqli_connect('localhost','root','root','pokemons');
if (!$con) {
    die('Could not connect: ' . mysqli_error($con));
}

$sql="SELECT * FROM pokemons_en WHERE id = '".$q."'";
$result = mysqli_query($con,$sql);

while($row = mysqli_fetch_array($result)) {
    
    $separator = '|';
        
    echo '<img src="'. $row['image'] .'" unselectable="on"/>' . $separator . $row['name'] . $separator.  $row['type'] . $separator . $row['categorie'] . $separator. $row['talent']. $separator. $row['taille']. $separator. $row['poids']. $separator . '<audio id="audio" src="'. $row['audio'] .'" ></audio>'. $separator . $row['type2']. $separator . $row['bio'] ;

}

mysqli_close($con);
?>
&#13;
&#13;
&#13;

这是从mySQL数据库输出数据的文件,它实际上正在运行。但是根据我的理解,我确实应该使用预处理语句来实现性能,并且还要防止SQL注入攻击。

我试过这个以及我能找到的许多其他方法,但我无法让它发挥作用。我应该更正/修改哪一部分?

&#13;
&#13;
<?php
$q = intval($_GET['q']);

$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "pokemons";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $conn->prepare("SELECT * FROM pokemons_en WHERE id = '".$q."'"); 
    $stmt->execute();

    $result = $stmt->setFetchMode(PDO::FETCH_ASSOC); 
    while($row = $stmt->fetchAll()) { 
        
        $separator = '|';
        
    echo '<img src="'. $row['image'] .'" unselectable="on"/>' . $separator . $row['name'] . $separator.  $row['type'] . $separator . $row['categorie'] . $separator. $row['talent']. $separator. $row['taille']. $separator. $row['poids']. $separator . '<audio id="audio" src="'. $row['audio'] .'" ></audio>'. $separator . $row['type2']. $separator . $row['bio'] ;
    }
}
catch(PDOException $e) {
    echo "Error: " . $e->getMessage();
}
$conn = null;
?>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:3)

变量不会进入准备好的陈述中。尝试:

?

execute是占位符,驱动程序将对其进行转义并根据需要引用它。 define thisenv = '(select name from v$database)' select &thisenv env, count(1) from phone; 将值绑定到查询中。