【发布时间】:2021-07-01 16:47:27
【问题描述】:
我正在尝试将选择选项的名称而不是值存储在 MySQL 数据库中。当前代码在数据库中存储客户 ID 而不是客户名称。我知道你们中的一些人会说为什么不在 name 属性中使用 $customer_result['name'] 但如果我这样做了,那么我将无法使用 id 过滤记录
MYSQL 和 PHP
<?php
$select_customer = "select * from customer";
$select_customer_query = mysqli_query($connection, $select_customer); // Customer Data
if(isset($_POST['add-sale-btn'])) {
$customer_name = mysqli_real_escape_string($connection, $_POST['customer_name']);
$customer_address = mysqli_real_escape_string($connection, $_POST['customer_address']);
$insert_sale = "insert into sale(customer_name, customer_address) values('$customer_name','$customer_address')";
$insert_sale_query = mysqli_query($connection, $insert_sale);
}
?>
<form method="post" action="">
<div class="form-group">
<select class="form-control" id="customer_name" name="customer_name">
<option>Customer Name</option>
<?php while($customer_result = mysqli_fetch_assoc($select_customer_query)) { ?>
<option value="<?php echo $customer_result['id']; ?>"><?php echo $customer_result['name']; ?></option>
<?php } ?>
</select>
</div>
<div class="form-group" style="margin-top:10px;">
<input type="submit" class="btn btn-primary" name="add-sale-btn" value="Save">
</div>
</form>
JQuery 代码
<script>
$(document).ready(function(){
$('#customer_name').on('change', function(){
var customer_name = $('#customer_name').val();
$.ajax({
url: 'customer-detail.php',
type: 'POST',
data: {id : customer_name},
success: function(customer_data){
$('#customer_detail').html(customer_data);
}
});
});
});
</script>
customer-detail.php
$select_customer_detail = "select * from customer where id={$_POST['id']}";
$customer_detail_query = mysqli_query($connection, $select_customer_detail);
$customer_detail_result = mysqli_fetch_assoc($customer_detail_query);
<div class="form-group">
<input type="text" class="form-control" name="customer_address" value="<?php echo $customer_detail_result['address']; ?>">
</div>
【问题讨论】:
-
这听起来像是一个 XY 问题 - 在这种特殊情况下存储 ID 有什么问题......?为什么要存储可变属性而不是存储(表面上)不可变的 ID?
-
警告:您对SQL Injections 持开放态度,应该使用参数化的prepared statements,而不是手动构建查询。它们由PDO 或MySQLi 提供。永远不要相信任何形式的输入!即使您的查询仅由受信任的用户执行,you are still in risk of corrupting your data。 Escaping is not enough!
-
这是对
$select_customer_detail = "select * from customer where id={$_POST['id']}";的引用,它接收 POST 中发送的任何内容并直接发送到数据库 -
为什么要在 customer_name 列中存储 id?我在 value (select) 属性中传递 id 因为我需要通过 ajax 将它传递给服务器,然后过滤记录 @esqew
-
????如果您刚刚开始使用 PHP 并想构建应用程序,我强烈建议您查看各种 development frameworks 看看是否能找到适合您风格的需要。它们有多种风格,从 Fat-Free Framework 之类的轻量级到 Laravel 之类的更全面。这些为您提供了具体的工作示例以及如何编写代码和组织项目文件的指导。