Using php to compare mysql results, then echo differences? - php

I'm new to PHP and I'm trying to figure out how I can compare two mysql query results and echo out the differences. Basically I have a database that is comparing state flag characteristics. The user would select 2 states and what I would like is to have the php echo out 3 sets of results (state 1 only, shared characterisics, and state 2 only). My rough code below only echos out characteristics for states 1 and 2. Is there a way that I can compare the query results, so that I get differences between the states, and also shared characteristics.
<?php $query1 = $_GET['query1'];
$query2 = $_GET['query2'];
$min_length = 2;?>
<!-- state 1 characteristics only -->
<div class="fluid s1charc">
<?php echo "<strong><p>Search results for $query1</strong></p>";?>
<?php if(strlen($query1) >= $min_length){$query1 = htmlspecialchars($query1);
$query1 = mysql_real_escape_string($query1);
$raw_results1 = mysql_query("SELECT * FROM charc_s WHERE `charc_f` ='$query1' ORDER BY FLAG_S") or die(mysql_error());
if(mysql_num_rows($raw_results1) > 0) {
while($results1 = mysql_fetch_array($raw_results1)){
echo "<table id='iseqchart' class='sortable'>
<tr valign='middle'>
<td ><a href='flag.php?FLAG_ID=".$results1['FLAG_ID']."'><img src='images/".$results1['IMAGE']."'></a></td>
<td> </td>
<td><strong><font size='3'><a href='flag.php?FLAG_ID=".$results1['FLAG_ID']."' style='color:#100783'>".$results1['FLAG_S']." (".$results1['STATE'].")</strong></a>
</td>
</tr>
</table>";
}
}
else{ // if there is no matching rows do following
echo "No results were found";
}
}
else{ // if query length is less than minimum
echo " ".$min_length;
}
?>
</div>
<!-- shared characteristics -->
<div class="fluid sharecharc">Shared</div>
<!-- state 2 characteristics only -->
<div class="fluid s2charc">
<?php echo "<strong><p>Search results for $query2</strong></p>"; ?>
<?php if(strlen($query2) >= $min_length){$query2 = htmlspecialchars($query2);
$query2 = mysql_real_escape_string($query2);
$raw_results = mysql_query("SELECT * FROM charc_s WHERE `charc_f` ='$query2' ORDER BY FLAG_S") or die(mysql_error());
if(mysql_num_rows($raw_results) > 0) {
while($results = mysql_fetch_array($raw_results)){
echo "<table id='iseqchart' class='sortable'>
<tr valign='middle'>
<td ><a href='flag.php?FLAG_ID=".$results['FLAG_ID']."'><img src='images/".$results['IMAGE']."'></a></td>
<td> </td>
<td><strong><font size='3'><a href='flag.php?FLAG_ID=".$results['FLAG_ID']."' style='color:#100783'>".$results['FLAG_S']." (".$results['STATE'].")</strong></a>
</td>
</tr>
</table>";
}
}
else{ // if there is no matching rows do following
echo "No results were found";
}
}
else{ // if query length is less than minimum
echo " ".$min_length;
}
?>
</div>

The best way to do this is on the server side. Make the database do 3 different selects. The reason is that the server will run the queries a lot faster than the php. And it will end up in a better user experience.
Only Table A
SELECT * FROM TableA A LEFT JOIN TableB B ON A.key = B.key
Only Table B
SELECT * FROM TableA A RIGHT JOIN TableB B ON A.key = B.key
And in Both Tables
SELECT * FROM TableA A INNER JOIN TableB B ON A.key = B.key
From there echo out your results.

Related

Count column of table group by rows

I can count number of a table rows by using mysqli_num_rows. I have a table which contains similar rows. How can I count by grouping by similar row?
For instance: I have a table with 2 columns : Student and Option. Let say there are 50 students. 20 are in Economy option, 20 are in Management option and 10 are in Secretary Option. How can display those numbers. I can display only the 50.
my codes
$qry = "select * from table group by option";
$req= #mysqli_query($conn, $qry);
$result = mysqli_query( $conn, "select id from table");
$num_rows = mysqli_num_rows($result);
Students Total (<?php echo $num_rows ?>)
<table >
<tr>
<th>Student</th>
<th>Option</th>
</tr>
<?php
while($row=mysqli_fetch_array($req))
{
?>
<tr>
<td><?php echo $row['student'] ?></td>
<td><?php echo $row['option'] ?></td>
</tr>
<?php
}
?>
</table>
Here is the query you need:
SELECT COUNT(*) AS `option_count`, * -- returns a count aliased as "options_count"
FROM `table`
GROUP BY `option` -- will group the options and show the counts
Now you can echo the count, along with other data:
echo $row['count_options'];
echo $['options'];
The problem that you have here is that you will not be able to display each student in the option because this counts / groups only the three options.
Behold the proper query :
$qry = "select option as opt, COUNT(*) AS option from table group by option";

