Split up array into rows - php

I have a table, with values from dat_eb_registrants as rows (e.g. $row[1]) and values from a horizontal array, extracted from dat_eb_field_values, I'd like to split those up so I can order everything into the table how I want it.
How the data gets put into my table:
$count = 0;
while ($row = mysql_fetch_row($result))
{
echo "<tr>";
$myArray[] ="<tr><td>" . $row[9] . "</td><td>"; echo $myArray[$count];
$count++;
echo "</tr>";
}
How all of the data get extracted from the database (yes, I know it's old):
SELECT dr.id, dr.first_name, dr.last_name, dr.email, dr.comment, dr.amount, dr.published, dr.transaction_id, dr.register_date, GROUP_CONCAT(df.field_value SEPARATOR '</td><td>')
FROM dat_eb_registrants dr
LEFT JOIN dat_eb_field_values df
ON dr.id=df.registrant_id
WHERE `event_id` >= 20 AND `event_id` <= 25
GROUP BY dr.id
ORDER BY '".$sort."', '".$ascdsc."'
Now, I want to put some rows from the first table (e.g. $row[1]) and (.eg. $row[2]) vertically, in the middle of the array. How can I do this?
Because the array fills my table in one time, and using the $rows, you can simply tell which rows to display where...
This is what I want (code might not be correct):
while ($row = mysql_fetch_row($result)) {
echo "<tr>";
echo "<td>"'.$row_table_1[1]'"</td>";
echo "<td>"'.$row_table_1[2]'"</td>";
echo "<td>"'.$row_table_2[35]'"</td>";
echo "<td>"'.$row_table_2[45]'"</td>";
echo "<td>"'.$row_table_1[5]'"</td>";
echo "<td>"'.$row_table_2[6]'"</td>";
echo "</tr>";
}
I used to do:
echo "<td>"; $result24 = mysql_query("SELECT field_id, field_value FROM dat_eb_field_values WHERE (field_id = 88) AND (registrant_id = $row[0])"); $r24 = mysql_fetch_row($result24); echo $r24[1]; echo "</td>";
echo "<td>"; $result25 = mysql_query("SELECT field_id, field_value FROM dat_eb_field_values WHERE (field_id = 57) AND (registrant_id = $row[0])"); $r25 = mysql_fetch_row($result25); echo $r25[1]; echo "</td>";
echo "<td>" . $row[5] . "</td>";
echo "<td>" . $row[6] . "</td>";
I want to do:
echo "<td>" . $rowfromsecondtable[1] . "</td>";
echo "<td>" . $rowfromsecondtable[2] . "</td>";
echo "<td>" . $row[5] . "</td>";
echo "<td>" . $row[6] . "</td>";
(using the code I gave above)
Preview of dat_eb_registrants:
| id | first_name | last_name | email |
------------------------------------------------------------------------
| 1 | Mike | Doe | mikedoe#hotmail.com |
| 2 | John | Smith | j_smith#hotmail.com |
Preview of dat_eb_field_values:
field 1 = fav.sport
field 2 = fav. color
field 3 = fav. food
| registrant_id | field_id | field_value |
----------------------------------------------------------
| 1 | 1 | tennis |
| 1 | 2 | green |
| 1 | 3 | spagetti |
| 2 | 1 | hockey |
| 2 | 2 | red |
| 2 | 3 | fish |
I need:
first_name | id | fav.sport | last_name | fav.food |
---------------------------------------------------------------------
Mike | 1 | Tennis | Doe | spagetti |
John | 2 | Hockey | Smith | fish |

Maybe I am missing something but why not just perform this task in SQL. This is basically a pivot. MySQL does not have a pivot but you can use an aggregate function with a CASE statement:
select r.first_name,
r.id,
r.last_name,
max(case when f.field_id =1 then f.field_value else null end) As FavSport,
max(case when f.field_id =2 then f.field_value else null end) As FavColor,
max(case when f.field_id =3 then f.field_value else null end) As FavFood
from dat_eb_registrants r
left join dat_eb_field_values f
on r.id = f.registrant_id
group by r.first_name, r.id, r.last_name
order by r.id
See SQL Fiddle with Demo
The result of the query is the output that you want:
| FIRST_NAME | ID | LAST_NAME | FAVSPORT | FAVCOLOR | FAVFOOD |
----------------------------------------------------------------
| Mike | 1 | Doe | tennis | green | spagetti |
| John | 2 | Smith | hockey | red | fish |
Or you can use multiple joins on the dat_eb_field_values table:
select r.first_name,
r.id,
r.last_name,
fSport.field_value FavSport,
fColor.field_value FavColor,
fFood.field_value FavFood
from dat_eb_registrants r
left join dat_eb_field_values fSport
on r.id = fSport.registrant_id
and fSport.field_id = 1
left join dat_eb_field_values fColor
on r.id = fColor.registrant_id
and fColor.field_id = 2
left join dat_eb_field_values fFood
on r.id = fFood.registrant_id
and fFood.field_id = 3
order by r.id
See SQL Fiddle with Demo. It produces the same result.

This does not answer your question but instead of using $row[9], $row[10] etc, you can just use the column names of your table as the row index.
$row['first_name']
$row['last_name']
and so on. It'll make your code more readable.
You might also want to grab all your data at first and then generate your html code. It'll look cleaner.
e.g
$result24 = mysql_query(sometihng here);
$r24 = mysql_fetch_row($result24);
$result25 = mysql_query(sometihng else here);
$r25 = mysql_fetch_row($result25);
//php code for table starts here
echo '<table>';

Related

How to dynamically use rowspan to print data in table in php and mysql?

In my program, the following query and code generate the following table like this:
+-------+---------+
|ward_id|Sub_block|
+-------+---------+
| 1 | A1 |
+-------+---------+
| 1 | B1 |
+-------+---------+
| 1 | C1 |
+-------+---------+
| 2 | D1 |
+-------+---------+
| 2 | E1 |
+-------+---------+
| 2 | F2 |
+-------+---------+
| 3 | K1 |
+-------+---------+
| 3 | G2 |
+-------+---------+
| 3 | I3 |
+-------+---------+
Here is my code that generate the above table.
if(isset($_POST["union_id"]) && !empty($_POST["union_id"]))
{
//Get all union data
$query = $mysqli->query("SELECT * FROM test_epi_table WHERE union_id = ".$_POST['union_id']);
//Count total number of rows
$rowCount = $query->num_rows;
//Display unions list
if($rowCount > 0)
{
echo "<hr>";
echo "<h3 align='center'>EPI Schedule</h3>";
echo "<table class='table table-bordered'>
<tr>
<th>Ward No</th>
<th>Sub-Block</th>
</tr>";
while($row = $query->fetch_assoc())
{
echo "<tr>";
echo "<td>" . $row['ward_no'] . "</td>";
echo "<td>" . $row['sub_block_name'] . "</td>";
echo "</tr>";
}
echo "</table>";
echo "<hr>";
}
else
{
echo "<br>";
echo "<h3 align='center'>Sorry, No Available Information!</h3>";
echo "<hr>";
}
}
Now I like to create the table like this. Mostly I think it is a rowspan task.
+-------+---------+
|ward_id|Sub_block|
+-------+---------+
| | A1 |
+ +---------+
| 1 | B1 |
+ +---------+
| | C1 |
+-------+---------+
| | D1 |
+ +---------+
| 2 | E1 |
+ +---------+
| | F2 |
+-------+---------+
| | K1 |
+ +---------+
| 3 | G2 |
+ +---------+
| | I3 |
+-------+---------+
what kind of changes do I need to add in my actual php code? Please help me out. Thanks in advance.
Use Inner query is one of the good way also you can use right outer join if you want it to be more efficient.

MYSQL select from table and count from another

I have subjects table contains subjects details and subject_student table contains the subjects selected by students. I want to select all the the subjects details selected by more than 2 students and also get the count of students for each subject selected by more than 2 students.
Subjects table
------------------------------
ID | Name | units
------------------------------
1 | web | 1
2 | programming | 1
3 | java | 1
4 | QA | 1
------------------------------
student_subject Table
Subject table
------------------------------
student_id | subject_id | status
------------------------------
1 | 1 | current
1 | 2 | current
2 | 1 | current
2 | 3 | current
3 | 1 | current
3 | 3 | current
4 | 1 | current
5 | 5 | current
------------------------------
so the result here must select the first row of subjects table and the 4 which is the count of students selected web subject
Here is the Query:
$query= "
SELECT s.sub_ID
, s.Name
, s.units
, count(st.subject_id) as cc
from subjects as s
LEFT
JOIN students_subject as st
ON s.ID = st.subject_id
GROUP
BY st.subject_id
Having count(st.subject_id)>2)
";
when I run the code it gives me this error:
Notice: Trying to get property of non-object
here is the PHP code:
global $con,$users;
$query= "SELECT s.sub_ID,s.Name, s.units,s.dept, count(st.subject_id)as cc from subjects as s LEFT JOIN students_subject as st
ON s.ID=st.subject_id GROUP BY st.subject_id Having count(st.subject_id)>2)";
//$query="SELECT * FROM subjects;";
$result=mysqli_query($con,$query);
if ( $result->num_rows == 0 ) // User doesn't exist
echo "Subjects doesn't exist!";
else { echo "
<tr>
<th>Subjects ID</th>
<th>Title</th>
<th>Units</th>
<th>Department</th>
<th>Check</th>
</tr>";
$r=0;
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['sub_ID'] . "</td>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['units'] . "</td>";
echo "<td>" . $row['cc'] . "</td>";
}
Check your query for names of tables and columns Subjects(ID,Name,units), students_subject(student_id,subject_id,status):
SELECT
sb.id AS sub_ID, -- !!!
sb.Name,
sb.units,
COUNT(st.student_id) AS cc
FROM Subjects sb
JOIN students_subject st ON st.subject_id=sb.id
GROUP BY sb.id,sb.name,sb.units
HAVING COUNT(st.student_id)>2
You also can use print_r in while for test names which were returned with mysqli_fetch_array
while($row = mysqli_fetch_array($result))
{
print_r($row);
...
Here doesn't need a bracket )
$query= "... Having count(st.subject_id)>2)"; // <--
Try to delete it
$query= "... Having count(st.subject_id)>2";

Getting Number of Rows using Left Join

I have two tables, one is comments, and another is likesordislikes
comments
+----+--------+---------------+---------+
| id | userid | usercom | comname |
+----+--------+---------------+---------+
| 35 | 5 | check comment | 12 |
| 36 | 6 | comment test | 12 |
| 37 | 6 | third comment | 12 |
| 38 | 5 | number four | 12 |
| 39 | 7 | fifth | 13 |
| 40 | 4 | 6th | 13 |
| 41 | 18 | seven | 13 |
+----+--------+---------------+---------+
likesordislikes
+----+-------+------+-------+
| id | vtype | uid | comid |
+----+-------+------+-------+
| 1 | 0 | 5 | 35 |
| 2 | 1 | 6 | 35 |
| 3 | 1 | 7 | 35 |
| 4 | 0 | 8 | 36 |
| 5 | 1 | 5 | 36 |
| 6 | 1 | 9 | 35 |
| 7 | 1 | 10 | 36 |
| 8 | 1 | 11 | 36 |
| 9 | 1 | 20 | 35 |
| 10 | 0 | 9 | 35 |
| 11 | 1 | 21 | 37 |
+----+-------+------+-------+
In comments table userid is session id (logged in user) and comname is the post unique id on which comments are made by logged in users.
In likesordislikes table vtype is vote type where (0 = dislike , 1 = like), uid is logged in user id who likes or dislikes a comment and comid is from comments table (id) column
Now, i want to show total number of likes or dislikes under each comment for this specific comment.
the PHP code i am trying is here
$query1 = "SELECT
comments.id,
comments.usercom,
COUNT(likesordislikes.id) AS count
FROM
comments
LEFT JOIN likesordislikes ON
comments.id=likesordislikes.comid
WHERE likesordislikes.vtype='1'
GROUP BY
comments.id";
$query2 = "SELECT
comments.id,
comments.usercom,
COUNT(likesordislikes.id) AS count
FROM
comments
LEFT JOIN likesordislikes ON
comments.id=likesordislikes.comid
WHERE likesordislikes.vtype='0'
GROUP BY
comments.id";
$stmt = $DB->prepare($query1);
$stmt->execute();
$likes = $stmt->fetchAll();
$tlikes = count($likes);
$stmt = $DB->prepare($query2);
$stmt->execute();
$dislikes = $stmt->fetchAll();
$tdislikes = count($dislikes);
$slt = "SELECT * FROM `comments` where `comname` = '$c_name' and `post` = '$type'";
$res = mysqli_query($con, $slt);
while($fetch = mysqli_fetch_array($res)) {
echo $fetch['usercom']."<br />";
echo "Likes ".$tlikes."<br />";
echo "Dislikes ".$tdislikes;
}
that way, its not showing each comments likes/dislikes under that comment
in more clearer way, I want this result
Comments:
check comment
Likes 4 - Dislikes 2
comment test
Likes 3 - Dislikes 1
third comment
Likes 1 - Dislikes 0
number four
Likes - Dislikes
fifth
Likes - Dislikes
6th
Likes - Dislikes
seven
Likes - Dislikes
But its showing Likes 4 - Dislikes 2 on each comment on the article 12
Can anyone please check whats wrong in it?
You're basically getting all the likes and dislikes, for all the comments:
$query1 = "...";
$query2 = "...";
// ...
$tlikes = count($likes);
// ...
$tdislikes = count($dislikes);
And printing them for all the comments:
echo $fetch['usercom']."<br />";
echo "Likes ".$tlikes."<br />";
echo "Dislikes ".$tdislikes;
Which is why you're getting the same values for every comment. In order to fix your current code, you could create a map for $likes and $dislikes, like this:
$stmt = $DB->prepare($query1);
$stmt->execute();
$likes = array();
while($like = $stmt->fetch(PDO::FETCH_ASSOC){
$likes[$like['id']] = $like['count'];
}
And then, change your printing to something like:
while($fetch = mysqli_fetch_array($res)) {
echo $fetch['usercom']."<br />";
echo "Likes ".(empty($likes[$fetch['id']])?0:$likes[$fetch['id']])."<br />";
// ...
}
Note: You probably should filter the likes and dislikes queries the same way you filter the comments query (so you don't ask for things you won't use)
An alternative way is changing your three queries for a single one, which would change your code to something like this:
$slt =
"SELECT" .
" c.usercom," .
" SUM(CASE WHEN lod.vtype=1 THEN 1 ELSE 0 END) likes," .
" SUM(CASE WHEN lod.vtype=0 THEN 1 ELSE 0 END) dislikes" .
" FROM" .
" comments c LEFT JOIN likesordislikes lod ON lod.comid=c.id" .
" WHERE" .
" c.comname = '$c_name' AND c.post = '$type'" .
" GROUP BY" .
" c.id"
;
$res = mysqli_query($con, $slt);
while($fetch = mysqli_fetch_array($res)) {
echo $fetch['usercom']."<br />";
echo "Likes ".$fetch['likes']."<br />";
echo "Dislikes ".$fetch['dislikes'];
}
Here you have the query in case you want to see it working
Update
If you don't want to show two zeros, you could change your while to something like:
while($fetch = mysqli_fetch_array($res)) {
echo $fetch['usercom']."<br />";
if($fetch['likes']==='0' && $fetch['dislikes']==='0'){
$fetch['likes'] = '';
$fetch['dislikes'] = '';
}
echo "Likes ".$fetch['likes']."<br />";
echo "Dislikes ".$fetch['dislikes'];
}
Your query looks at the comname columns meaning it would give you everything for article 12 as you call it summed up and not separate for each of them.
You should be looking at the ids - something like
$slt = "SELECT * FROM `comments` where `id` = '$id' and `post` = '$type'";
where $id is the id in your comments table.
I am not sure how you can get this given the code you have shown but give it a try.

MYSQLi Count and Group by

I have this table (sample)
|---id---|---place---|---admin---|
| 1 | Q | AJ |
| 2 | p | PM |
| 3 | w | AJ |
| 4 | t | TY |
| 5 | u | AJ |
I want to count how many places each admin control using MYSQLi not mysql.
I have searched and all what I found is MYSQL and using COUNT(*) and when I am trying to use it, does not work.
Thanks all in advance.
$result = mysqli_query("SELECT admin, COUNT(admin) as 'amount' FROM tablename GROUP BY admin");
while($row = mysqli_fetch_assoc($result))
echo "Name: " . $row['admin'] . " - ". $row['amount'] . "<br />";
Using count + GROUP by you can get the amount of times each admin appears in the table.

Sorting an array of information from another array output from SQL

I need to be retrieve multiple unique values from an array set of data. Currently they are extracted as follows :
while($row1 = mysql_fetch_array($result1))
{
echo "<tr>".
"<td>".$row1[0] . "</td>".
"<td>".$row1[1] . "</td>".
"<td>".$row1[2] . "</td>".
"<td>".$row1[3] . "</td>".
"<td>".$row1[4] . "</td>".
"<td>".$row1[5] . "</td>".
"<td>".$row1[6] . "</td>".
"<td>".$row1[7] . "</td>".
//$row1[8] is the number of hours
"<td>".$row1[8] . "</td>".
//$row1[9] is the user
"<td>".$row1[9] . "</td>";
}
As commented above, I need to accumulate the hours per user. However, I have problem sorting the array as the user value has to be unique in the array whereas the number has to keep stacking.
Really confused now. Appreciate any help offered.
EDIT : $row1[8] is an integer yes.
The sample data output table ( sorry no image) will be as follows :
------------------------------------------------------------------------------------------
Users |Telephone | Address | Postal Code | Hobbies | Interest| FB |Twitter | Insta | Hours
------------------------------------------------------------------------------------------
John | 92238726 | SG | 345322 | Running | Movies | 1 | 0 | 0 | 5
Tom | 922382134 | MY | 345212 | Soccer | Movies | 1 | 0 | 0 | 8
Jerry | 92238726 | SG | 342122 | stamps | Nil | 0 | 1 | 0 | 5
John | 92238726 | SG | 345322 | Running | Movies | 1 | 0 | 0 | 12
Jerry | 92238726 | SG | 342122 | stamps | Nil | 0 | 1 | 0 | 2
Based on the output above which was extracted with the mysql_fetch_array, I'd like to sort the information to something like the following :
Users | Total Hours
John | 17
Tom | 8
Jerry | 7
SQL CODE :
"select DISTINCT jl.refno, jl.logno, jl.attendee, jl.jobsummary, FROM_UNIXTIME(jl.date, '%d/%m/%y') AS 'Date-In', from_unixtime(jl.dateout + (15*3600), '%d/%m/%y') AS 'Date-Out', #timein := (left(jl.timein,2)*60+right(jl.timein,2)) AS 'Time-In', #timeout := (left(jl.timeout,2)*60+right(timeout,2)) AS 'Time-Out', #temp := ((dateout -date)* 24 * 60) + #timeout - #timein AS 'temp', us.username from joblog jl, projects proj, users us where jl.project ='{$value}' AND proj.id ='{$value}' AND jl.staff = us.id"
Since you are using MySQL anyway, I recommend you to do it with an SQL. It's cleaner.
Edit your query to:
SELECT users, SUM(hours) as total FROM userTable GROUP BY users ORDER BY total DESC;
UPDATE - PHP Edition:
You can do it like this in PHP.
$counters = array();
while ($row1 = mysql_fetch_array($result1)) {
$counters[$row1[9]] += $rows1[8];
}
arsort($counters);
foreach ($counters as $name => $total) {
// do your output here
}
<?php
function totalHours($user){
$result=mysql_query("select sum(hours) as total from table_name where users='".$user."'");
$row=mysql_fetch_array($result);
return $row['total'];
}
$result=mysql_query("select * from table_name group by users");
echo "</table>";
echo "<tr>
<td>User</td>
<td>Total Hours</td>
</tr>";
while($row1 = mysql_fetch_array($result1))
{
echo "<tr>".
"<td>".$row1[0]. "</td>".
"<td>".totalHours($row1[0]). "</td></tr>";
}
echo "</table>";
?>

Categories