how to display / Select a MYSQL query horizontally - php

I am currently extracting some timetable information from my database.
I am facing a problem that I need the rows in cols and cols in rows.
The query is as:
SELECT `courses`.`course_id`,`faculty`.`uName`,`rooms`.`room_name`,`slot_allocs`.`slot_num`
FROM `faculty`
LEFT JOIN `courses` ON `courses`.`fac_id` = `faculty`.`uName`
LEFT JOIN `depts` ON `faculty`.`dept_code` = `depts`.`dept_code`
LEFT JOIN `slot_allocs` ON `slot_allocs`.`course_id` = `courses`.`course_id`
LEFT JOIN `rooms` ON `slot_allocs`.`room` = `rooms`.`room_name`
LEFT JOIN `slots` ON `slot_allocs`.`table_name` = `slots`.`table_name` AND `slot_allocs`.`day` = `slots`.`day` AND `slot_allocs`.`slot_num` = `slots`.`slot_num`
WHERE `slot_allocs`.`day` = 1 AND `depts`.`dept_code` = 100
ORDER BY `slots`.`slot_num` ASC
After I execute my PHP file in which this query executes it's in a sequential retrieve and show, I would like to have the output -- > one after the another
> > **I want to align in the sequential manner of the period per day like this:
> >|---------------------------------------------
> >day 1| period 1 |period 2 |period 3 |period 4|
> >|----|----------|---------|---------|--------|
> >day 2| period 1 |period 2 |period 3 |period 4|
> >|---------------------------------------------
And this is my php code:
$sql = file_get_contents("eboard.sql");
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<table>";
echo "<tr>";
echo "<td>";
echo " Course: ID ". $row["course_id"]." : ";
echo " Prof.:". $row["uName"]." : ";
echo " Room :".$row["room_name"]." : ";
echo " period".$row["slot_num"]."";
echo "</td>";
echo "</tr>";
echo "</table>";
}
} else
echo "0 results";
$conn->close();
The output i get : ---
Please help !!

Move the <table> out of the loop:
if ($result->num_rows > 0) {
echo "<table>";
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>";
echo " Course: ID ". $row["course_id"]." : ";
echo " Prof.:". $row["uName"]." : ";
echo " Room :".$row["room_name"]." : ";
echo " period".$row["slot_num"]."";
echo "</td>";
echo "</tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();

Ok, So this code should do it. You should read up on how tables works. W3Schools have a simple page about it. I hope this version is what you want. It is not a full solution but it shows you how to use tables.
if ($result->num_rows > 0) {
echo "<table>";
echo " <tr>";
echo " <th>Course</th>";
echo " <th>Prof.</th>";
echo " <th>Room</th>";
echo " <th>Period</th>";
echo " </tr>";
while($row = $result->fetch_assoc()) {
echo " <tr>";
echo " <td>Course: ID ". $row["course_id"]."</td>";
echo " <td>Prof.:". $row["uName"]."</td>";
echo " <td>Room :".$row["room_name"]."</td>";
echo " <td>period".$row["slot_num"]."</td>";
echo " </tr>";
}
echo "</table>";
} else {
echo "0 results";
}

Related

removing same fetched data 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>";

mysql get the value of a column in a database as a percentage

I have a table in a database and am currently pulling data using the SELECT statement Where the information from the column Opinion equals either Negative or Positive.
what i want to also do is output the positive data as an overall percentage but Unsure if that would be possible i had a look at multiple overflow questions but couldn't see anything. Any help would be appreciated.
$sql = "select Opinion from survey where Opinion = 'Positive'";
$result = mysqli_query($con, $sql);
if (!$result) {
die(mysqli_error($con));
}
echo "<div style='overflow: auto;'>";
echo "<table width=40% border=1 align=center >
<tr>
<th>Opinion</th>
<th>Date</th>
</tr>";
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo '<tr align=center>';
echo "<td>" . $row['Opinion'] . "</td>";
}
} else {
echo "0 results";
}
?>
The query will calculate how many percentage of 'Positive' opinions compared to total rows of the 'survey' table:
select (SUM(IF(Opinion = 'Positive',1,0))/count(*))*100 as percentage_positive
from survey
The query below can determine the percentage of each different opinions at once:
select
Opinion,
count(*) as total,
(count(*) / (select count(*) from survey))*100 as percentage
from survey
group by opinion
Something like this as SQL query?
SELECT COUNT(Opinion) / (SELECT COUNT(Opinion) FROM survey) * 100
FROM survey
WHERE Opinion = 'Negative'
After help from Kevin HR i have fixed my issue with the code below.
$sql = "select Opinion,count(*) as total,(count(*) / (select count(*) from survey))*100 as percentage from survey group by opinion";
$result = mysqli_query($con, $sql);
echo "<div style='overflow: auto;'>";
echo "<table width=40% border=1 align=center >
<tr>
<th>Opinion</th>
<th>Percentage</th>
</tr>";
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo '<tr align=center>';
echo "<td>" . $row['Opinion'] . "</td>";
echo "<td>" . $row['percentage'] . "</td>";
}
}
else {
echo "0 results";
}
Working code for getting the value of number of rows from a database
$sql = "SELECT * FROM `survey` WHERE Opinion='Positive'";
$connStatus = $con->query($sql);
$numberOfRows = mysqli_num_rows($connStatus);
echo "There are a total number of $numberOfRows Positive rows in the database";
echo "<br>";
echo "<br>";

