简体   繁体   中英

How to add (ALTER table_name) in my code

Is it possible to add new field without editing my database but using PHP code or jquery to insert new field in my database, so let's say i have a table name MAIN with (COL1 ,COL2) and in my PHP code/jquery will insert new field (COL 3) in my database. Is it possible?

$result=("SELECT * FROM main");
$res = $conn->query($result);
if(isset($_POST['Add'])){
    if(empty($_POST['ParentCreate'])){
        echo "Fill up the textbox";
    }else{
        $sql = "ALTER TABLE tablemain ADD COLUMN
'".$_POST['ParentCreate']."' VARCHAR(100) NOT NULL COMMENT '' AFTER
main_one";
    $conn->query($sql);
    echo "New Field created";
}

}
-----------------------------------
<body>
<div id="frm_div">
    <form id="frm1" action="">
        <input type="text" name="ParentCreate" placeholder="ParentCreate" />
        <input type="submit" name="Add" value="Add" />
    </form>
</div>
<div id="result">
<?php
if($res!=""){
while($row=$res->fetch_row()){
    echo $row[0]."<br/>";
    echo $row[1]."<br/>";

}   
 }else{
    echo "Nothing Found";
 }
?>
</div>

First have a look at this: W3 Schools | SQL ALTER

Explanation

The SQL Code you are looking for:

ALTER TABLE table_name
ADD column_name datatype [AFTER previous_column_name]

[AFTER] -> optional, default at the end.

In your case it's (let's suppose the datatype for COL3 is VARCHAR):

ALTER TABLE MAIN
ADD COL3 VARCHAR(30) [AFTER previous_column_name]

If you do not even know how to use mysqli in PHP have a look at the PHP.net MySQLi Documentation (Alternative: php.net/manual/en/book.mysql.php)

But watch out! PHP will drop support for MySQL, so you better use MySQLi.

Update 1 - Fire a mysql Query

Get connected with the Host:

$conn = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) 
        or die("Failed to connect to Database: " . mysql_error());

Select the Database:

$db = mysql_select_db(DB_NAME, $conn) 
      or die("Failed to select Database: " . mysql_error());

Define your Query:

$sql = "ALTER TABLE tablemain 
        ADD '".$_POST['ParentCreate']."' VARCHAR(100) NOT NULL AFTER main_one";

Fire your Query:

mysql_query($sql) or die("Failed adding column: " . mysql_error());

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