如何使用字符串变量作为插入 PHP 中的表目标


How to use a string variable as a table destination in a INSERT INTO PHP

我有这个代码

<?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 = "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 . "')";