对于每个查询结果,将其添加到表中并提供ID php

时间:2018-12-08 23:09:57

标签: php mysql mysqli

我需要帮助将查询结果插入到另一个表中,并为每个结果提供一个ID号。

$GroupSize = $_POST['groupsize'];

//Connect to the Server+Select DB
$con = mysqli_connect($host, $user, $password, $dbName) or die("Nope");

if (isset($_POST['create'])) {

//assign group id to groups created
//insert groupinformation to table from userInformation group Id must increment by every group created

    //$query ="Select RegistrationId from userInformation order by RAND() LIMIT ".$GroupSize;
    $query = "INSERT INTO groupInformation SELECT RegistrationId FROM (SELECT RegistrationId FROM userInformation ORDER BY RAND() LIMIT ".$GroupSize.")";

    $result = mysqli_query($con, $query) or die ("query failed " . mysqli_error($con));

    while (($row = mysqli_fetch_row($result)) == true) {
        echo $row[0].'<br>';

    }

我的表userInformation在groupInformation中的RegistrationId有一个主键,在RegistrationId上有一个外键。 groupInformation中的组ID将自动为每个结果自动生成ID。

我知道我需要使用while循环或foreach来做到这一点,但我不知道如何。

1 个答案:

答案 0 :(得分:1)

开始选择您想要的样子

$ stmt = $con->prepare("SELECT //Select what you want to select\\)
$ stmt->execute()
$ array = $stmt->fetch()

在您可以插入到新表之后,例如

$ stmt = $con->prepare(INSERT INTO groupinformation)
$ stmt->execute

U不能在同一行中插入和选择