mysqli - PHP - Include variables on condition in mysqli_stmt_bind_param
Get the solution ↓↓↓I'm writing a function for a search query. users can search with category and keyword. I also want to add an option to search all records or only user's records.
One of the field will always be there. either keyword or category.
Now I''m trying to makemysqli_stmt_bind_param
adjust to the query.
With my current knowledge, I'm writing a lot of if/else if conditions.
Later one I'll be adding another field location. which means more if/else
Is there a better way to do this?
function filter_records($db, $fields, $keyword, $category, $status, $user = '')
{
if (empty($keyword) and empty($category)) {
return false;
}
$keyword = empty($keyword) ? "" : "%$keyword%";
$keyword_query = !empty($keyword) ? "(title LIKE ? OR tagline LIKE ? OR description LIKE ? OR tags LIKE ?)" : '';
$add_and = empty($keyword_query) ? '' : ' AND ';
$category_query = !empty($category) ? "$add_and categories LIKE ?" : '';
$user_query = !empty($user) ? 'AND user_id = ?' : '';
$sql = "SELECT $fields FROM mc_listings WHERE $keyword_query $category_query $user_query AND status = ? ORDER BY id DESC";
$stmt = mysqli_stmt_init($db);
if (mysqli_stmt_prepare($stmt, $sql)) {
mysqli_stmt_bind_param($stmt, 'sssssss', $keyword, $keyword, $keyword, $keyword, $category, $status, $user);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
mysqli_stmt_close($stmt);
return $result;
}
return false;
}
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: object not found by the @paramconverter annotation.
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.