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"
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.
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 using MySQL to show data on my website: http://www.onlinedealsindia.in. You can see the deals (deal boxes) there but I want to limit them. I want only 50 deals (deal boxes) to show up per page. Clicking the more button would show the next 50 deals.
Below is my code to get data from MySQL:
<?php
$host="localhost";
$username="username";
$password="pass";
$dbname="DB NAme";
$conn=new mysqli($host, $username, $password, $dbname);
if($conn->connect_error)
{
die("error".$conn->connect_error);
}
else { echo "";}
$sql= "SELECT * FROM table ORDER BY p_id DESC";
$results=$conn->query($sql);
if($results->num_rows > 0)
{ while($row=$results->fetch_assoc())
{ $pid=$row["p_id"];
?>
The mechanic you are looking for is called skip and take.
In mySQL you can use the LIMIT to accomplish this. With one parameter it returns that many rows. With two parameters, it will skip the first number in rows and return the number of rows for the second number.
This SQL would return 20 rows:
$sql= "SELECT * FROM table LIMIT 10 ORDER BY p_id DESC";
This SQL would return the ten rows skipping the first 10
$sql= "SELECT * FROM table LIMIT 20,10 ORDER BY p_id DESC";
Documentation and examples of LIMIT can be found here
To make this work for your website just pass a parameter that tells what page you are on and how many rows per page. You can then calculate the two numbers you need for your select statement.
$mysqli = new mysqli($host, $username, $password, $dbname);
if($mysqli->connect_error)
{
die("error".$mysqli->connect_error);
}
else {
echo "";
}
$datas = $mysqli->prepare('SELECT id FROM table LIMIT 50 ');
if($datas)
{
$datas->execute();
$datas->bind_result($id);
while($datas->fetch)
{
$store['id']= $id;
$results[] = $store;
}
return $results;
}
foreach($results as $result)
{
echo $result['id'];
}
I have this code that will display all of the info on my database. The problem is I want to show only about 10 of the last results. But be able to request more somehow by pressing button. Thank you for taking interest in my question.
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<div id='message'> <br> ". $row["firstname"]. " " . $row["lastname"] . "<br> </div>";
}
} else {
echo "0 results";
}
$conn->close();
?>
There are two ways you could solve this
Option 1
The problem is I want to show only about 10 of the last results
One way to do it is to use the SQL Limit specifier
$sql="Select * from ORDERS LIMIT 5"
this will fetch the 5 items from your database. You can use ordering mechanisms for sorting,etc
But be able to request more somehow by pressing button.
You can use the offset specifier for this.
$sql="Select * from ORDERS LIMIT 5 OFFSET 15"
This fetches 10 records from the 16th record.You can add to the offset on each button press.
Here is some more information on this link.
Option 2
Pagination.This link should help.
use LIMIT and OFFSET clause for limit selection. link
if you want to select last 10 data, write query like this.
SELECT id, firstname, lastname FROM MyGuests ORDER BY id DESC LIMIT 10
and you should use ajax for "show more" function.