简体   繁体   中英

How can I select all the data from a table with condition?

I am new to android programming and I am having trouble with queries. I tried to search for similar questions but I found nothing :) so, here..

given this patientinfo table

patient_id | name | gender | age 
      1    | jen  | female | 20
      2    | jay  |  male  | 19

and records table

patient_id |   date   | description
      1    | 01-01-14 | healthy!
      1    | 02-01-14 | healthy!
      2    | 01-01-14 | needs medication.

I'd like to get all the records of a certain patient. like for example, if I choose patient1.. all records of patient1 will be displayed.

this is my query..

$query = "SELECT * FROM records INNER JOIN patientinfo ON records.patient_id = patientinfo.patient_id WHERE records.patient_id = $patient_id";

try{
    $stmt = $dbname->prepare($query);
    $result = $stmt->execute(); 

}catch(PDOException $ex){
        $response["success"] = 0;
        $response["message"] = $ex;

        die(json_encode($response));
    }


but it gives me an error in sql syntax, I think it's in the $patient_id

errorInfo: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use.

Thank you in advance! hoping for an answer! Thanks :)

Try by:

SELECT *
FROM patientinfo, records
WHERE (patientinfo.patient_id = $patient_id) AND (patientinfo.patient_id = records.patient_id);

You may also specifically list the columns to show, and assign them an alias, for instance:

SELECT records.date AS the_date

The WHERE records.patient_id = $patient_id seems ok as long as $patient_id is not an empty string. For that, I'd echo the query prior to executing it and checking whether it's ok.

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