【发布时间】:2016-01-21 23:57:03
【问题描述】:
我有这个代码
<?php
$servername = "localhost";
$username = "username";
$password = "pass";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Take the data from the request
$json = file_get_contents('php://input');
$data = json_decode($json, true);
$tableto = $data['tabledestination'];
$Question = $data['question'];
$answerone = $data['answerone'];
$answertwo = $data['answertwo'];
$answerthree = $data['answerthree'];
$Feedback = $data['feedback'];
$Correctanswer = $data['Correctanswer'];
$reparcial = $data['partial'];
//Insert the data into the database
$sql = "INSERT INTO mydatabase."$tableto" (Question, Answer_1, Answer_2, Answer_3, Correct_Answer, Parcial, Feedback)
VALUES ('" . $Question . "', '" . $answerone . "', '" . $answertwo . "', '" . $answerthree . "', '" . $Correctanswer . "', '" . $reparcial . "', '" . $Feedback . "')";
if ($conn->query($sql) === TRUE) {
echo '{ "result": "success" }';
} else {
echo '{ "result": "error" }';
}
//Close the connection
$conn->close();
?>
我通过带有 HTTPMethod "POST" 的 URLRequest 传递信息 我想通过我发布数据库表目标的字典发送,以便我可以根据传递的字符串分配表的目标
【问题讨论】:
-
而上面代码的问题是?
-
它不插入任何东西
-
您必须在 $sql 字符串中的 $tableto 变量周围添加点。
-
首先我看到没有创建 $conn。此外,即使此脚本运行,它也容易受到 sql 注入的影响。使用参数化查询,准备好的语句而不是直接插入查询。
-
警告:当使用
mysqli时,您应该使用参数化查询和bind_param将用户数据添加到您的查询中。 请勿使用字符串插值或连接来完成此操作,因为您将创建严重的SQL injection bugs。 从不将$_POST数据直接放入查询中。