我正在建立一个简单的网站,每个用户都有自己的表格(我知道这是个坏主意),其他用户可以在其中发表评论 - 就像 Facebook 墙的超预算版本。
这就是我创建表时的查询:
$userTable = mysqli_query($conn, "CREATE TABLE `".$epost."`(
ID INT(255) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
eMail VARCHAR(50) NOT NULL,
comment VARCHAR(500) NOT NULL,
timestampp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
)");
但是,当我尝试从表单中获取值并将它们插入到特定的表中时,它们似乎无法找到其中的方式。这是我的代码:
<?php
include 'connect.php';
/*if(isset ($_POST['userUser']))*/
$valueEmail = mysqli_real_escape_string($conn, $_POST['userEmail']);
$valueUser = mysqli_real_escape_string($conn, $_POST['userUser']); /*have the user to input the name, so i can connect to the correct DB*/
$valueMessage = mysqli_real_escape_string($conn, $_POST['userMessage']);
$findUserTable = "SELECT * FROM UserInfo WHERE Firstname = '$valueUser'";
$findUserEmail = mysqli_query($conn, $findUserTable);
if(mysqli_num_rows($findUserEmail) > 0) /*finding the name of the persons email*/
{
while ($result = mysqli_fetch_assoc($findUserEmail))
{
$email = $result['Email'];
}
}
/* VALIDATION HERE */
$sql = "INSERT INTO ".$email." (eMail, comment) VALUES ('$valueEmail', '$valueMessage')"; /* wrong query?*/
header("refresh:10 url=userProfil.php");
/*echo '<script>alert("Meddelande skapat!");</script>';*/
echo $sql;
mysqli_close($conn);
?>
我一直在尝试变量的不同“版本”,例如“.$email.”、'.$email.'
和 “.$epost.”
。当我回显查询或仅回显变量时,我得到了正确的名称 - 但它似乎找不到表?
我非常清楚我的代码味道很糟糕,所以请在这一点上原谅我。
最佳答案
您只需简单地编写查询,忘记执行它。
$sql = "INSERT INTO ".$email." (eMail, comment) VALUES ('$valueEmail', '$valueMessage')"; /* wrong query?*/
使用这个
mysqli_query($conn,$sql);//for execute
更好地使用绑定(bind)和准备语句作为
$sql = "INSERT INTO ".$email." (eMail, comment) VALUES (? ,?)"; /* wrong query?*/
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $valueEmail, $valueMessage);
/* Execute the statement */
$stmt->execute();
$row = $stmt->affected_rows;
if ($row > 0) {
echo "data inserted";
} else {
"error";
}
关于php - 将值插入具有 PHP 变量名称的表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37411937/