Join table without any reference

in the result of sql query, I will check with php which column has record.
example:
if ($column_1) {echo $column_1}
if ($column_2) {echo $column_2}
if ($column_3) {echo $column_3}
I don't use else if there because I need it to continue in checking the record from the sql query.
However with the php code above, I can't union table in order to get another record of column from that table too. First, because the column count doesn't match. Then even though I manipulate the column, it will give me a duplicate row.
What I have been trying so far to achieve this is to use sub query. But before I know the result, it has come with an error.
Well, this is my full code. Have a look, please.
$sql = "SELECT op.reference_no, op.eight_percent, op.ten_percent,
op.date, op.claim, op.orders_history_id,
oh.one_product_price, oh.quantity,
(
SELECT it.type
FROM infimoney_transfer it
),
(
SELECT it.receiveable
FROM infimoney_transfer it
),
(
SELECT oh.id AS ohid
FROM infimoney_transfer it
)
FROM order_promotion op
LEFT JOIN orders_history oh
ON oh.id = op.orders_history_id
WHERE oh.customer_id = $member_id";
$saldo = $mysqli->query($sql);
if(!$saldo){ printf("Errormessage: %s\n", $mysqli->error); die(); }
if ($saldo->num_rows > 0) {
while($objek = $saldo->fetch_object()) {
if ($objek->eight_percent)
{
$sourceCash = $objek->quantity % 10 > 4 ? 1 : 0;
echo "<tr>
<td>".$objek->reference_no . "</td>
<td>Cashback 8%</td>
<td>".$objek->date."</td>
<td>".$sourceCash * 5 * $objek->one_product_price."</td>
<td>".$objek->eight_percent."</td>
<td> - </td>
<td> Not Yet </td>
</tr>";
}
if ($objek->ten_percent)
{
$sourceCash = (int)($objek->quantity / 10);
echo "<tr>
<td>".$objek->reference_no . $objek->orders_history_id."</td>
<td>Cashback 10%</td>
<td>".$objek->date."</td>
<td>".$sourceCash * 10 * $objek->one_product_price."</td>
<td>".$objek->ten_percent."</td>
<td> - </td>
<td> Not </td>
</tr>";
}
if ($objek->claim)
{
$sourceCash = (int)($objek->quantity / 10);
echo "<tr>
<td>".$objek->reference_no . $objek->orders_history_id."</td>
<td>Claimed</td>
<td>".$objek->date."</td>
<td>".$objek->claim."</td>
<td> - </td>
<td>".$objek->claim."</td>
<td> Not </td>
</tr>";
}
Please Help. Thanks in Advance.
If you join your tables all in the same select query, it will not give you duplicate rows:
$sql = "SELECT op.reference_no, op.eight_percent, op.ten_percent,
op.date, op.claim, op.orders_history_id,
oh.id, oh.one_product_price, oh.quantity,
it.type, it.receiveable,
FROM order_promotion op
LEFT JOIN orders_history oh ON oh.id = op.orders_history_id
LEFT JOIN infimoney_transfer it ON it.orders_list_id=oh.order_list_id
WHERE oh.customer_id = $member_id";

Display MySQL table ( number of rows are not same ) in PHP

I have one MySQL table and it has two columns -
I want to display in my site like this -
I can easily take the table name Boy | Girl . But when i try to display the table I get like this -
I am just showing one example here. There may be 50 boys and 10 girls.. So I need help.
After displaying the heading
while($row_type = mysql_fetch_array($type))
{
$type_name = $row_type['type_name']; //Boy (or) Girl taking from another table
$type_name = Database::getInstance()->query("SELECT * FROM details WHERE type='type_name'");
echo "<tr>";
while($row_name = mysql_fetch_array($type_name))
{
echo "<td>$row_name[type_name]</td>"; //Displaying the names
}
echo "</tr>";
}
So many views but not getting any answer. Please help guys. Please catch my mistake.
Try with two queries.
Make an array for each category(Male & Female)
It Works.
$maleQuery = mysql_query("SELECT * FROM table WHERE category='male'");
$femaleQuery = mysql_query("SELECT * FROM table WHERE category='female'");
while(($row = mysql_fetch_assoc($maleQuery))) {
$males[] = $row['name'];
}
while(($row = mysql_fetch_assoc($femaleQuery))) {
$females[] = $row['name'];
}
$number_of_rows = max(sizeof($males),sizeof($females));
echo "<table border='1'>";
echo "<tr><td>Male</td><td>Female</td></tr>";
for($i=0;$i<$number_of_rows;$i++)
{
echo "<tr><td>".#$males[$i]."</td><td>".#$females[$i]."</td></tr>";
}
Try this query 100% working but set php code.
SELECT IFNULL(c.Boy,'')AS Boy,IFNULL(c.Girl,'')AS Girl FROM
(SELECT x.name,CASE WHEN (x.category = 'boy') THEN x.name END AS Boy,CASE WHEN (x.category = 'girl') THEN x.name END AS Girl FROM (SELECT * FROM tablename) X)c
Is your problem to do with the creation of the table using PHP or is it related to the SQL query itself?
If it is the creation of the table then I suggest you use two tables embedded in a single table like this. That way you can build the first table using one SQL query, then build the second table using a second query, then display the table and girls and boys will appear side by side regardless of how many entries on each side. Your code would look a bit like this:
echo "<table>
<tr>
<td>
<table>
<tr><th>Boy</th></tr>";
$table = mysql_query("SELECT Name FROM details WHERE Category = 'Boy'") or die(mysql_error());
while($row = mysql_fetch_row($table))
echo "<tr><td>".$row[0]."</td>";
echo "</table>
</td>
<td>
<table>
<tr><th>Girl</th></tr>";
$table = mysql_query("SELECT Name FROM details WHERE Category = 'Girl'") or die(mysql_error());
while($row = mysql_fetch_row($table))
echo "<tr><td>".$row[0]."</td>";
echo "</table>
</td>
</tr>
</table>";
If you need to cater for more categories, do an initial search to determine the distinct categories, then put the section of code above that creates the inner table in a loop.
eg. in pseudo code:
echo the outer table <table><tr>
SELECT DISTINCT Category FROM details
while row1=get next category
$cat = row1[0];
echo "<td>
<table>
<tr><th>".$cat."</th></tr>";
$table = mysql_query("SELECT Name FROM details WHERE Category = '".$cat."'") or die(mysql_error());
while($row = mysql_fetch_row($table))
echo "<tr><td>".$row[0]."</td>";
echo "</table>
</td>
echo the </tr></table> to close the outer table

While loop Repeats infinitely

I have a while loop that populates a dropdown box with values from a mysql table. There are only two matching records and it is repeating them over and over. How do i only display each record once?:
$query = "SELECT * FROM members, sportevents, dates, results, event, userlogin ".
"INNER JOIN members AS m ON userlogin.id = m.id " .
"WHERE userlogin.username = '$un' " .
"AND sportevents.id = members.id " .
"AND sportevents.event_id = event.id " .
"AND sportevents.date_id = dates.id " .
"AND sportevents.result_id = results.id";
echo "<form method='POST' action='display.php'>";
echo "Please Select Your Event<br />";
echo "<select name='event'>";
echo "<option>Select Your Event</option>";
$results = mysql_query($query)
or die(mysql_error());
while ($row = mysql_fetch_array($results)) {
echo "<option>";
echo $row['eventname'];
echo "</option>";
}
echo "</select>";
echo "<input type='submit' value='Go'>";
echo "</form>";
Have you tried running that query manually in the mysql monitor? Nothing in your code would produce an infinite loop, so most likely your query is not doing joins as you expect and is doing a cross-product type thing and creating "duplicate" records.
In particular, your query looks very suspect - you're using the lazy "from multiple tables" approach, instead of explicitly specifying join types, and you're using the members table twice (FROM members ... and INNER JOIN members). You don't specify a relationship between the original members table and the joined/aliased m one, so most likely you're doing a members * members cross-product fetch.
give that you seem to be fetching only an event name for your dropdown list, you can try eliminating the unused tables - ditch dates and results. This will simplify things considerable, then (guessing) you can reduce the query to:
SELECT event.id, event.eventname
FROM event
INNER JOIN sportevents ON event.id = sportevents.event_id
INNER JOIN members ON sportevents.id = members.id
INNER JOIN userlogins ON members.id = userlogins.id
WHERE userlogins.username = '$un'
I don't know if the members/userlogins join is necessary - it seems to just feed sportevents.id through to members, but without knowing your DB's schema, I've tried to recreate your original query as best as possible.
You could always try changing the SELECT statement to a SELECT DISTINCT statement. That'll prevent duplicates of the selected fields.
Either that or reading all the results before displaying them, then de-duping them with something like array_unique().
Checkout My Example. It will be helped for you to understand. Because this code 100% working for me. Study it and get a solution.
And You Should Use DISTINCT keyword and GROUP BY Keyword. That's the Main Thing to prevent repeating values.
<?php
$gtid = $_GET['idvc'];
if(isset($_GET['idvc']))
{
$sql = mysql_query("SELECT DISTINCT gallery_types.gt_id, gallery_types_category.gtc_id, gallery_types_category.gt_category, gallery_types_category.gtc_image FROM gallery_types, gallery_types_category WHERE $_GET[idvc]=gtid GROUP BY gt_category");
mysql_select_db($database,$con);
while($row = mysql_fetch_array($sql))
{?>
<table>
<tr>
<td width="100px"><?php echo $row['gt_id'] ?></td>
<td width="100px"><?php echo $row['gtc_id'] ?></td>
<td width="300px"><?php echo $row['gt_category'] ?></td>
<td width="150px">
<a href='view_all_images.php?idvai=<?php echo $row[gtc_id] ?>' target='_blank'>
<img width='50' height='50' src='<?php echo $row[gtc_image] ?>' />
</a>
</td>
</tr>
</table>
<?php
}
}
?>
Better Understand, Follow Following Method,
$sql = mysql_query("SELECT DISTINCT table1.t1id, table2.t2id, table2.t2name FROM table1, table2 WHERE t1id=t2id GROUP BY t2name");

Combine total count for entries in 2 SQL tables

I can't seem to find the right way to do this so I was hoping someone could give me some direction?
The SQL Database is structured like this (I've removed the irrelevant stuff):
Requests
R_ID R_FulfilledBy
1 Bob
2 Craig
3 Bob
SIMs
SM_ID SM_FulfilledBy
1 Bob
2 Craig
3 Bob
I'm hoping to end up with this output:
Fulfilled By Requests
Bob 4
Craig 2
Here's my PHP/HTML:
<div id="table">
<?php
//Connect to MySQL Database
$connection = mysql_connect($runnerdbServer, $runnerdbUser, $runnerdbPass);
mysql_select_db($runnerdbName, $connection) or die("MysQL Error");
$query = "SELECT R_FulfilledBy, COUNT(R_ID) FROM Requests GROUP BY R_FulfilledBy ORDER BY COUNT(R_ID) DESC";
$result = mysql_query($query) or die(mysql_error());
?>
<!-- Number of Runners (Counts total number of records in Requests table) -->
<table border='0' width='50%'>
<tr>
<th>Runners Fulfilled</th>
<tr><td><?php
$query = mysql_query("SELECT * FROM Requests");
$number=mysql_num_rows($query);
echo $number;
?>
</td></tr>
</table>
<!-- Fulfillment Stats -->
<table border='0' width='50%'>
<tr>
<th>Name</th>
<th>Runners Fulfilled</th>
</tr>
<?
// Print out result (I want this to calculate requests fulfilled by each user in 'Requests' and 'SIMs' table)
while($row = mysql_fetch_array($result)){
echo "<tr>";
echo "<td>". $row['R_FulfilledBy'] ."</td>";
echo "<td>". $row['COUNT(R_ID)'] ."</td>";
echo "</tr>";
}
?>
</table>
At present it's only calculating the records from the 'Requests' table :(
You could union all the two tables together in a subquery:
select FulfilledBy
, count(*)
from (
select R_FulfilledBy as FulfilledBy
from Requests
union all
select SM_FulfilledBy
from SIMs
) as SubQueryAlias
group by
FulfilledBy
Use union all instead of union because the second eliminates duplicates; which would give everyone a maximum count of 1.
I'd go with this:
SELECT R_FulfilledBy, COUNT(*) +
( SELECT COUNT(*) FROM SIMs WHERE R_FulfilledBy = SM_FulfilledBy )
FROM Requests GROUP BY R_FulfilledBy

Categories