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.
Related
I have 2 tables :
accounts
lanes
lanes contains 1 column "boss_id" which is an INT between 1 and 12
accounts contains various columns including username, password and also a boss_id column
Im trying to use PHP to display ALL items from the lanes table, which is working great! But, what i need to do is also show if a user from "accounts" also shares or has the same boss_id and displays a different output :
Regular output (no matching account)
foreach ($boss_id as $boss) {
echo "Lane " . $boss . "<br>;
}
If there is a matching account show this instead
echo "Lane booked by " . $username. "<br>;
I've spent a lot of time on this, and really need some help as i cant seem to figure it out.
Any help would be awesome! If you need anymore information, please ask!
Thanks in advance
E
This is what i have so far (variables may differ in name but you should get the idea!)
$db_host = "localhost";
$db_username = "root";
$db_password = "";
//connect to mysqli database (Host/Username/Password)
$connection = mysqli_connect($db_host, $db_username, $db_password) or die("Error " . mysqli_error());
//select MySQLi dabatase table
$db = mysqli_select_db($connection, "archery-booking") or die("Error " . mysqli_error());
// get ALL lanes from database table "lanes"
$sql = mysqli_query($connection, "SELECT * FROM lanes");
while($row = mysqli_fetch_array($sql)) {
$bossid[] = $row['bossid'];
}
// save each result as a variable
foreach ($bossid as $compare) {
$compare = $compare;
}
// get ALL BOOKED lanes from database table "accounts"
$sqluser = mysqli_query($connection, "SELECT * FROM accounts WHERE boss_id = '".$compare."' ");
while($row = mysqli_fetch_array($sqluser)) {
$bookedboss[] = $row['boss_id'];
}
Updates
So i have no made a couple of changes, and getting the information for both lane.boss_id and also accounts.boss_id
How ever, i still need to do the following :
If lane.boss_id doesnt have an account attached to it, then do this, if it does have an account then do that.
What would be the best way of checking this condition? I was going to use an if/else on "username" but i got an error about illegal string offsets....here's my code so far!
$db_host = "localhost";
$db_username = "root";
$db_password = "";
//connect to mysqli database (Host/Username/Password)
$connection = mysqli_connect($db_host, $db_username, $db_password) or die("Error " . mysqli_error());
//select MySQLi dabatase table
$db = mysqli_select_db($connection, "archery-booking") or die("Error " . mysqli_error());
// get ALL lanes from database table "lanes"
$sql = mysqli_query($connection, "SELECT l.*, a.username FROM lanes l LEFT JOIN accounts a ON a.boss_id = l.bossid");
while($row = mysqli_fetch_array($sql)) {
$bossid[] = $row['bossid']['username'];
var_dump($bossid);
}
UPDATE 3
I can't thankyou all enough for your help, we've really made progress!! :D
I have 1 final request though and i hope you guys can help as well as you have already! :)
So, in my script i have the following :
if (isset($uname)) {
echo "<div class='col-xl-3 col-lg-3 col-md-6 col-sm-6 col-xs-6'>
<div class='card bg-normal'>
<div class='card-header day1'>
<p>Lane booked from 6.00pm</p>
</div>
<div class='card-body'>";
echo "<h2 class='lane-title taken'>Lane " . $bossid . "</h2>";
echo "<p class='lead'>Booked by " . $uname . "</p>";
echo "</div>
</div>
</div>";
} else {
echo "<div class='col-xl-3 col-lg-3 col-md-6 col-sm-6 col-xs-6'>
<div class='card bg-normal'>
<div class='card-header day1'>
<p>Lane booked from 6.00pm</p>
</div>
<div class='card-body'>";
echo "<h2 class='lane-title'>Lane " . $bossid . "</h2>";
echo "Lane Available";
echo "</div>
</div>
</div>";
}
This works great and outputs everything required, BUT....what i need is the following :
If no username, show 1 entity with label "FREE"
If username + detail = 1, show 1 entity with label "TAKEN BY $username"
IF username + detail = 1 AND 2, show 1 entity with label "TAKEN BY $username1 and $username2
At the moment, from the code above, if detail 1 AND 2 are on boss_id 5, then there are 2 entities of boss_id 5, where i only need 1 entity showing both the details 1 AND 2.
Hope this makes some sense!! :)
TIA
E
You seem to want a LEFT JOIN:
SELECT l.*, a.username
FROM lanes l
LEFT JOIN accounts a ON a.boss_id = l.boss_id
When there is a recored in accounts whose boss_id matches, this brings the corresponding username in the resultset. If there is no match, username comes as null.
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
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();
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();
I have 2 tables, bs_reservations and bs_events. The first contains a bunch of IDs, the second both the (same) IDs and the corresponding titles. I'm trying to replace on-the-fly the IDs taken from first table with the corresponding titles, taken from the second table.
First table is bs_reservations which only has an eventID column. Here's the PHP code I use to fetch the IDs:
<?php
$servername = "localhost";
$username = "blabla";
$password = "blabla";
$dbname = "blabla";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM bs_reservations WHERE serviceID=3";
$result = $conn->query($sql);
if ($result->num_rows > 0) { echo "<table><tr><th>Name</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["eventID"]. "</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
The second table, bs_events has 2 columns, id and title. id corresponds to the same eventID of the first table, title is the corresponding title.
How can I modify the snippet above to match eventID from the first table with id of the second table and replace on-the-fly $row["eventID"] with the corresponding title?
Don't say to just use the second table as of course the first table has also other columns I'm fetching.
You can use the JOIN directive in your query:
$sql = "SELECT *
FROM `bs_reservations`
JOIN `bs_events` ON `bs_reservations`.`eventID` = `bs_events`.`id`
WHERE `bs_reservations`.`serviceID`=3";
You can then access the title attribute of each row just as if it was in the same table:
echo "<tr><td>" . $row["title"]. "</td></tr>";
Update:
If you need the events with no reservations yet as well, you can use a RIGHT OUTER JOIN:
$sql = "SELECT *
FROM `bs_reservations`
RIGHT OUTER JOIN `bs_events` ON `bs_reservations`.`eventID` = `bs_events`.`id`
WHERE `bs_reservations`.`serviceID`=3";
Use a join in your query.
SELECT r.*, e.title FROM bs_reservations as r JOIN bs_events as e on r.event_id = e.id WHERE r.serviceID = 3
Then in your loop you can echo the title. Assuming the reservations table doesn't have a title column, then you may want to rename it ..., e.title as eventTitle FROM ...
echo "<tr><td>" . $row["title"]. "</td></tr>";