简体   繁体   English

如何使用 PHP 和 MYSQL 动态更改表列

[英]How to Alter table column dynamically using PHP and MYSQL

I added a form including an input field and a button.我添加了一个包含输入字段和按钮的表单。 Now I am trying to pass the text from the input field into my query as the column name when the button is pressed.现在我试图在按下按钮时将输入字段中的文本作为列名传递到我的查询中。 the form's method is post and the action is the path to the PHP file that holds the function.表单的方法是 post,动作是 PHP 文件的路径,该文件包含 function。 The text from the input field is held in the variable $subject and now I'm trying to pass this variable into to the query.输入字段中的文本保存在变量$subject中,现在我试图将此变量传递给查询。 I'm running my application on XAMPP server and it keeps on giving me this我在 XAMPP 服务器上运行我的应用程序,它一直给我这个

error:错误: "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''English' VARCHAR(100)' at line 1" . “您的 SQL 语法有错误;请查看与您的 MariaDB 服务器版本相对应的手册,了解在第 1 行的 ''English' VARCHAR(100)' 附近使用的正确语法”

How do I do this successfully?我如何成功地做到这一点?

WEB PAGE SOURCE: WEB 页面来源:

<form action="addons/functions.php" method="POST">
                            <br><h1 class="bg-warning">Subject</h1>
                            <input type="text" placeholder="add Subject" name="subject" class="input-group"><br>
                            <button type="submit" name="addsub" class="btn-success btn-dark">Add Subject</button>
                            <span class="mailspan"><?php 

                            if(isset($_SESSION['message'])){
                                echo $_SESSION['message'];
                                unset ($_SESSION['message']);
                            }

                    ?></span>
                        </form>

PHP FILE SOURCE: PHP 文件来源:

if (isset($_POST['addsub'])){
    $sub=$_POST['subject'];
    $conn->query("ALTER TABLE students ADD '$sub' VARCHAR(100)" ) or die($conn->error);
    $_SESSION['message']='Subject added successfully!';
 header("location:../admin.php");
}

I think there is a missing word "COLUMN" in this query if you are going to add new column.如果您要添加新列,我认为此查询中缺少单词“COLUMN”。 Instead of this而不是这个

"ALTER TABLE students ADD '$sub' VARCHAR(100)"

Try尝试

"ALTER TABLE students ADD COLUMN '$sub' VARCHAR(100)"

But like other guys said, read about prepared statements to avoid SQL injection.但就像其他人说的那样,阅读准备好的语句以避免 SQL 注入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM