简体   繁体   中英

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.

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();

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