removing same fetched data php - php

<?php
$con = mysqli_connect("localhost","root","","final_osa");
$s_stud = $con->query("SELECT * FROM violations_tbl GROUP BY violation_type");
while($data = $s_stud->fetch_assoc() ){
$bilang = $con->query("SELECT COUNT(*) FROM violations_tbl WHERE `violation_type` ='".$data['violation_type']."' ");
$result = $bilang->fetch_assoc();
if($result['COUNT(*)'] > 1 ){
echo "<tr>";
echo "<td>";
$query=$con->query("SELECT `violation_type` FROM `violations_tbl` WHERE `violation_type`='".$data['violation_type']."'");
while($row=$query->fetch_assoc() ){
echo $row['violation_type'].", ";
}
echo "</td>";
echo "</tr>";
}
}
?>
How can i eliminate same fetched data and echo only one? thanks
here is the one that it echoes. it should be that it will echo only one because its the same
What i'm trying to do here is get the mos violated rule in school thanks

If you want all the violations in order of most violated to least violated
$s_stud = $con->query("SELECT violation_type, count(violation_type) as num_violations
FROM violations_tbl
GROUP BY violation_type
ORDER BY num_violations DESC");
while($row= $s_stud->fetch_assoc() ){
//echo the violation and the count
if($row['num_violations'] > 1 ){
echo "<tr>";
echo "<td>$row[violation_type]</td>";
echo "<td>$row[num_violations]</td>";
echo "</tr>";
}
}
If you only want the MOST violated you could add a LIMIT 1 to the query and remove the looping.
$s_stud = $con->query("SELECT violation_type, count(violation_type) as num_violations
FROM violations_tbl
GROUP BY violation_type
ORDER BY num_violations DESC
LIMIT 1");
$row= $s_stud->fetch_assoc();
//echo the violation and the count
echo "<tr>";
echo "<td>$row[violation_type]</td>";
echo "<td>$row[num_violations]</td>";
echo "</td></tr>";

Related

Echo two SQL queries in one HTML table

I'm trying to display information from two queries in one single table, but can't figure out how to make it work.
This is what I got working with one query:
SELECT Company,COUNT(*) as count FROM Employee_Table GROUP BY Company ORDER BY count DESC;
Company Employees
ABC 45
DEF 15
GHI 5
Now beneath that I'd like to have another query that simply counts all rows, giving me the total amount of Employees.
SELECT Company,COUNT(*) as count FROM Employee_Table GROUP BY Company ORDER BY count DESC;
SELECT COUNT(*) AS Total FROM Employee_Table;
Company Employees
ABC 40
DEF 15
GHI 5
Total 60
This is what my code looks like right now. I defined two extra variables for my extra query that I want to echo out, but believe this is not the proper way to do it as I get an sqlsrv_fetch_array error.
$query1 = "SELECT Company,COUNT(*) as count FROM Employee_Table GROUP BY Company ORDER BY count DESC;";
$query2 = "SELECT COUNT(*) AS Totaal FROM Employee_Table;";
$result1 = sqlsrv_query($conn, $query1);
$result2 = sqlsrv_query($conn, $query2);
echo "<table id='total'>";
echo "<tr><th>Company</th><th>Amount of employees</th></tr>";
while ($row=sqlsrv_fetch_array($result1, $result2)) {
echo "<tr><td>";
echo $row["Company"];
echo "</td><td>";
echo $row["count"];
echo "</td><td>";
echo $row["Total"];
echo "</td></tr>";
}
echo "</table>";
How can this be achieved? I'd appreciate any help
First correct
sqlsrv_fetch_array()
see here http://php.net/manual/de/function.sqlsrv-fetch-array.php
Use just a single query and use mysqli_num_rows() function to count
$count = mysqli_num_rows($result);
I think you can achieve this by using only first query
$query1 = "SELECT Company,COUNT(*) as count FROM Employee_Table GROUP BY Company ORDER BY count DESC;";
$result1 = mysql_query($conn, $query1);
$total_employee = 0;
echo "<table id='total'>";
echo "<tr><th>Company</th><th>Amount of employees</th></tr>";
while ($row=mysql_fetch_array($result1)) {
echo "<tr><td>";
echo $row["Company"];
echo "</td><td>";
echo $row["count"];
$total_employee += $row["count"];
echo "</td><td>";
echo "</td></tr>";
}
echo "<tr><td>Total</td><td>$total_employee</td></tr>";
echo "</table>";
You can use only one query:
$result = sqlsrv_query($conn, "SELECT Company,COUNT(*) as count FROM Employee_Table GROUP BY Company ORDER BY count DESC");
?>
<table id='total'>
<tr><th>Company</th><th>Amount of employees</th></tr>
<?php
$total = 0;
while ($row=sqlsrv_fetch_array($result)) {
$total += $row["count"];
?>
<tr><td><?= $row["Company"] ?></td><td><?= $row["count"] ?></td></tr>
<?php
}
?>
<tr><td></td><td><?= $total ?></td></tr>
</table>
<?php
Try the following code
$query1 = "SELECT Company,COUNT(*) as count FROM Employee_Table GROUP BY Company ORDER BY count DESC;";
$query2 = "SELECT COUNT(*) AS Totaal FROM Employee_Table;";
$result1 = sqlsrv_query($conn, $query1);
$result2 = sqlsrv_query($conn, $query2);
echo "<table id='total'>";
echo "<tr><th>Company</th><th>Amount of employees</th></tr>";
while ($row=sqlsrv_fetch_array($result1)) {
echo "<tr><td>";
echo $row["Company"];
echo "</td><td>";
echo $row["count"];
echo "</td><td>";
echo "</td></tr>";
}
$rows = sqlsrv_fetch_array($result1)
echo "<tr><td>";
echo $rows["Total"];
echo "</td></tr>";
echo "</table>";

Using data from first mysqli query in second query and nesting results

I have multiple tables I am joining to use in results for a second query and nesting the second results inside the first results.
I am using the following code:
$result = mysqli_query($con,"SELECT info.lotto_id, info.name, info.number_balls, info.number_bonus_balls, info.db_name, country.name_eng AS country, currency.name AS currency, currency.symbol AS symbol, next.draw_date AS next_draw, next.jackpot AS next_jackpot
FROM info
LEFT JOIN country ON info.country_id = country.id_country
LEFT JOIN currency ON info.currency_id = currency.currency_id
LEFT JOIN next ON info.lotto_id = next.lotto_id
WHERE (info.active='1')
ORDER BY next_jackpot DESC");
while($lotto = mysqli_fetch_array($result))
{
echo "<table border='0' width='600px' align='center'>";
echo "<tr>";
echo "<td>";
echo "<h1>Results for:</h1>";
echo "</td>";
echo "<td align='right'>";
echo "<p><img src='images/". $lotto['lotto_id'] ."_big.png' alt='". $lotto['name'] ." Results'/></p>";
echo "</td>";
echo "</tr>";
echo "</table>";
$result2 = mysqli_query($con,"SELECT * FROM" .$lotto['db_name'].
"ORDER BY date DESC
Limit 3");
while($draw = mysqli_fetch_array($result2))
{
echo "<table class='results' align='center'>";
echo "<tr>";
$draw['display_date'] = strtotime($draw['date']);
$lotto['cols'] = $lotto['number_balls'] + $lotto['number_bonus_balls'];
echo "<td class='date' colspan='".$lotto['cols']."'>".date('D M d, Y', $draw['display_date']). "</td>";
if ($draw[jp_code] < "1")
{
echo "<td class='winner' align='center'>Jackpot Amount</td>";
}
else
{
echo "<td class='rollover' align='center'>Rollover Amount</td>";
}
It is giving me the following error: Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in /home/content/95/11798395/html/results/info_mysqli.php on line 59
This relates to my results2 query. Can somebody please suggest what I am doing wrong.
Thank you.
Change:
$result2 = mysqli_query($con,"SELECT * FROM" .$lotto['db_name'].
"ORDER BY date DESC
Limit 3");
to:
$result2 = mysqli_query($con, "SELECT * FROM {$lotto['db_name']} ORDER BY date DESC LIMIT 3");
if ($result === false) {
exit("Error: " . mysqli_error($con));
}

Using JOIN to display data in a table

Thanks for reading my question
i am trying to make *clients_id* from the table repair_jobs appear as the name from the table contacts
but i am having no luck
i have got 2 sql query's is this wrong?
the 1st
$query = "select * from repair_jobs";
this helps me display the information i need regarding the fields from repair_jobs and works
this is the 2nd
$query = "SELECT repair_jobs.client_id, contacts.name
FROM repair_jobs
INNER JOIN contacts
ON repair_jobs.client_id=contacts.name";
under that i have this to try to display the name of the client
echo "<td>{$client_id}</td>";
but it is only displaying the number and not the data (clients name) that i need
am i missing something?
Additional information
The client_id (repair_jobs) is a number and is the same as id (contacts) but wanting to display the name (contacts)
CLIENTS
Id – name – surname – phone – address
REPAIRS
Id – clients_id (same as id in clients) – unit – date – price
current code
<?php
//include database connection
include 'db_connect.php';
//query all records from the database
$query = "select * from repair_jobs";
//execute the query
$result = $mysqli->query( $query );
//get number of rows returned
$num_results = $result->num_rows;
//this will link us to our add.php to create new record
if( $num_results > 0){ //it means there's already a database record
//start table
//creating our table heading
echo " <table class='table_basic'>";
echo "<thead><tr>";
echo "<th>Job #</th>";
echo "<th>Name Of Unit</th>";
echo "<th>Client</th>";
echo "<th>Estimated Value</th>";
echo "</thead></tr><tbody><tr>";
//loop to show each records
while( $row = $result->fetch_assoc() ){
//extract row
//this will make $row['firstname'] to
//just $firstname only
extract($row);
//creating new table row per record
echo "<tr>";
echo "<td width='40px'><a href='rdetails.php?id={$id}'># {$id}</a></td>";
echo "<td>{$rmake} {$rmodel}</td>";
$query = "SELECT rj.client_id, c.name AS client_name FROM repair_jobs rj INNER JOIN contacts c ON rj.client_id=c.id";
echo "<td>{$client_name}</td>";
echo '<td align="center"><span class="badge badge-success">£';
$lhours = $labour;
$repaircosts = $ourcosts;
$labourpay = $labourcharge;
$sum_total = $repaircosts +($lhours * $labourpay);
print ($sum_total);
echo '</span></td>';
echo "</td>";
echo "";
}
echo "</tr></table>";//end table
}else{
//if database table is empty
echo "No records found.";
}
//disconnect from database
$result->free();
$mysqli->close();
?>
Change your 1st query to you join query, as there is no reason to do a 2nd query in the middle of your code. (also you never executed that query anyway).
//query all records from the database
$query = "SELECT repair_jobs.*, contacts.name as client_name
FROM repair_jobs
INNER JOIN contacts
ON repair_jobs.client_id=contacts.id";
Then in your table keep the $client_name
echo "<td>{$client_name}</td>";
<?php
include 'db_connect.php';
$query = "SELECT rj.Id AS job_number, rj.unit, rj.make, rj.model, c.name AS client_name, rj.price FROM repair_jobs rj INNER JOIN contacts c ON rj.clients_id = c.id ORDER BY c.date";
$result = $mysqli->query( $query );
$num_results = $result->num_rows;
if( $num_results > 0){ //it means there's already a database record
echo " <table class='table_basic'>";
echo "<thead><tr>";
echo "<th>Job #</th>";
echo "<th>Name Of Unit</th>";
echo "<th>Client</th>";
echo "<th>Estimated Value</th>";
echo "</tr></thead><tbody>";
while( $row = $result->fetch_assoc() ){
extract($row);
echo "<tr>";
echo "<td width='40px'><a href='rdetails.php?id={$job_number}'>#{$job_number}</a></td>";
echo "<td>{$make} {$model}</td>";
echo "<td>{$client_name}</td>";
echo "<td align='center'><span class='badge badge-success'>£";
$lhours = $labour;
$repaircosts = $ourcosts;
$labourpay = $labourcharge;
$sum_total = $repaircosts +($lhours * $labourpay);
echo $sum_total;
echo '</span></td>';
echo "</td>";
echo "</tr>";
}
echo "</tbody></table>";
} else {
echo "No records found.";
}
$result->free();
$mysqli->close();
?>

Why Isn't My Data Being Shown?

I have the following tables in my database:
Minutes: minute_id, subject, next_subject, approval, meeting_id
Agendas: agenda_id, subject, duration, approval, reason, meeting_id
I am using the following PHP code:
<?php
$result = mysql_query("SELECT * FROM Agendas INNER JOIN Minutes ON Minutes.meeting_id = Agendas.meeting_id WHERE Agendas.Approval = 'disapproved'")
or die(mysql_error()); ;
if (mysql_num_rows($result) == 0) {
echo 'You Have No New Messages';
} else {
while($info = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td><br/>" .'Title: '. $info['title']." </td>";
echo "<td><br/>" .'Approved?: '. $info['approval']. "</td>";
echo "<td><br/>" .'Reason: '. $info['reason']."</td>";
echo "<hr>";
}
}
echo "</tr>";
echo "</table>";
?>
I am not getting the desired data to be shown as I am only been presented with the message 'You Have No New Messages' when in the agendas table, there is a row which has a field disapproved!
Any ideas?
You are doing an INNER JOIN... make sure there is also an associated row in the minutes table, or else there will be no data to return, even if there is an entry in Agendas.

PHP while-loop not working with mysql_result

I have a Physician Query:
// Primary Physician Query
$qPhysician = mysql_query("SELECT * FROM physicians ORDER BY lastName ASC, firstName ASC");
$rowPhysician = mysql_fetch_array($qPhysician);
// State Query for Physician
$idStatePhysician = $rowPhysician['idstate'];
$qStatePhysician = mysql_query("SELECT * FROM states WHERE idstate=$idStatePhysician");
$rowStatePhysician = mysql_fetch_array($qStatePhysician);
// City Query for Physician
$idCityPhysician = $rowPhysician['idcity'];
$qCityPhysician = mysql_query("SELECT * FROM cities WHERE idcities=$idCityPhysician");
$rowCityPhysician = mysql_fetch_array($qCityPhysician);
I have a while loop to display all physicians row to a table:
$num = mysql_num_rows($qPhysician);
$i=0;
while($i < $num)
{
$idphysicians = $rowPhysician['idphysicians'];
if ($i % 2 == 0){
echo "<tr class='even' onclick=\"DoNav('physicianUpdate.php?idphysicians=$idphysicians');\">";
}
else{
echo "<tr class='odd' onclick=\"DoNav('physicianUpdate.php?idphysicians=$idphysicians');\">";
}
echo "<td>" . mysql_result($qPhysician,$i,"lastName") . "</td>";
echo "<td>" . mysql_result($qPhysician,$i,"firstName") . "</td>";
echo "<td>";
if(isset($rowPhysician['idcity'])){echo mysql_result($qCityPhysician,$i,"name");} else{}
echo "</td>";
$i++;
}
My problem is: I have 3 rows of data from my physicians table. Each has a value for 'idcity' reflecting the idnumber from my City table. However, the 1st row of Data displays the idcity=Name properly, but the 2nd and 3rd row gave an error:
Warning: mysql_result() [function.mysql-result]: Unable to jump to row 1 on MySQL result index 7 in C:\wamp\www\iPOC\physicians.php on line 55
Also, if I have a blank value for idcity on one of the row, it also generates an error.
Please help! Thanks in advance!
The problem is that you're using mysql_result() with a one-way result. The correct fix is to use one of the mysql_fetch_*() functions instead, checking the returned value in your while loop.
while($row = mysql_fetch_array($qPhysician)) {
...
}
Something like this would probably work better:
$qCityPhysician = mysql_query("SELECT * FROM cities WHERE idcities=$idCityPhysician");
$qCityPhysicians = array();
while($row = mysql_fetch_array($qCityPhysician)) {
$qCityPhysicians[$row['idcity']] = $row['name'];
}
$qPhysician = mysql_query("SELECT * FROM physicians ORDER BY lastName ASC, firstName ASC");
$i=0;
while($row = mysql_fetch_array($qPhysician)) {
if ($i % 2 == 0) {
echo "<tr>";
echo "<td>" . $row['lastName'] . "</td>";
echo "<td>" . $row['firstName'] . "</td>";
echo "<td>";
if(isset($row['idcity'])) {
echo $qCityPhysicians[$row['idcity']];
}
echo "</td>";
$i++;
}
}

Categories