您已经制作了一个PHP脚本,用户可以选择或添加多个条目到数据库中,例如用户可以一次添加10个项目的10个区域,但主要问题是只有最后一个添加到数据库中而不是所有数据都分成多个条目,这里是代码,它的名字是final.php
<?php
if(isset($_POST['multi'])){
echo "<form action='final.php' method='POST'>";
$a = $_POST['number'];
$b = 0 ;
$c = $_POST['country'];
$d = $_POST['state'];
echo"<table border='1'><tr><td colspan='7'>Country:<input type='text'
name='country' value='$c'></td></tr>";
while($a != $b){
$b++;
echo "
<tr>
<td>State</td>
<td>Name</td>
<td>Main Information</td>
<td>Second Information</td>
</tr>
<tr>
<td><input type='text' name='state".$b."' value='$d'></td>
<td><textarea name='name".$b."'></textarea></td>
<td><textarea name='info1".$b."'></textarea></td>
<td><textarea name='info2".$b."'></textarea></td>
</tr>
";
};
echo "</table></br>Total:<input type='text' name='total' value='$a'>";
echo"<input type='submit' name='Add' value='Add'></form>";
}
elseif(isset($_POST['Add'])){
$a1 = $_POST['total'];
$b1 = 0;
$c1 = $_POST['country'];
echo "There is $a1 types in here";
$cn = mysql_connect("127.0.0.1","root","");
if(!$cn)
{
die('Could not connect:'.mysql_error());
}
mysql_select_db("test",$cn);
while($a1 != $b1){
$b1++;
$state = "state".$b1;
$name = "name".$b1;
$info1 = "info1".$b1;
$info2 = "info2".$b1;
$sq="INSERT INTO ftable(Country, State, Name, First, Second ) VALUE('$c1', '$_POST[$state]', '$_POST[$name]', '$_POST[$info1]', '$_POST[$info2]')";
echo "</br>Country:$c1</br>
State:".$_POST[$state]."</br>
Name:".$_POST[$name]."</br>
Info1:".$_POST[$info1]."</br>
Info2:".$_POST[$info2]."</br>";
}
if (!mysql_query($sq,$cn))
{
die('Error:'.mysql_error());
}
echo"<palign='center'>You have added $a to the dbms</br>";
}
else{
echo"<form action='final.php' method='POST'>
<input type='number' name='number'>
<input type='text' name='country' value='country'>
<input type='submit' value='Generate' name='multi'>
</form>";
}
?>
非常感谢,如果有人可以帮我解决此问题,我会非常感激,并且我只是编写了一个noob
答案 0 :(得分:1)
这是因为您在while
循环之外执行查询。解决方案是在while循环中移动mysql_query($sq, $cn)
。您的插入查询还有VALUE
而不是VALUES
,请参阅insert syntax。
while($a1 != $b1){
$b1++;
$state = "state".$b1;
$name = "name".$b1;
$info1 = "info1".$b1;
$info2 = "info2".$b1;
$sq="INSERT INTO ftable(Country, State, Name, First, Second ) VALUES('$c1', '$_POST[$state]', '$_POST[$name]', '$_POST[$info1]', '$_POST[$info2]')";
echo "</br>Country:$c1</br>
State:".$_POST[$state]."</br>
Name:".$_POST[$name]."</br>
Info1:".$_POST[$info1]."</br>
Info2:".$_POST[$info2]."</br>";
if (!mysql_query($sq,$cn))
{
die('Error:'.mysql_error());
}
echo"<palign='center'>You have added $a to the dbms</br>";
}
请注意,您的代码容易受到SQL注入攻击,您应该使用mysql_real_escape_string进行调查,如下所示:
$a = mysql_real_escape_string($_POST['number']);
$c = mysql_real_escape_string($_POST['country']);
$d = mysql_real_escape_string($_POST['state']);