简体   繁体   English

PHP的while循环插入MySQL

[英]php insert mysql with while loop

i want to get datas from a mySQL table and want to insert every row (that my query get) into another table. 我想从mySQL表中获取数据,并想将每行(我的查询获得)插入到另一个表中。

With following code i get my Datas: 通过以下代码,我得到了我的数据:

$cart = new Dbconn();
$query = new Dbconn();
if ($cart->pdo()) {
   $cart->stmt("SELECT id, product FROM cart WHERE uid =:uid");
   $cart->bindParam(':uid', Session::get('uid'));
   $cart->exe();
}

After i get the data i want to insert it, with a while loop 获得数据后,我想用while循环将其插入

while ($rowPay = $cart->fetch()) {
    if ($query->pdo()) {
       $query->stmt('INSERT INTO orders (products_id, order_id) VALUES(:uid, :products)');
       $query->bindParam(':user_id', Session::get('uid'));
       $query->bindParam(':products', $rowPay['product']);
       $query->exe();
    }
}

He get all Datas but insert only the first entry. 他获取所有数据,但仅插入第一项。 Where is my mistake? 我的错误在哪里?

Greetings 问候

If it insert only the first entry, then there is a problem with the parameters you try to insert. 如果仅插入第一个条目,则您尝试插入的参数存在问题。 You probably try to insert several rows with the same primary key. 您可能尝试使用相同的主键插入几行。 I need to know where is the primary key in each table in order to help you more. 我需要知道每个表的主键在哪里,以便为您提供更多帮助。

$payCart->fetch() fetches single row and $payCart->fetchAll() fetches all rows. $ payCart-> fetch()提取单行,$ payCart-> fetchAll()提取所有行。

Try as this 这样尝试

while ($rowPay = $payCart->fetchAll(PDO::FETCH_ASSOC)) {
       if ($query->pdo()) {
           $query->stmt('INSERT INTO orders'
                       .'(products_id, order_id)'
                       .'VALUES(:uid, :products)');
           $query->bindParam(':user_id', Session::get('uid'));
           $query->bindParam(':products', $rowPay['product']);
           $query->exe();}}

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

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