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();
Related
I have two tables, SpeciesHuntBoats contains details of Boats, the Make, Skipper etc. and SpeciesHunt which is generated by the skipper submitting a catch report form with details of their fishing catches. showboats.php displays 5 columns, Year, Boat Name, Make, Skipper, Number Of Species Caught.
For the final column I want a display of the number of rows in SpeciesHunt where that BoatName appears (to give a leaderboard of who has entered the most catches). This is as far as I've been able to get unfortunately, any help much appreciated!
<body>
<?php
$servername = "xxx";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Count Rows
$result = mysqli_query($conn, "SELECT * FROM SpeciesHunt");
$num_rows = mysqli_num_rows($result);
// Check row count of entire table works
echo "$num_rows Rows\n";
$sql = "SELECT Year, BoatName, BoatMake, Skipper FROM SpeciesHuntBoats";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>Hunt Year</th><th>Boat Name</th><th>Boat Make</th><th>Skipper</th><th>Number Of Species</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["Year"]. "</td><td>" . $row["BoatName"]. "</td><td>" . $row["BoatMake"]. "</td><td>" . $row["Skipper"]. "</td><td>
$num_rows</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
</body>
Table structures:
SpeciesHunt
SpeciesHuntBoats
For your tables, you should rather make use of a relationship between boats and hunts
You should research a bit into sql relationships.
Currently you are basically saving the boat name, make and skipper twice.
This is a better suggestion for the structure:
Boats:
Year
Name
Make
Skipper
Photo
Hunts:
DateCaught
Angler
Species
Notes
BoatId (This will be a reference to a certain boat record)
In this case you can do a sql query that joins the two tables
select Year, Name, Make, Skipper, count(hunts.id) from boats
join hunts on boats.id = hunts.BoatId
group by Year, Name, Make, Skipper;
What this will return is a certain boat with a total count of hunt records.
Things you can research into:
MySQL relationships
MySQL joins
MySQL aggregates
I have two tables in my database these are:
customer
product
customer table:
customerID
sl_no(pk)
name
email
phone
product table:
product_id(pk)
sl_no(fk)
product
price
When i run this query it shows me only one result:
$sql = (" SELECT * FROM customer INNER JOIN product WHERE customer. sl_no LIKE '%$search%' OR product. sl_no LIKE '%$search%'");
Your sql query will at some point return an error of being ambiguous or column with name, product not found. I have added aliases in the SQL query. If you do not understand. You can read up from here. https://www.w3schools.com/sql/sql_alias.asp
If you
Also try using mysqli because mysql is been deprecated as of PHP
5.5.0
$servername = "yourhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = (" SELECT customer.name AS name, customer.email AS email, customer.phone AS phone, product.product AS product_name, product.price AS price FROM customer, product WHERE customer.sl_no = product.sl_no AND customer. sl_no LIKE '%$search%' OR product. sl_no LIKE '%$search%' ");
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<strong>CUSTOMER</strong>";
echo "Customer Name: " . $row["name"]."<br>";
echo "Customer email: " . $row["email"]."<br>";
echo "Customer phone: " . $row["phone"]."<br>";
echo "----";
echo "<strong>PRODUCT</strong>";
echo "Product Name: " . $row["product_name"]."<br>";
echo "Product Price: " . $row["price"]."<br>";
echo "-----";
echo "----";
}
} else {
echo "0 results";
}
$conn->close();
Don't forget to first test or run query in the database via your
UI/phpmyadmin or CLI to understand what result you should expect.
Hope this helps.
You may have several issues. As we can't see the Php iteration of the results.... here's some issues with the basic select...
Missing on clause (or change your inner join to a cross join) so your meaning is clear.
The OR in the clause or doesn't make sense if it's an inner join given PK/FK nature of the field.
searching using like %var% seems like bad form. Do you know the exact values? if so use them instead of %var% since this method can't use indexes.
your where customer. sl_no has a space... this won't work.
.
$sql = ("SELECT *
FROM customer C
INNER JOIN product P
ON C.sl_no = P.SL_NO
WHERE C.sl_no = '$search'");
If you do really mean like then put the like and %'s back but this seems like bad form. and don't you need . before and after var in php. I'm not a big developer there so maybe I'm thinking of something else.
I've just started learning PHP so this is quite a struggle for me, any help is appreciated!
So, I've managed to select my database, table and get data from it. But I need to select more data from the older columns.
Here is some of the code:
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//execute the SQL query and return records
$result = mysqli_query($conn, "SELECT username FROM interview");
while($rowval = mysqli_fetch_array($result))
{
$username= $rowval['username'];
$username2= $rowval['username'];
$username3= $rowval['username'];
$username4= $rowval['username'];
}
?>
And I am displaying the data in a button, I want $username to display the first column and $username2 to display the second column etc...
I fetch the data using this code:
<?php echo $username; ?>
<?php echo $username2; ?>
<?php echo $username3; ?>
<?php echo $username4; ?>
Thanks!
I would suggest you re-factoring your "while" loop the following way for better scalability:
$usernames=array();
while($rowval = mysqli_fetch_array($result))
{
$usernames[] = $rowval['username'];
}
Then, you'll be able to access usernames like:
echo 'The first user name is: '.$usernames[0];
echo 'The second user name is: '.$usernames[1];
echo 'The third user name is: '.$usernames[2];
My php skills are a bit rusty, so take this with a grain of salt:
At first it is important to get the language right. A database table consists of rows and columns, the columns are the ones you select with the the part after the SELECT statement, if you write SELECT username what you select is the username column.
SELECT username FROM interview;
So if you want to select more columns from your table you have to put them in your SELECT statement. Let's say you want to select the username and the status of the interview, you would need to include the status in your SELECT statement like this:
SELECT username, status from interview;
Then you can access the interview status just like you did it with the username.
$result = mysqli_query($conn, "SELECT username, status from interview;");
while($rowval = mysqli_fetch_array($result))
{
$username= $rowval['username'];
$status = $rowval['status'];
}
Remember that what you get as the $rowVal is just a single row of your table. So if you want to collect all usernames and statuses from your table you have to use a datastructure to collect them.
$queryResult = mysqli_query($conn, "SELECT username, status from interview;");
$result = array();
while($rowval = mysqli_fetch_array($queryResult))
{
$username= $rowval['username'];
$status = $rowval['status'];
// With this action we build an array, that has each row's result as value.
$result[] = array('username' => $username, 'status' => $status);
}
To access the results you can then query the $result array like this:
// The interview status of the first entry in your table
$result[0]['status'];
The purpose behind this, is for me to be able to extract data from a table thats been formed via INNER JOIN of two other tables.
I've mapped a tariff name to a username successfully. But what i want to do is to be able to return data from this new table that was created via INNER JOIN in a text field on android studio.
My main concern at the moment is figuring out the right query to do be able to return the data. I've tried researching this but have had no luck/
I have 2 databases. A useraccount database and a tariff database.
useraccount database consists of the following columns:
ID
Name
Surname
EmailAddress
PostCode
City
PhoneNumber
Username
Password
ConfirmPassword
tariffs
And my Tariff database consists of the following column:
ID
Name
I have joined the two tables using INNER JOIN, and have linked the username column with the tariff name column, essentially, i ended up with a table like this:
Username|Tariff
Here is the code for that:
$query = "SELECT useraccount.Username, tariff.Name as tariffs
FROM useraccount
INNER JOIN tariff ON useraccount.tariffs = tariff.id";
$result = mysqli_query($conn,$query);
if($result->num_rows){
while($row = $result ->fetch_object()){
echo "{$row->Username} ({$row->tariffs}) <br>";
}
}else{
echo "No results";
}
$query2 = "SELECT";
$result2 = mysqli_query($conn,$query2);
Question:
How do I access the columns of the result set?
This image shows the result of the execution of the PHP file
Joining two tables together does not create a third table, but creates a result set from the combined records of the two tables. In your code example, you already have access to all the data contained in the useraccounts and tariff tables. To gain access to this data, simply modify your select statement so that it references the desired columns. You could also just use the '*' wildcard to include all columns in your result set.
// Using a wildcard to get all useraccount data.
$query = "SELECT useraccount.*, tariff.Name as tariffs
FROM useraccount
INNER JOIN tariff ON useraccount.tariffs = tariff.id";
$result = mysqli_query($conn,$query);
if($result->num_rows){
while($row = $result ->fetch_object()){
// Reference any user data you want.
echo "{$row->Username} {$row->EmailAddress} {$row->PostCode} ({$row->tariffs}) <br>";
}
}
You need to join the user account id on the tariff id:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT useraccount.Username, tariff.Name FROM useraccount INNER JOIN tariff ON useraccount.id = tariff.id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "Username: " . $row["username"]. " - Tarrif: " . $row["name"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
There is 3 tables:
First table (oc_product_to_category):
Second table (oc_product_description):
Third table (oc_product):
I want to list product name, image, price where category_id is 59
to this div:
<div class="content" style="">
<h1>'Product image'</h1>
<h3>Product name and price</h3>
</div>
I am beginner in working with multiple tables.
Can somebody help me?
<?php
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT product_id FROM oc_product_to_category WHERE category_id='62'";
$result = $conn->query($sql);
if ($result->num_rows > 0) { // output data of each row
while($row = $result->fetch_assoc()) {
echo "<div class='content' style=''> <h1>Orbit does content now.</h1> <h3>" . $row["product_id"]. "</h3> </div>";
} }
$conn->close();
?>
UPDATE: price in: oc_product table
In my opinion this is more a question related to SQL than to PHP. In each table, you have a product_id column, so you can use this as a foreign key. The SQL should look similar to:
SELECT
pd.name, p.image
FROM
oc_product_to_category ptc
JOIN
oc_product_description pd ON ptc.product_id=pd.product_id
JOIN
oc_product p ON ptc.product_id=p.product_id
WHERE
ptc.category_id=59;
If you make this query using php, you get an array containing name and image of each row matching the given category_id.
PS: I did not find any price column.