下午好。您需要编辑数据库中的数据。首先,我选择所需的表。HTML:
<div class="col-lg-3" id = "block3">
<form id="form_edit">
<label>Редактирование</label>
<select class="form-control" name="edit" id = "edit">
<option value = "category">category</option>
<option value = "image">image</option>
<option value = "model">model</option>
<option value = "news">news</option>
<option value = "users">users</option>
</select>
<input type="button" id="edit_send" value = "Редактировать запись">
</form>
</div>
<script>
$('#edit_send').on('click',function(){
var table = $('#edit').val();
$.ajax({
type : "POST",
url: "admin_edit_script.php",
data: {table:table},
success : function(result){
url = "admin_form_edit.php" + '?param1='+table;
window.location.href = url;
},
error: function(xhr, resp, text) {
console.log(xhr, resp, text);
}
})
}
);
<script>
我将表名转移到另一个文件并形成字段。
if($_GET["param1"] == 'image') {
$sql = "SELECT * FROM image order by id";
$result = pg_query($connect, $sql);
echo "<form method = 'post' action = 'admin_edit_script.php'>";
while ($row = pg_fetch_array($result)) {
echo '<input type = checkbox id = "id" name = "id" value="'.$row["id"].'">
<input type = "text" id = "primary_name" name = "primary_name" value ="' . $row["primary_name"] . '">
<input type = "text" id = "secondary_name" name = "secondary_name" value ="' . $row["secondary_name"] . '">
<input type = "text" id = "link" name = "link" value ="' . $row["link"] . '">
<br>';
}
echo "<input type='hidden' id = 'table' name = 'table' value = '".$_GET['param1']."'><input type='submit'></form>";
}
和我想的一样。复选框包含条目的 id。当您点击按钮时,您需要将数据发送到另一个文件以执行更新请求并更新其 id 与所选 id 匹配的记录。但是结果,当我更新所有字段时,我得到了最后一个字段的值。
在这里您可以在照片中看到:我标记了该字段并对其进行了编辑。但最后,所有字段都从最后一个字段中获取它们的值。我怀疑这是因为所有输入都具有相同的名称。请求本身:
if(($_POST["table"] == "image") and (isset($_POST["id"]))){
$id = intval($_POST["id"]);
$sql = "update image set primary_name = '".$_POST["primary_name"]."', secondary_name = '".$_POST["secondary_name"]."', link = '".$_POST["link"]."' where id = '".$id."'";
$result = pg_query($connect, $sql) or die("fgdgdfg");
}
告诉我如何正确组织一切?因为我没有通过 PHP 编辑表格中的数据的正常经验。表本身
首先,您需要更正表单,输入字段的名称属性应该看起来像这样 name="id[]" 等等所有具有相同名称的。
并使代码看起来像:
一般来说,对于这样的事情,我沉迷于框架(Yii2、Laravel、Zend 等)。我自己用过Yii2。很重,但是如果您需要快速组装一些东西来处理数据库中的数据,就是这样。
希望对你有帮助,祝你好运!