Calculating Age Sql query

good day guys i have my code here to get age from date of birth stored in my database.
$connect=mysql_connect("localhost","root","");
mysql_select_db("mydb",$connect);
$query = "select date_format(now(), '%Y') - date_format(dob, '%Y') - (date_format(now(), '00-%m-%d') < date_format(dob, '00-%m-%d'))
as age from data";
$result = mysql_query($query);
$values = mysql_fetch_assoc($result);
$age = $values['age'];
$query="select * from data";
$result=mysql_query($query);
if(mysql_num_rows($result)>0){
echo "<table align='center' border='1'>";
echo "<tr>";
echo "<th>id</th>";
echo "<th>Last Name</th>";
echo "<th>First Name</th>";
echo "<th>Age</th>";
echo "</tr>";
while($row=mysql_fetch_array($result)){
echo "<tr>";
echo "<td>".$row['id']."</td>";
echo "<td>".$row['lname']."</td>";
echo "<td>".$row['fname']."</td>";
echo "<td>".$age."</td>";
echo "</tr>";
}
echo "</table>";
}
all data is fetch but the only problem is the age of the first row is the same as the rest of my data. what wrong with my code? anybody help please thank you.
You are printing pre-fetched age from values array.
Instead read from current row and use to display.
Change your SQL query as below:
$query = "select id, lname, fname,
date_format(now(), '%Y') - date_format(dob, '%Y')
- ( date_format(now(), '00-%m-%d')
< date_format(dob, '00-%m-%d'))
as age
from data";
Change:
echo "<td>".$age."</td>";
To:
echo "<td>".$row['age']."</td>";
The problem is you are fetching the age for single time, get the dob in while loop and then calculate the age and print the age in while loop itself.
You are getting age once and using it for rest of your data.
Try something like this:
<?php
$connect = mysql_connect("localhost", "root", "");
mysql_select_db("mydb", $connect);
$query = "select * from data";
$result = mysql_query($query);
if (mysql_num_rows($result) > 0) {
echo "<table align='center' border='1'>";
echo "<tr>";
echo "<th>id</th>";
echo "<th>Last Name</th>";
echo "<th>First Name</th>";
echo "<th>Age</th>";
echo "</tr>";
while ($row = mysql_fetch_array($result)) {
$query1 = "select date_format(now(), '%Y') - date_format(dob, '%Y') - (date_format(now(), '00-%m-%d') < date_format(dob, '00-%m-%d'))
as age from data where id = $row[id]";
$result1 = mysql_query($query);
$values1 = mysql_fetch_assoc($result);
$age = $values1['age'];
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['lname'] . "</td>";
echo "<td>" . $row['fname'] . "</td>";
echo "<td>" . $age . "</td>";
echo "</tr>";
}
echo "</table>";
}
Considering your age formula is right, try this query.
// query will give all records and age for each record.
$query="SELECT a.*, (SELECT TIMESTAMPDIFF(YEAR,dob,NOW()) FROM data AS b WHERE a.id = b.id) AS age FROM data AS a";
// rather than getting two result sets, you have age in the same record now, access it as a field.
$result=mysql_query($query);
if(mysql_num_rows($result)>0){
echo "<table align='center' border='1'>";
echo "<tr>";
echo "<th>id</th>";
echo "<th>Last Name</th>";
echo "<th>First Name</th>";
echo "<th>Age</th>";
echo "</tr>";
while($row=mysql_fetch_array($result)){
echo "<tr>";
echo "<td>".$row['id']."</td>";
echo "<td>".$row['lname']."</td>";
echo "<td>".$row['fname']."</td>";
echo "<td>".$row['age']."</td>"; // get age from db results
echo "</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));
}

mysql php subtract 2 fields from 2 tables Improving Query

hi guys im trying to improve my query for better performance is it possible to write this query in better way thanks a lot your helps
$query = " SELECT A FROM out_org where zone_id='1'";
$query2 = " SELECT A FROM out_dis where zone_id='1'";
$result = mysql_query($query);
$result2 = mysql_query($query2);
echo "<table border=1 style='background-color:#F0F8FF;' >";
echo "<caption><EM>my table</EM></caption>";
echo "<tr>";
echo "<th>" .OA. "</th>" ;
echo "<th>" .DA. "</th>";
echo "<th>" .total. "</th>";
echo "</tr>";
while($row = mysql_fetch_array($result) )
{
while( $row2 = mysql_fetch_array($result2)){
echo "<tr>";
echo "<td>" .$row['A']."</td>";
echo "<td>" .$row2['A']."</td>";
echo "<td>" .$total = $row['A'] - $row2['A']."</td>";
echo "</tr>";
}
echo "</table>";
}
Change your SQL to one query using a join and do the subtraction within the query:
$query = "SELECT (o1.A - o2.A) as value
FROM out_org o1
LEFT JOIN out_dis o2
ON o1.zone_id = o2.zone_id
WHERE o1.zone_id='1'";

Categories