创建MySQL准备语句

时间:2017-07-30 04:41:43

标签: php mysql

我绝对没有保护我的SQL数据的经验。我试图通过使用预准备语句来防止对我的Web服务的注入攻击。我已经关注了几个教程,但是我已经实现的每个教程都杀了我的PHP脚本。我怎么能保护这个查询呢?

$value = (integer)$_GET["name"];
$sql = "SELECT `coordinates`, `center` , `content_string` FROM Regions WHERE `id` = {$value}";

$result = $conn->query($sql);

$rows = array();

if ($result->num_rows > 0) {
        // output data of each row
        while($r = mysqli_fetch_assoc($result)) {
        $rows[] = $r;
        }
    } 

这是我的尝试:

$value = (integer)$_GET["name"];
$sql = $dbConnection->prepare('SELECT `coordinates`, `center` , `content_string` FROM Regions WHERE `id` = ?');
$sql->bind_param('i', $value);

$sql->execute();

$result = $sql->get_result();

$rows = array();

if ($result->num_rows > 0) {
        // output data of each row
        while($r = mysqli_fetch_assoc($result)) {
        $rows[] = $r;
        }
}

我不确定为什么这段代码无效。

2 个答案:

答案 0 :(得分:0)

使用MySQLi编写声明

$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

// prepare and bind
$stmt = $conn->prepare("INSERT INTO users (username, email) VALUES (?, ?)");
$stmt->bind_param("ss", $username, $email);

// set parameters and execute
$username= "John";
$email = "john@example.com";
$stmt->execute();

$username= "Mary";
$email = "mary@example.com";
$stmt->execute();

echo "New records created successfully";

$stmt->close();
$conn->close();

Php技巧和窍门。 http://www.phptherightway.com/

如果你担心安全问题,这是我非常喜欢的主题。 What are the best PHP input sanitizing functions?

答案 1 :(得分:0)

你必须绑定结果,下面是代码 - 它会起作用请尝试。请检查我的代码中是否存在任何语法问题。否则它会起作用。

$value = (integer)$_GET["name"];
$sql = $dbConnection->prepare('SELECT 'coordinates', 'center' , 'content_string' FROM Regions WHERE `id` = ?');
$sql->bind_param('i', $value);
$sql->execute();
$sql->bind_result($coordinates, $center, $content_string)

while($sql->fetch())
{
   echo $coordinates;
   echo $center;
   echo $content_string; 
}
相关问题