user9916463
user9916463

Reputation:

How to get specific ID in SQL Query

Im trying to echo the content of a specific users information. I am currently using

$sql = "SELECT treatment_log.tech,treatment_log.comments FROM customers LEFT OUTER JOIN treatment_log ON customers.id=treatment_fk WHERE customers.id = 12";

The number 12 will only echo the content of the patient with ID# 12. How would I be able to echo the content of any users information. In other words, I would also like to echo the content of users 13,14,15 etc individually. What would I have to put in the place of "12" to "GET" the id of the current user being viewed.

I can currently do this using PHP by typing:

$_GET['customer_id']

Upvotes: 1

Views: 2048

Answers (1)

UkFLSUI
UkFLSUI

Reputation: 5672

At first, keep the customer_id in a variable. Remember, GET should never be used with any sensitive data. However, as you have requested, maybe you are aware of this. Do it like below:

$cid = $_GET['customer_id'];

Then write sql query as following using ? sign in place of 12:

$sql = "SELECT treatment_log.tech,treatment_log.time,treatment_log.date,treatment_log.titration_parameter,treatment_log.pain,treatment_log.bdi,treatment_log.suicidality,treatment_log.comments FROM customers LEFT OUTER JOIN treatment_log ON customers.id=treatment_fk WHERE customers.id = ?";

Then do as follows:

$stmt = mysqli_stmt_init($conn);
mysqli_stmt_prepare($stmt, $sql);
mysqli_stmt_bind_param($stmt, "s", $cid);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);

To know about each of the above lines, read the official manual for mysqli_stmt_init(), mysqli_stmt_prepare(), mysqli_stmt_bind_param(), mysqli_stmt_execute(), mysqli_stmt_get_result()

And finally, to get the result, use something like below:

$resultCheck = mysqli_num_rows($result);
if($resultCheck > 0) {
    while($row = mysqli_fetch_assoc($result)) {
        echo "id: ". $row["tech"]. " " . $row["time"]." " . $row["date"]." " . $row["titration_parameter"]." " . $row["bdi"]." " . $row["suicidality"]." " . $row["comments"]. "<br>";
    }
}
else {
    echo "0 results";
}

Upvotes: 2

Related Questions