简体   繁体   English

创建MySQL准备语句

[英]Creating MySQL Prepared Statement

I have absolutely zero experience protecting my SQL data. 我对保护SQL数据的经验绝对为零。 I am trying to prevent injection attacks on my web service by using prepared statements. 我试图通过使用准备好的语句来防止对Web服务的注入攻击。 I've followed several tutorials, but each one I've implemented has killed my PHP script. 我遵循了一些教程,但是我实现的每个教程都杀死了我的PHP脚本。 How could I protect this query? 如何保护此查询?

$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;
        }
    } 

Here is my attempt: 这是我的尝试:

$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;
        }
}

I'm not really sure why this code doesn't work. 我不太确定为什么这段代码不起作用。

Prepared statement with MySQLi 用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 tips and tricks. PHP技巧和窍门。 http://www.phptherightway.com/ http://www.phptherightway.com/

If you are concerned about security this is the topic that I love very much. 如果您担心安全性,这是我非常喜欢的主题。 What are the best PHP input sanitizing functions? 什么是最好的PHP输入清理功能? .

You will have to bind the result and below is the code - it is going to work please try it. 您将必须绑定结果,下面是代码-它将起作用,请尝试一下。 please check if there any syntax issues in my code. 请检查我的代码中是否存在语法问题。 otherwise it will work. 否则它将起作用。

$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; 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM