Marksmanship
Marksmanship

Reputation: 169

Is it possible to get data from the 2nd table using column in 1st table using PHP PDO?

Well, I have a situation that I need to SELECT data from two tables at once. But my main problem is how can I SELECT .. WHERE in my table2 when the value that I needed in WHERE clause is in the return value of SELECT statement in table1.

test.php

<?php 
   include("../../connection.php");
    $data = json_decode(file_get_contents("php://input"));
    $id= $data->id;

    try{
      $db->exec("SET CHARACTER SET utf8");  
      $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

      $sql = "
        SELECT * FROM tblstudents WHERE studID=':id';
        SELECT * FROM tblparents WHERE studNumber=':studNumber';
      ";

      $statement = $db->prepare($sql);
      $statement->bindValue(":id", $id);
      $statement->bindValue(":studNumber", $studNumber);

      $result = $statement->execute();

      echo json_encode($result);

    }
    catch(PDOException $e) {
      echo $e->getMessage();
    }

?>

The studNumber value is in the tblstudents which will have a return value from SELECT statement.

Is it possible that I can get the studNumber value in the return value of SELECT statement when the SELECT statement of the tblparents is in the same sql query? Or is there another way around?

Hope I clearly explained my situation.

Upvotes: 0

Views: 35

Answers (1)

B. Desai
B. Desai

Reputation: 16446

You need to use JOIN for get data from multiple tables. Try this query:

$sql = "SELECT * FROM tblstudents JOIN tblparents on
 tblstudents.studNumber  = tblparents.studNumber  WHERE tblstudents.studID=:id;"

  $statement = $db->prepare($sql);
  $statement->bindValue(":id", $id);
  $result = $statement->execute();

Upvotes: 1

Related Questions