I have just looked at a YouTube video on how to create a custom database. I have tried to implement this into my site. However, obviously, it isn't working...
I get an error 'Query failed: ' and nothing more from the following code.
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect to database");
mysql_select_db("$db_name")or die("cannot select DB");
$con=mysqli_connect("$host","$username","$password","$db_name");
$terms = explode(" ", $search);
$query = "SELECT * FROM search WHERE ";
foreach ($terms as $each){
$i++;
if ($i == 1)
$query .= "keywords LIKE '%each%' ";
else
$query .= "OR keywords LIKE '%each%' ";
}
$query = mysql_query($query);
$numrows = mysql_num_rows($query) or die('Query failed: ' . mysql_error() . "<br />\n$sql");
if ($numrows > 0)
while($row = mysqlfetch_ASSOC($query)){
$id = $row['id'];
$title = $row['title'];
$description= $row['description'];
$keywords = $row['keywords'];
$link = $row['link'];
echo '<h2><a href="$link">$title</a><h2>
$description<br/><br/>';
}
else
echo "No results found";
//disconnect
mysql_close();
?>
To be honest, I only understand about 70% of that and have no idea. The database is connected properly and functions. WHAT AM I DOING WRONG???
mysql_num_rows was causing problems before but after putting a space inbetween WHERE'' and the closing quotation mark, it left me here.
First off....you need to include the $each to include the variable...not just each...
$query .= "WHERE keywords LIKE '%{$each}%' ";
Also....Move the WHERE infront of keywords, so that if a user enters nothing into the search...they will query everything...otherwise if they enter nothing, it will break...
$terms = explode(" ", $search);
$query = "SELECT * FROM search ";
if(!empty($terms)){
foreach ($terms as $each){
$i++;
if ($i == 1)
$query .= "WHERE keywords LIKE '%{$each}%' ";
else
$query .= "OR keywords LIKE '%{$each}%' ";
}
}