PHP - 将foreach值发送到mysql数据库字段

时间:2018-02-20 13:27:32

标签: php mysql arrays

我正在建立我的第一家网店。 到目前为止,在我创建的每个网站中,我都可以通过向插入查询发送只有一个值(名称,电子邮件,等等......)的$ _POST来填充数据库。

但这是我第一次只需要在一个数据库字段中存储许多产品名称。

我有一个会话,存储产品信息,如名称,价格,代码和数量。

如何向会话发送多个值,会话中存储n个产品到数据库字段?

我尝试在输入中使用foreach循环但是无法做到。

这是我的会话foreach循环:

<?php
          $total = 0;
          foreach($_SESSION["products"] as $product){       
            $product_name = $product["product_name"]; 
            $product_price = $product["product_price"];
            $product_code = $product["product_code"];
            $product_qty = $product["product_qty"];       
            $subtotal = ($product_price * $product_qty);
            $total = ($total + $subtotal);
        ?>

2 个答案:

答案 0 :(得分:1)

正如您所说,您需要为单行存储多个产品名称,这就是您可以做到的。

app.post('/home.html',function(req,res){
   //console.log(req.body);
   con.query('SELECT MAX(user_id) as id FROM users',(err,rows)=> {
        if(err) throw err;
        console.log('Data received from Db:\n');

        var string=JSON.stringify(rows);
        var json =  JSON.parse(string);

        console.log('>> MAX_ID: ', json[0].id);/* >> MAX_ID: 14 it is work successfully*/

        let name=getdata(json[0].id);
        console.log(">>getdata() : "+name); /* >>getdata() : undefined*/
   })
});


var MaxId;
function getdata(MaxId){
    var res;
    /*console.log('THIS IS MAX ',MaxId);*/
    con.query('SELECT * FROM users WHERE user_id = ?',[MaxId],(err,rows)=> {
       if(err)throw err;
       var string=JSON.stringify(rows);
       var json =  JSON.parse(string);

       r=json[0].user_first;
       //how i can return this varaible 
       //or move it outside con.query
    })
    return r;// r not defined
}

答案 1 :(得分:0)

好吧,经过多次尝试,我设法编写代码来解决问题:)

foreach($_SESSION["products"] as $product){       
  $product_name = $product["product_name"]; 
  $products[] = implode(',', (array)$product_name);
}

$p = json_encode($products);
var_dump($p);
$sql = "INSERT INTO fatura_mb(carrinho) VALUES ('$p')";
$results = $con->query($sql);

JSON转换优于serialize(),而implode方法总是抛出错误或只回显数组中的最后一个索引。

这样,数据可以在我需要的单个字段中妥善存储在数据库中。

感谢所有帮助我的人:)