我正在尝试通过 $_POST 数组和 FORM 更新 MySQL 数据库。这是我编写的代码,经过简化。
在第 1 页中,我得到一个包含 5 个数组的数组,它只是最后一个可用于更新的“文本框”,它会更新整个列,所有 5 个。我希望能够更新单个单元格。
这个问题我已经问过一次了,但是把代码涂白了,所以这里是:
第 1 页
<form method="POST" action="showpost.php" enctype="multipart/form-data" ><tr><td>
<?php
$host = "***";
$username1 = "***";
$password1 = "***";
$db_name = "***";
$tbl_name = "***";
mysql_connect("$host", "$username1", "$password1") or die("Can’t connect ");
mysql_select_db("$db_name") or die ("No connection to table ");
$foresp1 = mysql_query("SELECT * FROM $tbl_name");
while($data = mysql_fetch_array($foresp1))
{
$example = $data[3];
echo "<input type='text' value='$example' name='examplearray[]' size='10'><br>";
}
?>
</td></tr></table>
<input type="submit" value="Update">
</form>
第 2 页 - (showpost.php)
<?php
$host = "***";
$username1 = "***";
$password1 = "***";
$db_name = "***";
$tbl_name = "***";
mysql_connect("$host", "$username1", "$password1") or die("Can’t connect ");
mysql_select_db("$db_name") or die ("No connection to table ");
{
foreach($_POST['examplearray'] as $value)
{
mysql_query("UPDATE $tbl_name SET example_cell = '$value'");
}
}
?>
我在这里做错了什么?
最佳答案
这是一个片段,您应该尝试在插入时调整您的查询和数据。 我仍然不明白你有什么数据,所以我不能具体说明。
<?php
$host = "***";
$username1 = "***";
$password1 = "***";
$db_name = "***";
$tbl_name = "***";
// pdo is built into to newer versions of php, you should be able to do this
// this will help eliminate sql injection issues (data sanitation)
$db = new PDO("mysql:host=$host;dbname=$db_name", $username1, $password1);
if (!$db) {
die('no connection to table');
}
// you havent posted whats in $_POST and the inputs you have are also vague...
// lets say you want to update a name or a address and you have the row id
// so post has the following
// $_POST['name'] = 'some data the user posted from the form or a long name';
// $_POST['address'] = 'some other long data';
// $_POST['id'] = 16;
// you may want to check if the data is posted, not just assume the data is there
$dataToInsert = array(
':name' => $_POST['name'],
':bindvalue' => $_POST['address'],
':id' => $_POST['id']
);
// this creates a statement
$stmt = $db->prepare("UPDATE $tbl_name SET name = :name, address = :bindvalue WHERE row_id = :id");
// by executing your statement like this, you help protect against sql injection
$result = $stmt->execute($dataToInsert);
?>
关于php - $_POST 数组到 MySQL _v2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22487864/