【问题标题】:How to use a string variable as a table destination in a INSERT INTO PHP如何在 INSERT INTO PHP 中使用字符串变量作为表目标
【发布时间】: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数据直接放入查询中。

标签: php mysql json


【解决方案1】:

以下

$sql = "INSERT INTO mydatabase."$tableto" (Question, Answer_1, Answer_2, Answer_3, Correct_Answer, Parcial, Feedback)
VALUES ('" . $Question . "', '" . $answerone . "', '" . $answertwo . "', '" . $answerthree . "', '" . $Correctanswer . "', '" . $reparcial . "', '" . $Feedback . "')";

因为使用了“而有问题

在声明 $sql 时,您使用的是字符串的串联,而您错过了 .在你的串联中。

尝试更改为:

$sql = "INSERT INTO mydatabase." . $tableto . " (Question, Answer_1, Answer_2, Answer_3, Correct_Answer, Parcial, Feedback)
    VALUES ('" . $Question . "', '" . $answerone . "', '" . $answertwo . "', '" . $answerthree . "', '" . $Correctanswer . "', '" . $reparcial . "', '" . $Feedback . "')";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 2012-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-23
    • 1970-01-01
    相关资源
    最近更新 更多