简体   繁体   中英

How to alter a table (add a column) simultaneously when a row is added (column name = row id) in another table?

How to write code in MySQL such that when ever a row with a primary key id is added to a table, a corresponding column is added in another table such that the name of the column is equal to the id of the row just added.

I tried the following but to no use.

sqlQuery("INSERT INTO table1(name) VALUES('$name')");
$id = sqlQuery("SELECT id FROM table1 WHERE id = LAST_INSERT_ID()");
$id = mysqli_fetch_array($id);
$id = $id['id'];
sqlQuery("ALTER TABLE table2 ADD '$id' INT(2) NOT NULL");

sqlQuery - user defined function that return mysqli_query result.

Any help would be great. Also, I'm a newbie. Sorry if this is a silly question to ask.

Make it OOP style and there is a var in the class that automatically returns the last updated item.

$con = new mysqli(SQL_HOST, SQL_USER, SQL_PASSWORD, SQL_DATABASE); //do normal error checking with database connection
$sql = "INSERT INTO table1(name) VALUES('$name')";
$con->query($sql);
$sql2 = "ALTER TABLE table2 ADD '$con->insert_id' INT(2) NOT NULL"  //$con->insert_id is the parm you are looking for.
$con->query($sql2);

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