I have been trying to make a website to sell books where I have a mysql database of books and their authors. I wish to add a search bar on the main page (where the list of all books is printed using basic PHP and mysql).
I am still not sure about how to go about it, so here is what I intent to do:
- Connect to database
- Take a search query using POST method and make action to, let's say, search.php, for example, let's say the entry was "social change"
- In search.php, use explode() to break query sentences into words/keywords and make an array of it. So the query becomes an array with [0] => 'social' and [1] => 'change'
- In my existing database, let's say I have an entry of a book called "dynamics of social change". I make another column in my database that has an array of (dynamics, of, social, change) corresponding to that book. (((HOW to do it using mysql?))))
- Use SQL Queries to SELECT the entry from WHERE the book-name array contains any of the elements of my keyword array.
- Print, if any result found.
Here is what I have done: From index.php
<form action= 'search.php' method='post'>
<input type='text' name='q'>
<input type='submit'>
</form>
From search.php, after connecting to database:
$q = $_POST["q"];
$keys = explode(" ", $q);
$x = 0;
echo "<table>";
while ($x < sizeof($keys))
{
$req = "SELECT * FROM book WHERE name= '$keys[$x]'";
$run = mysqli_query($connect,$req)
or die('Query req failed: ' . mysql_error());
while
($line = mysqli_fetch_array($run, MYSQL_ASSOC))
{
echo "<tr>";
echo "<td>" . $line['name'] . "</td>";
echo "</tr>";
}
$x = $x + 1;
}
echo "</table>";
The problem I am facing is that I am not getting any output. I tried different inputs but I can not figure out the mistake.
What I want to ask: 1. Am I doing it correct logically? Considering the fact that I am a newbie in PHP and mysql, is it logically correct way to do a search? If no, can you suggest any simple/basic way for this simple web project?
If what I intend to do is right, can you help me figure out where am I making mistake?
I am yet to find out the HOW part in step 4, i.e., making another column in mysql database consisting of an array with elements that are basically words split from book titles. For example, Column A: "Dynamics of social change" Column B: (Dynamics, of, social, change)