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

时间:2014-11-19 16:28:01

标签: php mysql arrays explode

编辑:我忘了添加我遇到问题的爆炸部分。我需要爆炸查询结果。

我已经搞砸了一段时间并且在mysql中有一个可行的程序,但是我想在更大的脚本中完成这个。我有一个表格,其中包含ID和几列数据" |"分开的值。如何使用或编辑以下PHP来查询并将规范化结果插入到新表中?

如果我用实际字符串运行它:" 40 | 180 | 408 | 360 | 40 | 166 | 80 | 59&#34 ;;它会插入值(不是ID,我也需要),但是当我尝试传入查询结果时,我得到了#34;数组到字符串转换"错误。任何指导都将不胜感激。

$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 个答案:

答案 0 :(得分:2)

如果您想插入所有结果,请:

$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);

注意:

  • 通过在查询中转义变量来避免sql注入。

编辑:

基于OP评论。

$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);
    }

}