简体   繁体   中英

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. 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. I'm running my application on XAMPP server and it keeps on giving me this

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" .

How do I do this successfully?

WEB PAGE SOURCE:

<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:

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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