Håkan
Håkan

Reputation: 161

PHP search from two tables

I've a search function in PHP/MySQL that works fine as long as I only search from one table. The problem is that I need to search one table and display info from that but also display two parts from another table. Using this code I get an Notice: Trying to get property of non-obect error. My PHP code is this:

if(isset($_GET['search'])) {
    $search = $link->escape_string($_GET['search']);
    $query = $link->query("SELECT l.Id, l.ImageId, l.Subject, l.Level, l.Aim, i.NameImg, i.AltImg FROM LessonPlans l, Images i WHERE Subject LIKE '%".$search."%' OR Level LIKE '%".$search."%' OR Aim LIKE '%".$search."%' AND Language='English'");

if($query->num_rows){        
    while($r = $query->fetch_object()){

    echo '<div class="col s6 m4 l3">
            <div class="card">
                <div class="card-image waves-effect waves-block waves-light">
                    <img class="activator" src="../mlslp/assets/img/'.$r->NameImg.'" alt="'. $r->AltImg.'">
                </div>
                <div class="card-content">
                    <span class="card-title activator grey-text text-darken-4 truncate tooltipped" data-position="bottom" data-delay="800" data-tooltip="'.$r->Subject.'">'.$r->Subject.'</span>
                    <p class="blue-text">'.$r->Level.'</p>
                </div>
                <div class="card-action">
                    <a href="lessonplan.php?Id='.$r->Id.'">Open Lesson Plan</a>
                </div>
                <div class="card-reveal">
                    <span class="card-title grey-text text-darken-4">'.$r->Subject.'<i class="material-icons right">close</i></span>
                    <p>'.$r->Aim.'</p>
                </div>
            </div>
        </div>';

        }
    } 
}

Is there a way to get around the problem with that two tables don't send an object? I'm not sure if it's the query or the if/while statements that are wrong.

Upvotes: 0

Views: 67

Answers (2)

Arun
Arun

Reputation: 3721

If both table have the same name ImageId, then try the beloq query

$query = $link->query("SELECT l.Id, l.ImageId, l.Subject, l.Level, l.Aim, i.NameImg, i.AltImg FROM LessonPlans l join Images i on i.ImageId=l.ImageId WHERE Subject LIKE '%".$search."%' OR Level LIKE '%".$search."%' OR Aim LIKE '%".$search."%' AND Language='English'");

i.ImageId -> Image id of table Images table

l.ImageId -> Image id of LessonPlans table

Upvotes: 1

Richard
Richard

Reputation: 1055

You can't use hyphen in your database names.

In SQL i.Name-img should be treated as i.Name minus img

and in PHP it's the same.

You can't call $r->Name-Img because it's treated like $r->Name minus constant Img (or string).

Upvotes: 0

Related Questions