无法使用mysqli_real_escape_string()在表单提交方法中获取数组值

时间:2018-08-02 10:10:49

标签: php arrays submit

提交页面

<form  id='frmFeePayment' action="payment-obj.php" method="post">    
<input type='hidden' name='hdnStudentDbKey[]' id='hdnStudentDbKey' value='$StudentDbKey'/>
<input type='hidden' name='hdnFeeAmountDbKey[]' id='hdnFeeAmountDbKey' value='$FeeAmountDbKey'/>
<input type='hidden' name='hdnFeeNameDbKey[]' id='hdnFeeNameDbKey' value='$FeeNameDbKey'/>  

</form>

在我的数据接收页面中。 Payment-obj.php

$conn = mysqli_connect("localhost", "root", "", "TestDB");
if (mysqli_connect_errno($conn)) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$StudentDbKey = mysqli_real_escape_string($conn,$_POST['hdnStudentDbKey']);
$FeeAmountDbKey = mysqli_real_escape_string($conn,$_POST['hdnFeeAmountDbKey']);
$FeeNameDbKey = mysqli_real_escape_string($conn,$_POST['hdnFeeNameDbKey']);

使用上述代码无法获得价值。 但是,如果我使用直接的$ _POST方法,我将获得价值。

$StudentDbKey = $_POST['hdnStudentDbKey'];
$FeeAmountDbKey = $_POST['hdnFeeAmountDbKey'];
$FeeNameDbKey = $_POST['hdnFeeNameDbKey'];

谁能告诉我mysqli_real_escape_string()有什么问题

谢谢

2 个答案:

答案 0 :(得分:0)

您必须获取以下值

$StudentDbKey = $_POST['hdnStudentDbKey'][0];
$FeeAmountDbKey = $_POST['hdnFeeAmountDbKey'][0];
$FeeNameDbKey = $_POST['hdnFeeNameDbKey'][0];

这种类型的数组对于输入类型具有相同的名称很有用。

只需尝试打印$ _POST数组,您将得到它

答案 1 :(得分:0)

PHP使用方括号语法将表单输入转换为数组,因此在html表单中使用name="hdnStudentDbKey[]"时,您将获得一个数组。

执行此操作时:

$StudentDbKey = $_POST['hdnStudentDbKey']; // Returns an array
print_r($StudentDbKey); // Shows you all the values in the array

但是对于mysqli_real_escape_string()函数,您必须插入字符串值。不是数组值。

所以您可以这样做:

$StudentDbKey = mysqli_real_escape_string($conn,$_POST['hdnStudentDbKey'][0]); 
$FeeAmountDbKey = mysqli_real_escape_string($conn,$_POST['hdnFeeAmountDbKey'][0]); 
$FeeNameDbKey = mysqli_real_escape_string($conn,$_POST['hdnFeeNameDbKey'][0]);

mysql_real_escape_string整个数组,简单的方法:

$_POST['hdnStudentDbKey'] = array_map("mysql_real_escape_string", $_POST['hdnStudentDbKey']);
$_POST['hdnFeeAmountDbKey'] = array_map("mysql_real_escape_string", $_POST['hdnFeeAmountDbKey']);
$_POST['hdnFeeNameDbKey'] = array_map("mysql_real_escape_string", $_POST['hdnFeeNameDbKey']);