[英]Inserting values into a table with a PHP-variable name
I'm setting up a simple website where each user gets their own table (bad idea, I know), in which other users can put comments into - like a super budget version of a Facebook-wall. 我正在建立一个简单的网站,每个用户都可以拥有自己的表格(我知道,这是个坏主意),其他用户可以在其中添加评论,例如Facebook墙的超级预算版本。
This is what my query looks like when I create the table: 这是我创建表时的查询形式:
$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
)");
However, when I try to take the values from a form, and insert them into the specific table they can't seem to find their way in there. 但是,当我尝试从表单中获取值并将其插入到特定表中时,它们似乎无法在其中找到它们的方式。 Here's my code of that: 这是我的代码:
<?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);
?>
I've been trying different 'versions' of the variable, like ".$email.", '.$email.'
我一直在尝试变量的不同“版本”,例如“。$ email。”, '.$email.'
and ".$epost."
和".$epost."
. 。 I get the correct name when i echo out my query or just the variable - but it can't seem to find the table? 当我回显查询或只是变量时,我会得到正确的名称-但它似乎找不到表? I'm very aware that my code smells badly, so please spare me on that point. 我很清楚我的代码难闻,所以请您在这一点上多加保留。
You just simple write your query forget to execute it. 您只是简单地编写查询而忘记执行它。
$sql = "INSERT INTO ".$email." (eMail, comment) VALUES ('$valueEmail', '$valueMessage')"; /* wrong query?*/
Use this 用这个
mysqli_query($conn,$sql);//for execute
Better use Bind and prepare statement as 更好地使用Bind和prepare语句作为
$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";
}
Read http://php.net/manual/en/mysqli-stmt.bind-param.php 阅读http://php.net/manual/en/mysqli-stmt.bind-param.php
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.