[英]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. 如何在MySQL中编写代码,以便每当将具有主键ID的行添加到表中时,在另一表中添加相应的列,以使该列的名称等于刚添加的行的ID。
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. sqlQuery-返回mysqli_query结果的用户定义函数。
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. 使其具有OOP样式,并且该类中有一个var,它会自动返回最近更新的项目。
$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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.