Mysql Query Group By Display Using PHP - php

I want to display a table that looks like this from a Mysql query using PHP:
Vendor Name
Item Not to Drawing Item Defective Incorrect Item Received Other
9 2 3 5
Vendor Name
Item Not to Drawing Item Defective Incorrect Item Received Other
2 4 5 7
etc..
Here is my code....
<?php
$con = mysql_connect("localhost","xxx","xxx");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("qa", $con);
$result = mysql_query("SELECT Vendor, Sum(draw), Sum(defective), Sun(received), Sum(other) FROM qa_reports Group by Vendor Order by Vendor ASC");
echo "<table>
<tr>
<th>Item not to Drawing</th>
<th>Item Defective</th>
<th>Incorrect Item Received</th>
<th>Other</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['Sum(draw)'] . "</td>";
echo "<td>" . $row['Sum(defective)'] . "</td>";
echo "<td>" . $row['Sum(received'] . "</td>";
echo "<td'>" . $row['Sum(other)'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
Not sure how to get the above results formatted as such.
I've done this with CFML but am new to PHP and can not grasp how to list results in a table grouped by a field.

You need to alias your columns in order to reference them in your $row array.
SELECT vendor,
Sum(draw) AS draw,
Sum(defective) AS defective,
Sun(received) AS received,
Sum(other) AS other
FROM qa_reports ...
Then you can reference them like so:
$row['draw'];
...

SELECT Vendor, Sum(draw) AS sumDraw, Sum(defective) AS sumDefective ...
$row['sumDraw'] etc.

Related

Retrieving latest records from database and display in body? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm making a database driven site. But before I buy a .com domain, I was aiming to make the site more dynamic & interactive. Somehow, I got stuck with mySQL and PHP. I'm new to mySQL, and have a limited knowledge with PHP. I was able to get the page generator code running, all that's left is the dynamic homepage code.
So here's the thing, I want to get the 5 latest records from my database and display them in my homepage's formatted DIV boxes. I have a sample code but the records are displayed in a looped array. How can I get those data and store them in a $variable so that I could echo it out in my DIV boxes.
My Website: ASCAS.tk
HOW CAN I ASSIGN VARIABLES TO EACH DATA FROM THOSE 5 ROWS?
ex. ($id_1, $id_2, $id_3, $title_1, $title_2, $title_3...)
I also have a PHP code that displays all the records in one table.
<?php
$con=mysqli_connect("localhost","user","pass","u967445970_home");
if (mysqli_connect_errno())
{echo "Failed to connect to MySQL: " . mysqli_connect_error();}
$result = mysqli_query($con,"SELECT * FROM main");
echo "<table border='1'>
<tr>
<th>id</th>
<th>Title</th>
<th>Description</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['Title'] . "</td>";
echo "<td>" . $row['Description'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
HOW CAN I ASSIGN VARIABLES TO EACH DATA FROM THOSE 5 ROWS?
ex. ($id_1, $id_2, $id_3, $title_1, $title_2, $title_3...)
Change your result variable with this
$result = mysqli_query($con,"SELECT * FROM main LIMIT 5");
And if you want to order your last record ordering by (assuming in this case, i want to order by date) , this is the code
$result = mysqli_query($con,"SELECT * FROM main order by id DESC LIMIT 5");
Change the id with your primary key
Try this
$result = mysqli_query($con,"SELECT * FROM main order by created_date DESC LIMIT 2");
OR try this
$result = mysqli_query($con,"SELECT * FROM main order by id DESC LIMIT 2");
use this query
<?php
$con=mysqli_connect("localhost","user","pass","u967445970_home");
if (mysqli_connect_errno())
{echo "Failed to connect to MySQL: " . mysqli_connect_error();}
$result = mysqli_query($con,"SELECT * FROM main order by date desc limit 0, 5");
if(mysqli_num_rows($result)> 0){
echo "<table border='1'>
<tr>
<th>id</th>
<th>Title</th>
<th>Description</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['Title'] . "</td>";
echo "<td>" . $row['Description'] . "</td>";
echo "</tr>";
}
echo "</table>";
}
mysqli_close($con);
?>

In php-sql, I want to re-search within the first search result table.

In php-sql, I want to re-search within the first search result table.
This is the captured picture executed by my php-mysql code.
I want to use the button "Search below result" to gain the detailed result from the first search result table.
Then, "Search in below result" form action is another php code which has to hold the first result, and have the sql code that is as like
select uid, contents from datatable where contents like '%re-search word%'
and uid in (select uid from datatable where contents like '%first-search word%')
but I have a question and don't know how uid works.
How can i produce uid?
What is uid?
Where is uid information?
How can i use uid as like above the sql code?
Below is my first-search php code
<?php
$q = $_GET['q'];
$con = mysqli_connect('localhost','root','autoset','my_db');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM persons WHERE FirstName = '".$q."' ;
$result = mysqli_query($con,$sql);
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Age'] . "</td>";
echo "<td>" . $row['Hometown'] . "</td>";
echo "<td>" . $row['Job'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
and How can i re-use the first-search word variable in the another php code?
Another php code is designed as like below
<?php
$q = $_GET['q'];
$p = $_GET['LastName'];
$con = mysqli_connect('localhost','root','autoset','my_db');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql="SELECT uid, * FROM persons WHERE LastName = '".$p."' and select **uid** in (select uid from datatable where FirstName='".$q."') ;
$result = mysqli_query($con,$sql);
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Age'] . "</td>";
echo "<td>" . $row['Hometown'] . "</td>";
echo "<td>" . $row['Job'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
Above code, I think uid is important to recall the first search result.
But How can i get uid and set uid in php code or html code??
Please help me!
Q1: How can i produce uid?
A1: It should be a column in your table you created in mysql. Your create table statement would have looked something like:
CREATE TABLE persons (
uid INT(10) NOT NULL AUTO_INCREMENT,
FirstName CHAR(30) NOT NULL,
LastName CHAR(30) NOT NULL,
Age INT(3),
Hometown CHAR(40),
Job CHAR(40),
PRIMARY KEY (uid)
);
Q2: How can i produce uid?
A2: You won't have to. The AUTO_INCREMENT field will create itself for you when you insert an entry. doco for auto-increment here
Q3: What is uid?
A3: It likely stands for "user identification" which is a number unique to a user. No other user may have that number in their "uid" field.
Q4: Where is uid information?
A4: It's in your table
Q5: How can i use uid as like above the sql code?
A5: Providing that you created it in your "create table" statement like I mentioned in A1 then you should be able to access uid with the query you presented above but should look more like:
SELECT uid FROM persons WHERE LastName = '".$p."' AND FirstName ='".$q."';
OR if you want to run a test query with a name you know is in your database then something like below:
SELECT uid FROM persons WHERE LastName = 'timmy' AND FirstName ='tom';

PHP MySQL Queries - Addition

I am working on a formula where I am adding multiple values in a row and column depending on the values of other cells. For example I have the following working code:
$result = mysql_query("SELECT School,SUM(Wins + Losses) as total FROM tennis GROUP BY School");
echo "<table border='1'>
<tr>
<th>School</th>
<th>Score</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['School'] . "</td>";
echo "<td>" . $row['total'] . "</td>";
echo "</tr>";
}
However I want to add more columns that are also sums of other rows/columns and don't know how to do this while still keeping everything Grouped by the column 'School'. What I essentially want is the following, but the code is incorrect:
$result = mysql_query("SELECT School,SUM(Wins + Losses) as 1sttotal FROM tennis WHERE Event='1st Singles', SUM(Wins + Losses) as 2ndtotal FROM tennis WHERE Event='2nd Singles' GROUP BY School");
echo "<table border='1'>
<tr>
<th>School</th>
<th>1st Singles</th>
<th>2nd Singles</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['School'] . "</td>";
echo "<td>" . $row['1sttotal'] . "</td>";
echo "<td>" . $row['2ndtotal'] . "</td>";
echo "</tr>";
}
I'm new to PHP so I'm not sure the correct/optimal way to go about setting this up. Thanks
this is the query you should use to get the 2 totals:
SELECT
School,
SUM(IF(Event='1st Singles', Wins + Losses, 0)) as 1sttotal,
SUM(IF(Event='2nd Singles', Wins + Losses, 0)) as 2ndtotal
FROM tennis
GROUP BY School;
See how it adds according to the event columns? The trick is to pass a WHERE filter within the SELECT clause through conditional execution (IF)
Other possibility using CASE WHEN:
SELECT
School,
SUM(
CASE
WHEN Event='1st Singles' THEN Wins + Losses
ELSE 0
END
) as 1sttotal,
SUM(
CASE
WHEN Event='2nd Singles' THEN Wins + Losses
ELSE 0
END
) as 2ndtotal
FROM tennis
GROUP BY School;

Using two Tables to show SQL data on one Screen

I am still battelling to show data from two different tables on one screen. The tables both contain one common field name, all i want is to filter on that field name and be able to alter and display details from that line or lines based on that field name they share.
The two tables are:
members and recipients
In members it has a primary key member_id and it is unique. Then in recipients I created a member_id field that needs to link to the members table unique member_id as well.
The following code calls information from members table
<?php
$con = mysql_connect("localhost", "****", "****");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("stingin_epanic", $con);
$result = mysql_query("SELECT * FROM members WHERE member_msisdn='$slusername'");
echo "<table border='1'>
<tr>
<th>Membership</th>
<th>Number</th>
<th>Registration Date</th>
<th>End Date</th>
<th>Copy of ID</th>
</tr>";
while ($row = mysql_fetch_array($result)) {
echo "<td><center>" . $row['member_id'] . "</td>";
echo "<td><font color=blue>" . $row['member_msisdn'] . "</td>";
echo "<td><center>" . $row['asdate'] . "</td>";
echo "<td><center>" . $row['aedate'] . "</td>";
echo "<td><center>" . $row['attid'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
This works great and gives me what i need. I am also calling member_id here to show the primary key.
On same page i am trying to call information related to the member from another table using the following code. Note that the information is supposed to be linked to the member_id of the first code
<?php
$con = mysql_connect("localhost", "****", "****");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("stingin_epanic", $con);
$result = mysql_query("SELECT * FROM members a INNER JOIN recipients b ON member_id = member_id WHERE member_msisdn=$slusername");
echo "<table border='1'>
<tr>
<th>Name</th>
<th>Number</th>
</tr>";
while ($row = mysql_fetch_array($result)) {
echo "<td><font color=blue>" . $row['recipient_name'] . "</td>";
echo "<td>" . $row['recipient_msisdn'] . "</td>";
echo "</tr>";
echo "<td><font color=blue>" . $row['recipient_name'] . "</td>";
echo "<td>" . $row['recipient_msisdn'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
Using the second code i get no results as it is calling no information
Use mysqli instead of mysql functions
Use aliases in You SQL queries.
change this
"SELECT * FROM members a INNER JOIN recipients b ON member_id = member_id WHERE member_msisdn=$slusername"
on this
"SELECT * FROM members a INNER JOIN recipients b ON a.member_id = b.member_id WHERE member_msisdn=$slusername"
Maybe this will help.

Multiple Uniques MYSQL

I have some code im trying to get working. What im looking for is to have it so that i query a site, then display results and upload to database. I want it to ignore duplicates which i have working by checking the date. issue im having is when a user searches for another stock ticker it does not insert into DB because the date is the same. Anyone have any suggestions?
<?php
$con = mysql_connect("localhost","user","pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("bbpinpal_stocks", $con);
mysql_query("INSERT INTO stocks (stock_name, stock_value, stock_perc, date)
VALUES ('$name', '$last','$perc2', '$date')");
$result = mysql_query("SELECT * FROM stocks");
echo "<table border='1'>
<tr>
<th>Name</th>
<th>Value</th>
<th>Percent Change</th>
<th>Date</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['stock_name'] . "</td>";
echo "<td>" . $row['stock_value'] . "</td>";
echo "<td>" . $row['stock_perc'] . "</td>";
echo "<td>" . $row['date'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
I have set date to unique but i know that is prob my issue. How can i have this so that it checks both name and date and if match to ignore
Replace your UNIQUE index on date with one on (stock_name, date):
ALTER TABLE stocks
DROP KEY date,
ADD UNIQUE KEY (stock_name, date)
I have set date to unique but i know that is prob my issue
This is most probably the issue. Why don't you use another column to uniquely identify a row?
http://en.wikipedia.org/wiki/Unique_key
"..Each unique key is composed from one or more data attributes of that data entity.."
INSERT IGNORE prevents you adding data with a primary key that is already in the database. You can have a primary key that consists of 2 fields.

Categories