简体   繁体   English

如何在另一个表中插入返回值

[英]How to Insert returned values in another table

I am selecting 5 rows at random from a table. 我从表中随机选择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     
}

I want to INSERT (5 rows) the displayed 'stdid' into another table. 我想将显示的“ stdid”插入(5行)到另一个表中。

Do i need to add the INSERT in the WHILE loop ? 我是否需要在WHILE循环中添加INSERT? Is there another way to go about this ? 还有另一种方法吗?

Many thanks. 非常感谢。

It will work to put the insert inside the while loop. 将插入内容放入while循环中将起作用。 With only five entries, this won't be too inefficient. 只有五个条目,这不会太低效。 If you want to insert all of the values at once, you should check out this question on how to do it. 如果要一次插入所有值,则应查看有关如何操作的问题。 Inserting multiple rows in a single SQL query? 在单个SQL查询中插入多行?

Using PHP MySQLi prepared statements to prepare the insert query, once, outside the loop, then reuse that prep'd insert object to dump values into the desired table inside the loop: 使用PHP MySQL编写的语句在循环外部一次准备插入查询,然后重用该预先准备好的插入对象将值转储到循环内所需的表中:

$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);
}

You can just insert the statement as mentioned above. 您可以如上所述插入语句。 Here is some code to help you make a prepared statement which will add your values that are not predefined. 这是一些代码,可帮助您准备一条准备好的语句,该语句将添加未预定义的值。

$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();

Taken from the manual. 取自手册。 Hope it helps! 希望能帮助到你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM