dseigqk7443 2017-04-11 04:30
浏览 48

将php字符串插入mysql

I would like to into a string into mysql and understand I have to explode the string into an array before it can be inserted.

How would I write the PHP object oriented code to insert the string?

I have two variables:

$id = "Apple"    and    $product = "Pie, Candy"

This is what I would like the database to look like:

ID          Product
---         -------
Apple       Pie
Apple       Candy

This is what I have written so far in my code:

$id = "Apple";
$product = "Pie, Candy";
$product_arr = explode(", ",$product);

if (is_array($product_arr)) {
    $sql = "INSERT INTO table1 (id, product) VALUES ";
    $value_arr = array();

    foreach($product_arr as $row) {
        $prdct = mysql_real_escape_string($row[0]);
        $value_arr[] = "('$id','$prdct')";
    }
    mysqli_query($conn,$sql);
}
  • 写回答

1条回答 默认 最新

  • doushi2902 2017-04-11 07:53
    关注

    You can try this

    $id = "Apple";
    $product = "Pie, Candy";
    $product_arr = explode(", ",$product);
    $len = count($product_arr);
    
    for($i=0;$i< $len;$i++){
        $product = $product_arr[$i];
        $abc = "INSERT INTO table1 (id, product) VALUES "."('$id','$product')";
        if ($con->query($abc) === TRUE) {
        }
        else
        {
            //echo "Error: " . $abc . "<br>" . $con->error;
        }
    }
    

    Output

    评论

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失