php - 将值插入具有 PHP 变量名称的表中

标签 php mysql sql mysqli

我正在建立一个简单的网站,每个用户都有自己的表格(我知道这是个坏主意),其他用户可以在其中发表评论 - 就像 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";
}

阅读http://php.net/manual/en/mysqli-stmt.bind-param.php

关于php - 将值插入具有 PHP 变量名称的表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37411937/

相关文章:

java - 在Java中使用静态方法共享数据库连接

mysql - 我怎样才能使这个 MySQL 查询(带有子查询)更快?

sql - 如何从 Hive 中的 json 字符串中提取选定的值

php - Mysql group_concat 与 unique 和 where 给出奇怪的结果

php - 如何从此URL“http://localhost/blog/public/post?id = 2”中删除“?id =”?

PHP while循环基于MYSQL查询结果丢失第一行

mysql - 如何执行 SQL 查询,连接另一个表的 count() 列在sequelizejs中

php - MySQL,从 $_SESSION ['username' 开始计数]

MySql 获取余额查询

MySQL 对多个表进行排序需要很长时间