Searching a string within a table is quite easy, but searching within multiple tables in a database need a little trick. I know it’s not the good one, perhaps everybody who read this can share yours too 😉
Example: We have 3 tables with different content and structures for 3 different pages (News, Articles, Products)
< ?php
$string = $_POST['what'];
# 1. Search for News and store it into array
$search_news = mysql_query("SELECT * FROM table_news WHERE news_title LIKE '%$string%' OR news_content LIKE '%$string%' ");
while($result=mysql_fetch_array($search_news)){
$array_results[] = array($result['news_title'], "news.php?id=".$result['news_id']);
}
# 2. Search for Articles and store it into array
$search_articles = mysql_query("SELECT * FROM table_articles WHERE articles_title LIKE '%$string%' OR articles_content LIKE '%$string%' ");
while($result=mysql_fetch_array($search_articles)){
$array_results[] = array($result['articles_title'], "articles.php?id=".$result['articles_id']);
}
# 3. Search for products and store it into array
$search_products = mysql_query("SELECT * FROM table_products WHERE products_name LIKE '%$string%' OR products_content LIKE '%$string%' ");
while($result=mysql_fetch_array($search_products)){
$array_results[] = array($result['products_name'], "products.php?id=".$result['products_id']);
}
// all result now is in the array $array_results. index [0] is for Title, and index [1] is for the URL
echo "
";
foreach($array_results as $search_result){
echo "
";
}
echo "";
?>
Leave a Reply