I've got a search bar and I created a query in my code but I now want to create a stored procedure for it so I can just call it whenever I need it instead of having the query in my code.
However, it seems like I'm not able to create a stored procedure in mysql as I've used binding parameters. LIKE CONCAT('%',:title,'%')
public function search($searchTerm) {
$db = Db::getInstance();
$req = $db->prepare("SELECT p.postID, p.title, p.tagID, p.content, p.date, p.postImage, u.username "
. " FROM user as u inner JOIN user_post as UP on u.userID=up.userID inner JOIN post as p "
. "on up.postID=p.postID WHERE p.title LIKE CONCAT('%',:title,'%')");
$req ->execute(array('title' => $searchTerm));
$posts = [];
foreach ($req->fetchAll() as $blogPost) {
array_push($posts, new Post($blogPost['postID'], $blogPost['title'], $blogPost['tagID'], $blogPost['content'], $blogPost['date'], $blogPost['postImage'], $blogPost['username']));
}
if (empty($posts)) {
return null;
} else {
return $posts;
}
}
Does anyone know what my stored procedure should look like and how I'd call it?
The proc would look like this:
CREATE PROCEDURE MyProc(IN in_title TEXT)
BEGIN
SELECT p.postID, p.title, p.tagID, p.content, p.date, p.postImage, u.username
FROM user as u inner JOIN user_post as UP on u.userID=up.userID inner
JOIN post as p ON up.postID=p.postID
WHERE p.title LIKE CONCAT('%', in_title, '%');
END
Be careful to name your proc's input parameter something distinct from any of the columns of your table, or else you could get unexpected results.
You do NOT need to use a prepared statement in this procedure. Just use your procedure parameter in the expression in your SQL statement.
You don't need to write any cursor in the proc to process the result. The default thing a MySQL proc does with a SELECT statement is return its result.
You'd call it from PHP this way:
$req = $db->prepare("CALL MyProc(:title)");
All the rest of your PHP code would be identical.
Frankly, I wouldn't bother with this procedure. It doesn't really help reduce your code much. But it does:
I hardly ever use any MySQL stored procedures.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.