I’m playing around with mysql databases, and more specifically, relational tables for the first time and am looking for some guidance. It is structured as so:
Database: DV501 (containing 3 tables (for now))
models01 (holds each car model and gives them an id)
- model_id
- model_name
int01 (holds the parts, names, prices, etc…)
- id
- part_no
- part_name
- part_cost
- part_total
etc…
camry01 (used as relational table between models01 and parts in int01 that fit this car)
- id
- model_id
- part_id
For the web page, I have a form with a dropdown containing car models, each car in the dropdown has a value that corresponds to it’s model_id in the database. Camry has a value of ‘1’ and a model_id of ‘1’, Corolla a value of ‘2’ and a model_id of ‘2’ and so on…
When you submit the form, it stores the selected value in $_SESSION[‘selected_car’] variable to access later.
(This is where I am getting stuck)
When the next page loads after the form is submitted, it should display only parts from table ‘int01’ that fit the car stored in the session variable.
I was using the statement below to work from, but as you can see I’m telling it to use camry01 table where as I want to dynamically use the value stored in the $_SESSION[‘selected_car’] to choose the correct model, and display the parts that fit it.
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "DV501";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT camry01.model_id, camry01.part_id, int01.part_name, int01.part_no, int01.part_total
FROM camry01
LEFT JOIN int01 ON (int01.id = camry01.part_id)
WHERE (camry01.model_id = '1');";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo $_SESSION['selected_car'] . " - " . $row['part_name'] . " - Price: " . $row['part_total'] . "<br/>";
}
}
else {
echo "0 results";
}
mysqli_close($conn);
?>
Any help would be greatly appreciated.
You can get the variable name from SESSION and bind it in the query so that you can fetch the desired the result.
$stmt = $conn->prepare("SELECT camry01.model_id, camry01.part_id, int01.part_name, int01.part_no, int01.part_total
FROM camry01 LEFT JOIN int01 ON (int01.id = camry01.part_id) WHERE (camry01.model_id = ?)");
$stmt->bind_param("i", $_SESSION[‘selected_car’]);
$stmt->execute();
$stmt->close();
$conn->close();