如何使用PHP将多维数组存储到mysql中

时间:2012-04-17 19:36:56

标签: php mysql multidimensional-array

我创建了一个名为“test”的数据库,并创建了一个名为“biodata”的表。我在biodata表中创建了名为“Name”“Age”和“Description”的3列。现在如何将我的数组结果存储到每一列。

以下是完整的代码......

<?php

    $ip = "localhost";
    $username = "root";
    $password = "";
    $dbname = "test";
    $res = mysql_connect($ip,$username,$password);
    if(!$res)
    {
        echo "DB Connection Failed.";
        exit;
    }
    if(!mysql_select_db("test"))
    {
        echo "NOT SELECTED";
        exit;
    }

        $company =  array(
                    'Record1'=>array('Shabbir',26,'Designer'),
                    'Record2'=>array('Burhan',24,'Architecture'),
                    'Record3'=>array('Huzeifa',20,'Accountant'),
                );

        foreach ($company as $employees=>$details){

        echo '<strong>'.$employees.'</strong><br>';

        foreach($details as $employeeinfo){

            echo $employeeinfo.'<br>';

        }

        }

        $sql = "INSERT INTO biodata (Name, Age, Description) VALUES ($employeeinfo[0], $employeeinfo[1], '$employeeinfo[2]')";
        mysql_query($sql);

?>

3 个答案:

答案 0 :(得分:1)

您的mysql_query被认为是在foreach声明中...由于SQL Injection

,您还需要清理数据

您也不需要2 foreach声明...

<强>校正

foreach ($company as $employees =>$details){
    echo '<strong>'.$employees.' - OK</strong><br>';
    mysql_query(sprintf($sql,mysql_real_escape_string($details[0]),mysql_real_escape_string($details[1]),mysql_real_escape_string($details[2])));
}

完整脚本安排

$ip = "localhost";
$username = "root";
$password = "";
$dbname = "test";
$res = mysql_connect($ip,$username,$password);
$sql = "INSERT INTO biodata (Name, Age, Description) VALUES ('%s', '%d', '%s')";
$company =  array(
        'Record1'=>array('Shabbir',26,'Designer'),
        'Record2'=>array('Burhan',24,'Architecture'),
        'Record3'=>array('Huzeifa',20,'Accountant'),
);

if(!$res)
{
    echo "DB Connection Failed.";
    exit;
}

if(!mysql_select_db("test"))
{
    echo "NOT SELECTED";
    exit;
}

foreach ($company as $employees =>$details){
    echo '<strong>'.$employees.' - OK</strong><br>';
    mysql_query(sprintf($sql,mysql_real_escape_string($details[0]),mysql_real_escape_string($details[1]),mysql_real_escape_string($details[2])));
}

答案 1 :(得分:1)

旁注。无论循环有多小(迭代次数少)都不要在其中放置查询。而是仅使用循环来构造包含所有数据的一个复杂查询,然后在循环外执行查询。

编辑:您可以在循环中构建的查询示例。

INSERT INTO table 
    (name, age, position)
VALUES
   ('Shabbir', 26, 'Designer'),
   ('Burhan', 24, 'Architecture'),
   ('Huzeifa', 20, 'Accountant');

答案 2 :(得分:0)

您的SQL查询位于错误的位置:

foreach ($company as $employees=>$details)
{
    echo '<strong>'.$employees.'</strong><br>';
        foreach($details as $employeeinfo)
        {
            echo $employeeinfo.'<br>';
        }
    $sql = "INSERT INTO biodata (Name, Age, Description) VALUES ($details[0], $details[1], '$details[2]')";
    mysql_query($sql);
}