我的脚本使用PHP,我使用jQuery自动完成一个webform来注册事件。jQuery在name
文本字段上工作,并在选择名称后完成所有其他文本字段。
但是,我的数据库存储过去事件的所有记录。例如,Susan参加了我之前的5次活动,当我键入name
时,textfield将显示5个Susan。我如何过滤掉相同的名字?
我的jQuery代码:
$('input.item-autocomplete').on('autocompleteselect', function (e, ui) {
$.ajax({
url:"ajax_reg.php",
dataType:"json",
data:{
'name' : ui.item.value,
'action' : 'get_fulldata'
},
success:function(data){
$("#mobile1").val(data.mobile1);
$("#mobile2").val(data.mobile2);
$("#email").val(data.rt_email);
$("#tf1").val(data.tf1);
$("#tf2").val(data.tf2);
$("#tf3").val(data.tf3);
}
});
});
更新:对不起,我忘记了SQL代码,我正在另一个php文件中编写SQL。(SQL代码adjax_reg.php)
<?php
$name = $_GET['name'];
$action = empty($_GET['action'])?'':$_GET['action'];
if(empty($name)){
exit('No data');
}
require_once("../winphplib/kernel.php");
require_once ('../winphplib/dbconnect_egen.php');
if($action=='get_name'){
$sqlquery = "SELECT rt_name FROM reg_ticket WHERE rt_name LIKE '%$name%' LIMIT 15";
$result = mysql_query($sqlquery) or die(mysql_error());
while($myrow = MySQL_fetch_array($result)){
$data[] = strtoupper($myrow['rt_name']);
}
}elseif($action=='get_fulldata') {
$sqlquery = "SELECT * FROM reg_ticket WHERE rt_name = '$name' LIMIT 1";
$result = mysql_query($sqlquery) or die(mysql_error());
$data = mysql_fetch_assoc($result);
if(count($data)>0){
list($data['mobile1'], $data['mobile2']) = explode("-", $data['rt_contact']);
list($data['tf1'], $data['tf2'], $data['tf3']) = explode("-", $data['rt_ic']);
}
}
mysql_free_result($result);
echo json_encode($data);
发布于 2018-05-25 01:47:13
您需要获得users
的条件,他们参与的标准,至少一个事件。您可能加入了users
和events
,但是您需要根据它们的participation
过滤users
。假设您使用的是以下表:
用户(id,mobile1,mobile2,电子邮件,tf1,tf2,tf3) 事件(id,名称) 参与活动(id、user_id、event_id)
您需要这样的查询:
select id, mobile1, mobile2, email, tf1, tf2, tf3
from users
where exists (select 1
from participations
where users.id = participation.user_id)
and users.name like '%Susan%'
这将为每个用户返回一条记录,其中包含参与至少一个事件的搜索文本,为您提供所需的列。
编辑
我已经看过你编辑的问题了,还有很多问题要解决。
避免在查询中使用SELECT *
问题:
在select子句中使用列列表确保只选择所需的内容:
select mobile1, mobile2, rt_contact, tf1, tf2, tf3, rt_ic ...
会解决这个问题的。
解决你的问题
您必须使用不同的关键字
select distinct mobile1, mobile2, rt_contact, tf1, tf2, tf3, rt_ic ...
这将选择distinct
值,但如果存在不一致,即同一人的名称相同的不同属性,则将返回多条记录。
自动完成将无法工作,如果没有
如果您想要使用LIKE
和%...%
,就像在if
中一样,如果您希望select
用户的name
包含您传递的文本,则必须使用name
。而且,如果select
并不是唯一的,那么它也不会伤害name
,可能也不会伤害id
。
不推荐使用mysql_函数
永远不要使用查询中的用户输入。
这很容易导致SQL注入,黑客很容易对您的数据库造成伤害,甚至加载他们没有资格加载的数据。将参数化查询与PDO一起使用,或转义参数。
不要编写意大利细面代码
如果将处理数据库的部件从引擎部件与视图部件分离,代码更容易维护。
使数据库规范化
发布于 2018-05-25 01:34:23
在PHP脚本中,只需添加一个GROUP BY
子句,就可以调整SQL查询。
我还没有看到您的查询,但是类似这样的内容:
SELECT * FROM events
JOIN artists ON events.artist_id = artists.id
WHERE artist like :searchterm
GROUP BY artists.artist_name
https://stackoverflow.com/questions/50525792
复制