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);
        }
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥200 如何使用postGis实现最短领规划?
  • ¥15 pyinstaller打包错误
  • ¥20 cesm的气溶胶排放文件
  • ¥15 逐月累计,月份不连续,补齐月份
  • ¥15 应用简单的Python代码完成一个学生成绩管理系统
  • ¥15 用matlab求微分方程初值问题
  • ¥15 vscode下编写第三方库opencv与pcl代码时没有代码提示
  • ¥15 能够跑通不报错,如何解决?(标签-matlab)
  • ¥15 MOS在RDS较大,频率高时开关波形异常
  • ¥15 SCENIC分析报错求解答