使用php mysql在动态表中插入数据

时间:2015-04-06 14:17:17

标签: php mysql

insert.php

<?php
$nidErr = $scodeErr = $constituencyErr = "";
$nid = $scode = $constituency = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {

if (empty($_POST["nid"])) {
$nidErr = "*";
} else {
$nid = test_input($_POST["nid"]);
}

if (empty($_POST["scode"])) {
$scodeErr = "*";
} else {
$scode= test_input($_POST["scode"]);
}

if (empty($_POST["constituency"])) {
$constituencyErr = "*";
} else {
$constituency= test_input($_POST["constituency"]);

}
}

function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data; }
?>


<input type="button" value="Add Row" onclick="addRow('dataTable')">

<input type="button" value="Delete Row" onclick="deleteRow('dataTable')">

<table id="dataTable" width="350px" border="1">
<tbody><tr>
<td><input type="checkbox" name="chk[]"></td>
<td>National ID Number<span class="error">* <?php echo $nidErr;?></span>     

<input type="text" name="nid[]"></td>
<td>Security Code <span class="error">* <?php echo $scodeErr;?></span><input  

type="text" name="scode[]"></td>

<td><span class="error">* <?php echo $constituencyErr;?></span>
<select name="constituency[]">
<option value="in">Select Constituency</option>
<option value="de">Mirsorai1</option>
<option value="fr">Comilla1</option>
<option value="us">Dhaka1</option> 
<option value="ch">Sylhet1</option>
</select>
</td>
</tr>
</tbody></table>


<br><input type = "submit" value = "submit">

</form> 

insert_post.php

<?php
if ( $_POST["nid"] && $_POST["scode"] && $_POST["constituency"] ){

include("dbcon.php");

foreach($constituency as $a => $b){
$a+1;
$nid = $_POST['nid'][$a];
$scode = $_POST['scode'][$a];
$constituency = $_POST['constituency'][$a];

mysql_query("INSERT INTO voterlist(constituency,scode,nid)
VALUES ('$constituency', '$scode', '$nid')");
}

}

?>

<table id='display'>

<tr>  
<td><?php echo "National ID:<br>" ; ?></td>
<td><?php echo "Security Code:<br>" ; ?></td> 
<td><?php echo "Constituency:<br>" ; ?></td> 



<hr>
</tr>


<tr>
<td><?php echo "<br>" .$nid; ?></td>
<td><?php echo "<br>".$scode; ?></td> 
<td><?php echo "<br>".$constituency; ?></td> 

</tr>


<?php   

?> 
</table>

****我想在insert_post.php页面中显示数据。但它显示错误,数据也没有存储在后端。我对foreach循环感到困惑。我想就此提出一些建议。

1 个答案:

答案 0 :(得分:0)

Foreach独自走路阵列

为此目的,您不需要$ a + 1或代码中[$ a]的引用

如果您对变量和POST输入使用相同的名称(这似乎是您的情况),以下建议可以正常工作

首先定义一个safe()函数,在其中处理注释中提到的可能的SQL注入攻击

然后

foreach ($_POST as $key => $value){
    $$key = safe($value);
}

将检索您要查找的值

希望它有所帮助!