简体   繁体   中英

selecting a value from multiple tables

I have added search option to a project. There I used jquery auto complete feature to display related result for the keyword when some particular user is entering in search text box.

this is my php script..

<?php

require_once('database.php');

if(isset($_POST['queryString'])) {

    $queryString = $dbc->real_escape_string($_POST['queryString']);

    if(strlen($queryString) >0) {
        //$query = $dbc->query("SELECT subjects FROM subject WHERE subjects LIKE '$queryString%' LIMIT 10");
        $q = "SELECT tutor_name FROM tutors WHERE tutor_name LIKE '%$queryString%' LIMIT 10";

        $r = mysqli_query ( $dbc, $q);

        if($q) {
            while ($row = mysqli_fetch_array($r, MYSQL_ASSOC)) {
                echo '<li onClick="fill(\''.$row['tutor_name'].'\');">'.$row['tutor_name'].'</li>';
            }
        } else {
            echo 'ERROR: There was a problem with the query.';
        }
    } else {

    }
} else {
    echo 'There should be no direct access to this script!';
}

?> 

This is working properly for me.. but my problem is I need to check multiple tables with typing keyword. Here I use only one table.. anyone can tell me how can I attach my other tables to this query?

use UNION

SELECT keyword 
FROM
(
    SELECT tutor_Name AS keyword FROM tutors
    UNION
    SELECT subject_name AS keyword FROM subjects
    UNION
    SELECT institute_name AS keyword FROM institutes
) s
WHERE keyword LIKE '%$queryString%' 
LIMIT 10

you query is also vulnerable with SQL Injection , please read the article below

The below Query merge three tables that returns you only those selective records present in tables on the basis of common column in the tables .

SELECT tutor_name FROM yourDB
LEFT JOIN tableA ON tutor_name = '%$queryString%'
LEFT JOIN tableB ON tutor_name = '%$queryString%';

Hope this works for you.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM