我从表中随机选择5行。
$query = "SELECT stdid, name FROM students order by rand(UNIX_TIMESTAMP()) limit 5"
$myquery = mysqli_query($db_connect, $query);
while($students = mysqli_fetch_assoc($myquery)){
$stdid =$students['stdid']; $name = $students['name']; $dept = $students['dept'];
echo "<br><br>".$stdid."<br>".$name."<br>".$dept;
//NOT SURE IF I ADD INSERT HERE
}
我想将显示的'stdid'插入(5行)到另一个表中。
我是否需要在WHILE循环中添加INSERT?还有另一种方法可以解决这个问题吗?
非常感谢。
答案 0 :(得分:0)
将插入放在while循环中是有效的。只有五个条目,这不会太低效。如果要一次插入所有值,则应该查看有关如何执行此操作的问题。 Inserting multiple rows in a single SQL query?
答案 1 :(得分:0)
使用PHP MySQLi预处理语句准备插入查询,在循环外部,然后重用该准备插入对象以将值转储到循环内的所需表中:
$query1 = "SELECT stdid, name FROM students order by rand(UNIX_TIMESTAMP()) limit 5";
$myquery1 = mysqli_query($db_connect, $query1);
// prepare insert stdid
$query2 = "INSERT INTO someothertable (stdid) VALUES (?)";
$myquery2 = mysqli_prepare($db_connect, $query2);
mysqli_stmt_bind_param($myquery2, 'i', $stdid);
while($students = mysqli_fetch_assoc($myquery1)){
$stdid =$students['stdid']; $name = $students['name']; $dept = $students['dept'];
echo "<br><br>".$stdid."<br>".$name."<br>".$dept;
// insert stdid
mysqli_execute($myquery2);
}
答案 2 :(得分:0)
您只需插入上述语句即可。下面是一些代码,可以帮助您制作一个准备好的语句,该语句将添加未预定义的值。
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$mysqli->query("CREATE TABLE myCity LIKE City");
/* Prepare an insert statement */
$query = "INSERT INTO myCity (Name, CountryCode, District) VALUES (?,?,?)";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("sss", $val1, $val2, $val3);
$val1 = 'Stuttgart';
$val2 = 'DEU';
$val3 = 'Baden-Wuerttemberg';
/* Execute the statement */
$stmt->execute();
$val1 = 'Bordeaux';
$val2 = 'FRA';
$val3 = 'Aquitaine';
/* Execute the statement */
$stmt->execute();
/* close statement */
$stmt->close();
取自手册。希望它有所帮助!