需要帮助使用PHP在mysql数据库中插入逗号分隔数据

前端之家收集整理的这篇文章主要介绍了需要帮助使用PHP在mysql数据库中插入逗号分隔数据前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
数据库表中已有的演示数据:
INSERT INTO `csvtbl` (`ID`,`SKU`,`Product_Name`,`Model`,`Make`,`Year_From`,`Year_To`) VALUES
(1,'C2AZ-3B584-AR','Power Steering Pump Seal Kit (Eaton Pump)','Galaxie','Ford','1960','1965'),(2,'Thunderbird ','Fordtrest','1965');

我使用下面的代码并插入年份,并在表格中分隔逗号(,):

INSERT INTO `diff_yearstbl` (`ID`,`Year`) VALUES
(1,'1960,1961,1962,1963,1964,1965'),1965');

年份数据运行良好,但我想插入数据Make和Model与Year相同,但这次只是使用逗号(,)将数据插入一行,如下例所示,使用SKU字段.因此需要将上述两条记录合并为一行,如下面的记录.

INSERT INTO `diff_yearstbl` (`ID`,'Galaxie,Thunderbird','Ford,Fordtrest' '1960,1965');

以下是我所做的代码

$query = "select Year_TO - Year_From as diff_years,ID,SKU,Product_Name,Model,Make,Year_From,Year_To from csvtbl";
$result = MysqL_query($query,$connect );

//$result = $db->query($select_test)->fetchAll();

if (count($result) > 0) 
{

    while($QryRow = MysqL_fetch_assoc($result)) 
    {
        $diff_years = $QryRow['diff_years'];
        $Year_From = $QryRow['Year_From'];
        $SKU = $QryRow['SKU'];
        $Product_Name = $QryRow['Product_Name'];
        $Model = $QryRow['Model'];
        $Make = $QryRow['Make'];

        $years= array();
        for ($x = $QryRow['Year_From']; $x <= $QryRow['Year_To']; $x++) 
        {           
            $years[] = $x;    
        }

        $query_insert = "INSERT INTO diff_yearstbl(SKU,Year) VALUES('".$SKU."','".$Product_Name."','".$Model."','".$Make."','".implode('|',$years)."')";
        $s_insert = MysqL_query($query_insert,$connect ); 
    }
} 
else 
{
    echo "<p>Nothing matched your query.</p>";
}

    ?>

请帮忙一下.

您应该从$QryRow [‘Year_From’]循环到$QryRow [‘Year_To’]并在插入它们之前收集它们.
$years= array();
for ($x = $QryRow['Year_From']; $x <= $QryRow['Year_To']; $x++) 
{           
    $years[] = $x;    
}

$query_insert = "INSERT INTO diff_yearstbl(SKU,'".implode(',',$years)."')";
$s_insert = MysqL_query($query_insert,$connect );

不推荐使用MysqL_ *请使用MysqLi_ *或PDO

原文链接:https://www.f2er.com/php/240290.html

猜你在找的PHP相关文章