0

我创建了一个名为“test”的数据库并创建了一个名为“biodata”的表。我在生物数据表中创建了 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);

?>
4

3 回答 3

1

mysql_query应该在你的foreach陈述中......你还需要清理你的数据,因为SQL Injection

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

更正

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])));
}
于 2012-04-17T19:50:32.403 回答
1

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

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

INSERT INTO table 
    (name, age, position)
VALUES
   ('Shabbir', 26, 'Designer'),
   ('Burhan', 24, 'Architecture'),
   ('Huzeifa', 20, 'Accountant');
于 2012-04-17T20:00:42.703 回答
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);
}
于 2012-04-17T19:46:25.910 回答