duanliang2017 2014-11-19 16:28
浏览 42
已采纳

转换| 使用PHP将值分隔为新表

Edit: I forgot to add the explode part that I'm having the issues with. I need the query result exploded.

I have been messing with this for a while and have a workable procedure in mysql, however I want to accomplish this as part of a larger script. I have a table filled with IDs and several columns of data with "|" separated values. How can I use or edit the below PHP to query and insert normalized results into a new table?

If I run this with an actual string: "40|180|408|360|40|166|80|59"; It will insert values (not the ID, which I also need) but when I try to pass in query results, I get "Array to string conversion" errors. Any guidance would be appreciated.

$query = "Select id, imageSize from T1";
$result = mysqli_query($conn, $query);
$myArray = explode('|', $result);

foreach($myArray as $value) {
   $sql = "INSERT INTO testExplode VALUES ($value)";
$result = mysqli_query($conn, $sql);
}
  • 写回答

1条回答 默认 最新

  • dtnrsmi824877 2014-11-19 16:32
    关注

    If you want to insert all of your results then:

    $query = "Select id, imageSize from T1";
    $myArray = mysqli_query($conn, $query);
    
    while ($row = mysqli_fetch_assoc($myArray)) {
        $sql = "INSERT INTO testExplode VALUES (" . mysqli_real_escape_string($conn, $row['imageSize']) . ")";
        mysqli_query($conn, $sql);
    }
    
    //If just only one:
    
    $query = "Select id, imageSize from T1";
    $myArray = mysqli_query($conn, $query);
    
    $row = mysqli_fetch_assoc($myArray);
    $sql = "INSERT INTO testExplode VALUES (" . mysqli_real_escape_string($conn, $row['imageSize']) . ")";
    mysqli_query($conn, $sql);
    

    NOTE:

    • Avoid sql injecions by escaping your variables in your querys.

    EDIT:

    Based on the OP comment.

    $query = "Select id, imageSize from T1";
    $myArray = mysqli_query($conn, $query);
    
    while ($row = mysqli_fetch_assoc($myArray)) {
        $values = explode('|', $row['imageSize']);
        foreach ($values as $value) {
            $sql = "INSERT INTO testExplode VALUES (" . mysqli_real_escape_string($conn, $value) . ")";
        mysqli_query($conn, $sql);
        }
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据