[英]Why does my query returns 0 rows using LIKE with php PDO
so I have this ajax keyup search event in my js 所以我的js中有这个ajax keyup搜索事件
$("#search").keyup(function(){
var searchText = $('#search').val();
var searchBy = $('#searchBy').val();
var newObj = { action: "search",
searchText: searchText,
searchBy: searchBy
}
$.ajax({
method: "POST",
url:"../_tasklogger/classes/tasklog-functions.php", //the page containing php script
dataType: 'html',
data: newObj,
success: function(response){
$("#taskTable").html(response);
},
error: function (req, status, err) {
console.log('Something went wrong', status, err, req);
}
});
});
which calls this php function below: 在下面调用此php函数:
$searchText = $_POST['searchText'];
$searchBy = $_POST['searchBy'];
$limit = 5;
$sql = "SELECT *
FROM tasks
WHERE userId = :userid and :searchby LIKE :searchtext
LIMIT :datalimit";
$stmt = $db_con->prepare($sql);
$searchText = $searchText."%";
$stmt->bindParam(":userid", $_SESSION['userid']);
$stmt->bindParam(":searchby", $searchBy);
$stmt->bindParam(":searchtext", $searchText, PDO::PARAM_STR);
$stmt->bindParam(":datalimit", $limit, PDO::PARAM_INT);
if($stmt->execute()){
echo'<tr>
<th>Date</th>
<th>Task Name</th>
<th>Duration</th>
<th>Start Time</th>
<th>End Time</th>
<th colspan="2" style="text-align:center;">Action</th>
</tr>';
while ($row = $stmt->fetch()){
echo '<tr>';
echo '<td>'.$row['taskDate'].'</td>';
echo '<td>'.$row['taskName'].'</td>';
echo '<td>'.$row['duration'].'</td>';
echo '<td>'.$row['startTime'].'</td>';
echo '<td>'.$row['endTime'].'</td>';
echo '<td>
<button id="editbtn" value="'.$row['taskId'].'" class="btn waves-effect waves-light orange lighten-1 hoverable">Edit</button>
</td>';
echo '<td>
<button id="deletebtn" value="'.$row['taskId'].'" class="btn waves-effect waves-light red lighten-1 hoverable">Delete</button>
</td>';
echo '</tr>';
}
}
But it does not return anything. 但是它不返回任何东西。 I have tested the query in the database and it works fine.
我已经在数据库中测试了查询,并且工作正常。 I think the thing that is causing the problem is in my
$searchText
variable. 我认为引起问题的是在我的
$searchText
变量中。
Thank you for anyone that can help me! 谢谢任何能帮助我的人!
Understanding PDO like statements: 了解类似PDO的语句:
This is WRONG: 这是错误的:
"SELECT * FROM `users` WHERE `name` LIKE '%:key%'";
The CORRECT solution is to leave clean the placeholder like this: 正确的解决方案是像这样保持干净的占位符:
"SELECT * FROM `users` WHERE `name` LIKE :key";
And then add the percentages to the php variable where you store the keyword: 然后将百分比添加到存储关键字的php变量中:
$key= "%".$key."%";
Reference php PDO manual. 参考php PDO手册。
Hope it helps you. 希望对您有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.