I'm a newbie to PHP and MySQL. Trying to make a common search field for my website, which searches 3 different tables with different structure with the same keyword. 3 tables are course, lecture, faq.
My code is something similar: `
<?php
if(isset($_POST['submit'])) {
//connect to the database
$mysqli = new MySQLi("localhost","root","password","database");
$search = $mysqli->real_escape_string($_POST['search']);
//Query the db
$result = $mysqli->query("
SELECT topic, course_id, lect_no, table_id FROM lecture WHERE topic LIKE '%$search%'
UNION
SELECT course_name, course_id, table_id FROM course WHERE course_name LIKE '%$search%'
UNION
SELECT faq_link, table_id FROM faq WHERE faq_key LIKE '%$search%'
");
if($result->num_rows > 0) {
while($rows = $result->fetch_assoc()) {
if($result->table_id == 1) {
$topic = $rows['topic'];
$course_id = $rows['course_id'];
$lect_no = $rows['lect_no'];
?>
<a href="http://www.xyz.php?course=<?php echo $course_id; ?>&lect=<?php echo $lect_no; ?>"><?php echo $topic; ?></a>
<?php
} else if ($result->table_id == 2) {
$course_name = $rows['course_name'];
$course_id = $rows['course_id'];
?>
<a href="http://www.xyz.php?course=<?php echo $course_id; ?>"><?php echo $couse_name; ?></a>
<?php
} else if($result->table_id = 3) {
$faq_link = $rows['faq_link'];
echo $faq_link;
}
}
} else {
echo "No Results Found";
}
}
?>
`
But unfortunately it only searches in first table(lecture) only, even there are matches in other tables also. I searched a lot but didn't found any solution.