我有两个单独的输入字段,一个搜索姓氏,另一个名称搜索数据库。
<li><label>Surname: </label><input type="text" name="surname" id="search_text" required autocomplete="off" /></li>
<li><label>Name: </label><input type="text" name="name" id="name" required autocomplete="off"/></li>
<script> // first input live search
$(document).ready(function() {
$("#search_text").keyup(function () {
var txt = $(this).val();
setTimeout(function() {
if(txt.length>=3)
{
$.ajax({
url:"fetchsurname.php",
method:"post",
data:{search:txt},
dataType:"text",
success:function(data)
{
$('#searchresults').html(data);
}
});
}
else
{
$('#searchresults').html('');
}
}, 2000); // 1 sec delay to check.
}); // End of keyup function
}); // End of document.ready
</script>
<script> // second input live search
$(document).ready(function() {
$("#name").keyup(function () {
var txt = $(this).val();
setTimeout(function() {
if(txt.length>=3)
{
$.ajax({
url:"fetchname.php",
method:"post",
data:{search:txt},
dataType:"text",
success:function(data)
{
$('#searchresults').html(data);
}
});
}
else
{
$('#searchresults').html('');
}
}, 2000); // 1 sec delay to check.
}); // End of keyup function
}); // End of document.ready
</script>
使用两个单独的php fetchname和fetchsuurname
文件搜索数据库“SELECT * FROM base WHERE name LIKE'”。$ _ POST [“search”]。“%'”
“SELECT * FROM base WHERE surname LIKE'”。$ _ POST [“search”]。“%'”
我的问题是每个字段都在表中搜索自己的值,而不是与第一个字段结合以显示结果。
答案 0 :(得分:0)
根据你的html,你应该改变jQuery和以下代码:
<li><label>Surname: </label><input type="text" name="surname" id="search_text" required autocomplete="off" /></li>
<li><label>Name: </label><input type="text" name="name" id="search_name" required autocomplete="off"/></li>
<script> // first input live search
var keyupfunction = function () {
var search_text = $("#search_text").val();
var search_name = $("#search_name").val();
setTimeout(function() {
if(txt.length>=3)
{
$.ajax({
url:"fetchsurname.php",
method:"post",
data:{"surname":search_text, "name":search_name},
dataType:"text",
success:function(data)
{
$('#searchresults').html(data);
}
});
}
else
{
$('#searchresults').html('');
}
}, 2000); // 1 sec delay to check.
}
$(document).ready(function() {
$("#search_text").keyup(keyupfunction);
$("#search_name").keyup(keyupfunction);
});
您可以在查询中使用或在查询中使用:
SELECT * FROM base WHERE name LIKE '".$_POST["name"]."%' AND surname LIKE '".$_POST["surname"]."%'
如果您不希望两个字段都具有值
,也可以使用Or还有另一个解决方案,你可以联合2选择2个不同的表
SELECT * FROM base WHERE name LIKE '".$_POST["name"]."%'
union all
SELECT * FROM base WHERE surname LIKE '".$_POST["surname"]."%'