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
Related
I have a page that is displaying a list of all company names (45 of them to be exact).
The database table has 43,815 results currently, so I only want to display them without duplicates (which is why I'm using the DISTINCT when I select) but I would also like to count how many results per company has and echo them out.
I'm tried using the count() as but it removes all the company results and just places the total (43,815).
My question is how would I display the companies using DISTINCT (because I don't want to have duplicates on the page) and then also echo out the total results of each company?
Any help is appreciated!
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
// Connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT DISTINCT company FROM ads ORDER BY company ASC";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
// Display the company name
echo $row["company"];
// I WOULD LIKE TO ECHO OUT HERE THE TOTAL OF EACH COMPANY HAS (COUNT) IN RESULTS!
}
} else {
echo "0 results";
}
$conn->close();
?>
I think that you should probably try to use the GROUP BY clause.
Without knowing your table markup try playing around with this:
$query = "SELECT
count(company) as count
FROM ads
GROUP BY company
ORDER BY company ASC"
Try:
SELECT
company,
COUNT(company)
FROM
ads
GROUP BY
company
ORDER BY
company
Use GROUP BY on your SELECT query, this should do what you are looking for, this will group all the same company's together and count them.
"SELECT COUNT(company) FROM ads GROUP BY company ORDER BY company ASC"
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.
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>";