我创建了一个名为“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);
?>
答案 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);
}