如何插入两个记录到不同的表中,第一个与插入,然后与选择从插入php mysql


How to insert two records into different tables first one with insert and then with select from the insert php mysql

我的问题不容易解释,但我会训练。

我可以插入一个记录到一个表的列形式的形式与php mysql没有问题。这个插入在同一表的另一列中生成一条auto_increment记录。

所以我想在另一个表中选择这个新的auto_increment记录和insert记录。

<?php
            // process form`enter code here`
            $db_host="myhost";
            $db_user="myuser";
            $db_password="mypassword";
            $db_name="mydbname";
            $db_table_name="table1";
            $db_table_name2="table2";
            $record1= utf8_decode($_POST['record1']);
            $record2= utf8_decode($_POST['redord2']);
            $db_connection = mysqli_connect($db_host,$db_user,$db_password,$db_name);
            if (!$db_connection) {
                die('Could not connect to the database');
            }
            //insert record1 into table1
            $insert_value = 'INSERT INTO `' . $db_name . '`.`'.$db_table_name.'` (`name`) VALUES ("' . $record1 . '")';
            $result1 = $db_connection->query($insert_value);
            //consult auto_increment column from table1
            $select_value = 'SELECT column FROM table1 WHERE name = "' . $record1 . '"';
           //insert record2 into table2 in a row where a column is like $record1 
            $insert_value2 = 'INSERT INTO `' . $db_name . '`.`'.$db_table_name2.'` (`column1, column2`) VALUES ("' . $record2. '","' . $select_value  . '") WHERE name = "'.$db_table_name2.'"';
            $result2 = $db_connection->query($select_value);
            mysqli_close($db_connection);
        ?>
$query="Insert Statement";
$RunQuery = $db_connection->prepare($query);

如果你使用PDO,它是PDO::lastInsertId()。如果你的数据库句柄是$link:

$LastID = $db_connection->lastInsertId();

或者,如果你正在使用MySQLi,它是MySQLi::$insert_id或mysqli_insert_id():

$LastID = $db_connection->insert_id;

现在,在下一个查询中使用这个$ lastd。

查看PDO

中的mysql_insert_id, mysql_query
$insert_value2 = 'INSERT INTO `' . $db_name . '`.`'.$db_table_name2.'` (`column1, column2`) VALUES ("'.$record2.'","'.$LastID.'") WHERE name = "'.$db_table_name2.'"';
$result2 = $db_connection->query($insert_value2);

mysqli_insert_id()函数返回对具有AUTO_INCREMENT属性的列的表进行查询所生成的ID。

如果最后一个查询不是INSERT或UPDATE语句,或者修改后的表中没有带有AUTO_INCREMENT属性的列,该函数将返回0。

例如,

$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
$mysqli->query($query);
echo $mysqli->insert_id;