Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

join query not fetching any data

Tags:

join

php

mysql

i am trying to write my first join query which will help me to join two different tables,one is for students and other is for subjects.This is my first join query and it seems it is not working,can anyone point out the mistakes.Php didn't show any error or worning

enter image description here enter image description here

   try{
     $pdo=new PDO("mysql:host=localhost;dbname=mydb",'root','');
     $sql="SELECT * FROM students LEFT JOIN subjects WHERE students.courseid=subjects.courseid";
     $conn=$pdo->prepare($sql);
      if($conn->execute()){
        $results=$conn->fetchAll();
        print_r($results);
      }
     }catch(PDOException $e){
         echo $e->getMessage();
     }
like image 676
AL-zami Avatar asked Apr 28 '26 21:04

AL-zami


2 Answers

Assuming you table name for students is students and you subjects table is subject then I think it should be:

SELECT * FROM students LEFT JOIN subjects on students.courseid=subjects.subjectid

because you have a subjectid in your subjects table and not courseid

like image 152
davejal Avatar answered Apr 30 '26 09:04

davejal


Replace WHERE with ON in your query.

SELECT * FROM students LEFT JOIN subjects ON students.courseid=subjects.courseid

See Mysql JOIN Syntax

like image 31
Dennis Y. Parygin Avatar answered Apr 30 '26 10:04

Dennis Y. Parygin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!