0

I am selecting 5 rows at random from a table.

$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.

Do i need to add the INSERT in the WHILE loop ? Is there another way to go about this ?

Many thanks.

Somename
  • 3,376
  • 16
  • 42
  • 84

3 Answers3

0

It will work to put the insert inside the while loop. 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?

Community
  • 1
  • 1
pocketg99
  • 124
  • 1
  • 12
0

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:

$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);
}
bloodyKnuckles
  • 11,551
  • 3
  • 29
  • 37
0

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!