0

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.

Faizuddin Mohammed
  • 4,118
  • 5
  • 27
  • 51

1 Answers1

0

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);
kayleighsdaddy
  • 670
  • 5
  • 15