Horizontal table instead of vertical with PHP - php

I created a horizontal html table with php using the suggested solution on this post: Printing out a table horizontal instead of vertical using PHP
And my code is like this:
$sql="SELECT Pr1, Pr2, Pr3, Pr4 FROM Tbdata ORDER BY Date DESC";
$result=mysqli_query($con,$sql);
$row=mysqli_fetch_assoc($result);
$Pr1 = '';
$Pr2 = '';
$Pr3 = '';
$Pr4 = '';
while($row = $result->fetch_assoc())
{
$Pr4 .= '<td>'.$row['Pr4'].'</td>';
$Pr3 .= '<td>'.$row['Pr3'].'</td>';
$Pr2 .= '<td>'.$row['Pr2'].'</td>';
$Pr1 .= '<td>'.$row['Pr1'].'</td>';
}
echo '
<table class="table">
<tbody>
<tr>
<td>'.$Pr4.'</td>
</tr>
<tr>
<td>'.$Pr3.'</td>
</tr>
<tr>
<td>'.$Pr2.'</td>
</tr>
<tr>
<td>'.$Pr1.'</td>
</tr>
</tbody>
</table>
';
?>
The code works fine. The only problem is that I extract data with Date DESC in the query. For some reason, the data of the most recent date doesn't appear on the table. What am I missing here? please Thanks.

Every fetch call advances the row count 1 position. Only have the while fetch call. Remove the preceding one (or comment it out, as I have to show).
//$row=mysqli_fetch_assoc($result);
$Pr1 = '';
$Pr2 = '';
$Pr3 = '';
$Pr4 = '';
while($row = $result->fetch_assoc())

You discard the first line...
$sql="SELECT Pr1, Pr2, Pr3, Pr4 FROM Tbdata ORDER BY Date DESC";
$result=mysqli_query($con,$sql);
$row=mysqli_fetch_assoc($result); // Reads row, comment this out
Comment out that last line.
Also as you wrap each item in <td> tags, you don't need them in...
<td>'.$Pr4.'</td>
So remove the <td> and </td> tags in these.

Related

PHP How do you separate your results to echo in two divs of the one page?

I know how to produce results one after another but how do you separate them? So in my sql I'm selecting * from table and limiting it to 4
$sql = "SELECT * FROM table limit 4";
$result = $conn->query($sql);
while($row = $result->fetch_assoc())
{$rows['id']=$row;};
$price = $row['price'];
I dont seem to get any result, any suggestions, sorry guys beginner
...<?php echo $id ?></font></span>
<h4><?php echo $price ?></h4></div>
<div class="planFeatures"><ul>
<li><h1><?php echo $id=2 ?></h1></li>//how do I echo the next id?
<li><?php echo $price2 ?></li> //also the next price which id now is also 2
//and so on......
How do I display the next increments results in a different area of the same page, within another div?
I do get results if I sql and re-select all over again (and say id=2) but I'm sure there is a better way of doing it because I've already got my 4 results with my limit.
It seems you are not saving the results from the query result properly. Each iteration of the loop overwrites the same bucket in the $rows array. Instead, you need to add elements to the $rows array; this will produce an indexed array. Then you can iterate over it and generate the HTML content.
<?php
// Perform query.
$sql = "SELECT * FROM table limit 4";
$result = $conn->query($sql);
// Fetch results
while (true) {
$row = $result->fetch_assoc();
if (!$row) {
break;
}
$rows[] = $row;
}
// Generate HTML content using $rows array.
?>
<table>
<thead>
<tr>
<th>ID</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<?php foreach ($rows as $row):?>
<tr>
<td>ID: <?php print $row['id'];?></td>
<td>Price: <?php print $row['price'];?></td>
</tr>
<?php endforeach;?>
</tbody>
</table>
I took some liberty in the above example and generated a simple HTML table. Of course you can modify this to generate whatever you want.
I hope I've interpreted your question accurately, apologies if not!

Move to next colum if condition is true when create table with loop in Php

so, what i wanted to do is show the total clicks per Category id of the items only for 20 items order by the highest total clicks per day.
now i am using hard code and the result have to looks like this
so, if the item id and total clicks already fill up the
20columns (for item id and total clicks) + 2 for the tittle so means
22columns
it has to move to next row.
because i am reffering to my db, so i am using loop to create the table, and when i doing that way, i am getting this result....
the result will keep showing until the end in the left side. thats very hard to read for report purposes. so i wanted the result looks like the first figure that i've uploaded.
here is what i am doing now
include "Con.php";
//get the value from Get Method
$CatidValue = $_GET['CatIds'];
//(The date format would looks like yyyy-mm-dd)
$DateFrom = $_GET['DateFrom'];
$DateTo = $_GET['DateTo'];
//select the CatID
$SqlGet= "Select CatId from try where CatId = $CatidValue";
$_SqlGet = mysqli_query($connection,$SqlGet);
$TakeResultGet = mysqli_fetch_array($_SqlGet);
$CatIdTittle = $TakeResultGet ['CatId'];
echo"
For Category Id : $CatIdTittle
<br>
";
//For Loop purpose and break the value
$explodeValueFrom = explode("-",$DateFrom);
$explodeValueTo = explode("-",$DateTo);
$DateValueFrom = $explodeValueFrom[0].$explodeValueFrom[1].$explodeValueFrom[2];
$DateValueTo = $explodeValueTo[0].$explodeValueTo[1].$explodeValueTo[2];
//Loop through the date
for($Loop=$DateValueFrom; $Loop <= $DateValueTo; $Loop++){
$YearLoop= substr($Loop, 0,4);
$MonthLoop =substr($Loop, 4,2);
$DayLoop = substr($Loop, 6,2);
$DateTittleValue = $YearLoop."-".$MonthLoop."-".$DayLoop;
$trValue = "<th class='tg-amwm' colspan='2'>$DateTittleValue</th>";
echo"
<table class='tg'>
<tr>
$trValue
</tr>
";
echo"
<table class='tg'>
<tr>
<td class='tg-yw4l'>Items Id</td>
<td class='tg-yw4l'>Total Clicks</td>
</tr>
";
//to get the item id and total clicks
$SqlSelect = "select `Item Id`,`Total Clicks`,Day from try where CatId = $CatidValue and Day = '$DateTittleValue' ORDER BY `try`.`Total Clicks` DESC limit 20";
$_SqlSelect = mysqli_query($connection,$SqlSelect);
foreach ($_SqlSelect as $ResultSelect) {
$Day = $ResultSelect['Day'];
$ItemId = $ResultSelect['Item Id'];
$TotalClicks = $ResultSelect['Total Clicks'];
echo"
<tr>
<td class='tg-yw4l'>$ItemId</td>
<td class='tg-yw4l'>$TotalClicks</td>
</tr>
";
}
}
?>
You dont need to declare your trValueTitle in the loop. Plus you need to concatenate it in your echo, try this :
$trValueTittle ="1"."<th class='tg-amwm' colspan='2'>$DateTittleValue</th>" ;
echo"<table class='tg'>";
for($loopForTr=1; $loopForTr<=3; $loopForTr++){
echo"<tr>". $trValueTittle ."</tr>";
}
I don't know what you want to do with the "1", but I think this is what you want to do:
echo "<table class='tg'>";
for($loopForTr=1; $loopForTr<=3; $loopForTr++){
$trValueTittle ="<th class='tg-amwm' colspan='2'>$DateTittleValue</th>";
echo"
<tr>
$trValueTittle
</tr>";
}
echo "</table>";
$trValueTittle ="1"."<th class='tg-amwm' colspan='2'>$DateTittleValue</th>" ;
echo"<table class='tg'>
<thead>
<tr>";
for($loopForTr=1; $loopForTr<=3; $loopForTr++){
echo $trValueTittle;
}
echo"</tr>
</thead>
</table>";
#Mantello, good answer, but i think it's better to keep out the "tr" from the loop, cause usually you don't want to place your tableheads (th) in different rows.
#Rax your Code won't work. You'll recive an error. You can't output a Variable the way you did in your echo.
echo"<tr> '.$trValueTittle.' </tr>";
would be fine. But there's also no need to define your variable inside the for loop. This way you slow up your script.

While loop is not displaying all values

I am having this weird problem.
There are seven admins: darth, jane, luke, najin, root, sam and sydney.
CODE:
<table>
<tr>
<th style="text-align: left; width: 200px;">Username</th>
<th colspan="2" style="text-align: left;">Action</th>
</tr>
<?php
$sql = "SELECT * FROM admins ORDER BY Admin_Username ASC";
$result = mysqli_query($connection, $sql);
$admin = mysqli_fetch_assoc($result);
while($admin = mysqli_fetch_assoc($result)) {
?>
<tr>
<td><?php echo ($admin["Admin_Username"]); ?></td>
<td>Edit</td>
<td>Delete</td>
</tr>
<?php
}
?>
</table>
If I use ASC order, the first admin, darth is not displayed in the loop and if I use DESC order, the last admin, sydney doesn't show up.
What could be the problem here?
Get rid of the first $admin = line.
Your loop will fetch all of them; you don't need to fetch the first one separately (and if fact by doing so are skipping it, because your loop immediately fetches the second before the first one could be written out).
remove this line
$admin = mysqli_fetch_assoc($result);//You already fetching the first result here
You have a redundant call to $admin = mysqli_fetch_assoc($result); before the while loop which will cause you to skip the first row of the result. Just remove it and you should be fine.
<?php
$sql = "SELECT * FROM admins ORDER BY Admin_Username ASC";
$result = mysqli_query($connection, $sql);
while($admin = mysqli_fetch_assoc($result)) {
?>
<tr>
<td><?php echo ($admin["Admin_Username"]); ?></td>
<td>Edit</td>
<td>Delete</td>
</tr>
<?php
}
?>
$admin = mysqli_fetch_assoc($result);
This must be in while loop So you can descard/remove old value above while

How do output combined results from two MySQL tables using PDO

I have the following two table structures in MySQL, which record details of a conference call and those participants that joined it:
Table: conference:
conference_sid, date_created, date_completed, RecordURL, PIN
*date_created and *date_completed are timestamps
Table: participants:
conference_sid, call_sid, call_from, name_recording
I want to output a simple table, that displays the following results for each conference_sid as a separate row:
<table>
<thead>
<th>Date</th>
<th>Duration</th>
<th>Participants</th>
<th>Recording</th>
</thead>
<tbody>
<tr id="conference_sid">
<td>date_created</td>
<td>duration: [date_completed - date_created in h/mm/ss]</td>
<td>
<li>call_from [for all participants in that conference_sid]
<li>call_from...
</td>
<td>
Call recording
</td>
</tr>
<tr id="conference_sid">
...
</tr>
</tbody>
</table>
I only want this table to show relevant results for conferences that have the same PIN as the user's Session::get('PIN')
You can combine the participants using GROUP_CONCAT
SELECT
conf.conference_sid,
date_created,
TIMEDIFF(date_completed, date_created) AS duration,
conf.RecordURL,
conf.PIN,
GROUP_CONCAT(pid SEPARATOR ",") AS pid,
GROUP_CONCAT(call_sid SEPARATOR ",") AS call_sid,
GROUP_CONCAT(call_from SEPARATOR ",") AS call_from,
GROUP_CONCAT(name_recording SEPARATOR ",") AS name_recording
FROM
conference conf
LEFT OUTER JOIN
participants p ON p.conference_sid = conf.conference_sid
WHERE
conf.PIN = 123
GROUP BY conf.conference_sid
Refer SQLFIDDLE and MySQL documentation about TIMEDIFF.
Now the application logic will be
<?php
$pin = 123;
$db = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$stmt = $db->prepare(
'SELECT
conf.conference_sid,
date_created,
timediff(date_completed, date_created) AS duration,
conf.RecordURL,
conf.PIN,
GROUP_CONCAT(pid SEPARATOR ",") AS pid,
GROUP_CONCAT(call_sid SEPARATOR ",") AS call_sid,
GROUP_CONCAT(call_from SEPARATOR ",") AS call_from,
GROUP_CONCAT(name_recording SEPARATOR ",") AS name_recording
FROM
conference conf
LEFT OUTER JOIN
participants p ON p.conference_sid = conf.conference_sid
WHERE
conf.PIN = :pin
GROUP BY conf.conference_sid');
$stmt->bindParam(':pin', $pin);
?>
<table border="1">
<thead>
<th>Date</th>
<th>Duration</th>
<th>Participants</th>
<th>Recording</th>
</thead>
<tbody>
<?php
$stmt->execute();
while ($row = $stmt->fetch()) {
?>
<tr>
<td><?php echo $row['date_created']; ?></td>
<td><?php echo $row['duration']; ?></td>
<td>
<table border="1">
<thead>
<th>call_sid</th>
<th>call_from</th>
<th>name_recording</th>
</thead>
<tbody>
<?php
$length = count(explode(',', $row['pid']));
$call_sid = explode(',', $row['call_sid']);
$call_from = explode(',', $row['call_from']);
$name_recording = explode(',', $row['name_recording']);
for ($i=0; $i < $length; $i++) {
?>
<tr>
<td> <?php echo $call_sid[$i]; ?> </td>
<td> <?php echo $call_from[$i]; ?></td>
<td> <?php echo $name_recording[$i]; ?> </td>
<tr>
<?php
}
?>
</tbody>
</table>
</td>
<td>
<a href="<?php echo $row['RecordURL']; ?>">
Call recording</a>
</td>
</tr>
<?php
}
?>
</tbody>
You will get the result set with comma(,) separated values in pid, call_sid, call_from, and name_recording. You can convert this string to array using explode.
array explode ( string $delimiter , string $string [, int $limit ] )
Returns an array of strings, each of which is a substring of string
formed by splitting it on boundaries formed by the string delimiter.
I won't do the PHP part, as I am not that knowledgeable in PHP, but here is the SQL:
SELECT *
FROM `conference`, `participants`
WHERE `conference`.PIN = $PIN AND
`participants`.conference_sid = `conference`.conference_sid
This will return rows with the information from conference and the participants of those conferences, joined into one row.
The following query will give you the information you need to display:
SELECT c.conference_sid
, c.date_created
, timediff(c.date_completed, c.date_created) AS duration
, p.call_from
, p.name_recording
, c.RecordURL
FROM conference c
JOIN participants p
ON c.conference_sid = p.conference_sid
WHERE c.PIN = :PIN
ORDER BY c.conference_sid
You will need to process the results with a nested loop. The outer loop should advance each time the conference_sid changes. The inner loop will display each element of the participants list for that conference.
This will be my take on it, it uses 2 separate queries to keep the data kinda separated. I use fetchAll() for brevity but this could have performance issues, luckily this can be accomodated. I didn't put any error checking, if you want it or you have questions, please ask
<?php
// assume $db is a PDO connection to the database
/* #var $db PDO */
$q = 'SELECT conference_sid, date_created, date_completed, RecordURL, PIN'
.' FROM conference';
// we need these
$conferences = $db->query($q)->fetchAll(PDO::FETCH_CLASS,'stdClass');
// let's group them as CSV, and concatenate the contents with ":"
$q = 'SELECT conference_sid,GROUP_CONCAT(CONCAT_WS(":",call_from,name_recording)) AS parts '
.' FROM participants GROUP BY conference_sid';
$conf_parts = array();
foreach ($db->query($q)->fetchAll(PDO::FETCH_CLASS,'stdClass') as $parts) {
// save the participants as an array, their data is still joined though
$conf_parts[$parts->conference_sid] = explode(',',$parts->parts);
// their contents will be exploded later
}
?>
<table>
<thead><th>Date</th><th>Duration</th><th>Participants</th><th>Recording</th></thead>
<tbody><?php foreach ($conferences as $conference) {
$csid = $conference->conference_sid;
// http://stackoverflow.com/questions/3108591/calculate-number-of-hours-between-2-dates-in-php
// Create two new DateTime-objects...
$date1 = new DateTime($conference->date_completed);
$date2 = new DateTime($conference->date_created);
// The diff-methods returns a new DateInterval-object...
$diff = $date2->diff($date1);
?><tr id="<?php echo $csid; ?>">
<td><?php echo $conference->date_created; ?></td>
<td><?php echo $diff->format('H/i/s'); ?></td>
<td>
<ul><?php foreach ($conf_parts[$csid] as $participant) {
// we have each participant for this conference call
list ($call_from, $name_recording) = explode($participant,':');
// and now we have the required data from each participant
?><li><?php echo $call_from; ?></li><?php
} ?></ul>
</td>
<td>
Call recording
</td>
</tr><?php
} ?></tbody>
</table>
In this particular contex I prefer to use two separated queries. Here's how I would do it:
<?php
try {
$db = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Could not connect to db';
exit;
}
$stmt_conferences = $db->prepare(
'SELECT
date_created,
timediff(date_completed, date_created) AS duration,
RecordURL,
conference_sid
FROM
conference
WHERE
PIN=:pin');
$stmt_conferences->bindParam(':pin', $pin);
$stmt_participants = $db->prepare(
'SELECT
name_recording,
call_from
FROM
participants
WHERE
conference_sid=:confsid');
$stmt_participants->bindParam(':confsid', $confsid);
?>
<table>
<thead>
<th>Date</th>
<th>Duration</th>
<th>Participants</th>
<th>Recording</th>
</thead>
<tbody>
<?php
$pin = 1; /* get your PIN here */
$stmt_conferences->execute();
while ($row = $stmt_conferences->fetch()) {
?>
<tr>
<td><?php echo htmlspecialchars($row['date_created'], ENT_QUOTES); ?></td>
<td><?php echo htmlspecialchars($row['duration'], ENT_QUOTES); ?></td>
<td>
<?php
$confsid = $row['conference_sid'];
$stmt_participants->execute();
while ($participant = $stmt_participants->fetch()) {
?>
<li><a href="<?php echo htmlspecialchars($participant['name_recording'], ENT_QUOTES); ?>">
<?php echo htmlspecialchars($participant['call_from'], ENT_QUOTES); ?>
</a>
<?php
}
?>
</td>
<td>
<a href="<?php echo htmlspecialchars($row['RecordURL'], ENT_QUOTES); ?>">
Call recording</a>
</td>
</tr>
<?php
}
?>
</tbody>
Please notice that you have to add some code to handle errors and to correctly escape all data you echo (can you really trust your database?). Also element IDs should be unique within the entire document, you can have just one id="conference_sid" in your page. Use classes instead.
Edit
If you can really trust your database, then you can just output the contents of a field with code like this:
<?php echo $row['call_from']; ?>
but what happens if RecordURL contains for example the following string?
<script>alert("I am injecting some code....");</script>
It will happen that some unwanted code will be injected in your page, so it is always better yo use a safe function like htmlspecialchars() every time you need to echo some output:
<?php echo htmlspecialchars($row['call_from'], ENT_QUOTES); ?>
this way, any unwanted code won't be harmful.
I also added a basic TRY/CATCH construct to handle errors.
Hope this helps!
First, we need to get our result.
$vPIN = $_SESSION['PIN']; // or however you get your user's pin from session
$vQuery = "SELECT * FROM conference AS a LEFT JOIN participants as B USING (conference_sid) WHERE a.PIN='$vPIN'";
$oResult = $oDB->execute($vQuery);
$aRows = $oResult->fetchAll(PDO::FETCH_ASSOC);
note the prefixes: $v if for a simple variable, $o represents a ressource (which I like to think of as an object), $a represents an array. It's just for my mental sanity.
so now, we have an array, probably very big, containing every single row in the conference table times every corresponding row in the participants. Sweet, now let's build an array with some meaning in it.
foreach($aRows as $aRow) // maybe a bit confusing but the 's' changes everything: all rows vs one row
{if (!isset($aConferences[$aRow['conference_sid']]['infos']))
{$aConferences[$aRow['conference_sid']]['infos']['date_created'] = $aRow['date_created'];
$aConferences[$aRow['conference_sid']]['infos']['date_completed'] = $aRow['date_completed'];
$aConferences[$aRow['conference_sid']]['infos']['record_url'] = $aRow['RecordURL'];
$aConferences[$aRow['conference_sid']]['infos']['pin'] = $aRow['PIN'];}
$aConferences[$aRow['conference_sid']]['participants'][] = $aRow['call_from'];}
so what happens here is that for each row, if the infos for corresponding conference_sid haven't been set, they will be, and then we create a list from 0 to x of each call_from for that conference. print_r of that array with dummy values:
[1627]['infos']['date_created'] = 2013-11-26
['date_completed'] = 2013-11-29
['record_url'] = 'http://whatever.com'
['PIN'] = 139856742
['participants'][0] = Bob
[1] = gertrude
[2] = Foo
[8542]['infos']['date_created'] = 2013-12-01
['date_completed'] = 2013-12-02
['record_url'] = 'http://whateverelse.com'
['PIN'] = 584217
['participants'][0] = Family Guy
[1] = aragorn
[2] = obama
[3] = Loki
so here is a nice array with which we can build a html table! let's do that
$vHTML = '<table>
<thead>
<th>Date</th>
<th>Duration</th>
<th>Participants</th>
<th>Recording</th>
</thead>
<tbody>';
foreach ($aConferences as $conference_sid => $aConference) // notice the s and no s again
{$vHTML.= '<tr id="' . $conference_sid . '">';
$vDateCreated = $aConference['infos']['date_created'];
$vDateCompleted = $aConference['infos']['date_completed'];
$vHTML.= '<td>' . $vDateCreated . '</td>';
$vHTML.= '<td>' . date('Y-m-d',(strtotime($vDateCompleted) - strtotime($vDateCreated))) . '</td>'; // you might have to debug that date diff for yourself.
$vHTML.= '<td><ul>'; // here a foreach for the participants
foreach ($aConference['participants'] as $call_from)
{$vHTML.= '<li>' . $call_from . '</li>';}
$vHTML.= '</ul></td>';
$vHTML.= '<td>' . $aConference['infos']['record_url'] . '</td>';
$vHTML.= '</tr>';}
$vHTML.= '</tbody></table>';
so here: for each conference create a table row with the infos, then for each participant, add a list item within the list. comment if you wish for any precision.
oh, and don't forget to do something with $vHTML. like echo $vHTML :)

Pulling All Associated Rows MySQLi

I have to pull from a table that's been made by someone else and print it onto a web page. Issue is, that column name are stored in the rows. For instance:
FIELD_NAME| FIELD_VALUE
______________________
first-name| John
last-name | Smith
This is how I'm going about grabbing the data
$tableRow = '';
$sql ="SELECT * FROM `wp_cf7dbplugin_submits` WHERE form_name = '".$nameOfForm."' ";
$result = $mysqli->query($sql);
while($tableData = $result->fetch_assoc()){
$fieldName = $tableData['field_name'];
$fieldValue = $tableData['field_value'];
//FIRST NAME
if($fieldName == 'first-name'){
$firstName = $fieldValue;
}
//LAST NAME
if($fieldName == 'last-name'){
$lastName = $fieldValue;
}
//BUILD A ROW FOR THE TABLE
$tableRow .='
<th>'.$firstName.'</th>
<th>'.$lastName.'</th>
';
}
it only KIND of works when I do $tableRow = instead of $tableRow .=
it will only show me one result, but when I do $tableRow .= it will only show me empty but the correct amount of s.
How can I populate an html table with all of the results pulling from a table like this?
EDIT:
I forgot to mention that the whole table looks like this:
<table id="theTable">
<thead>
<tr>
<th style="width:100px;">First Name</th>
<th style="width:100px;">Last Name</th>
</tr>
</thead>
<tbody id="rowsGoHere">
</tbody>
</table>
and I echo the PHP result via ajax,
//ECHO BACK RESULTS
$JSONData = array("true", $tableRow);
echo $_GET['callback']."(".json_encode($JSONData).")";
and use this to insert into table
var trueEncV = encodeURIComponent("true");
$.getJSON("pullTableData.php?callback=?",
{
trueV: trueEncV
},
function(dataBack){
alert(dataBack);
$('#rowsGoHere').html(dataBack[1]);
}
)
That all works fine and dandy.
According to your updated code the <tr> tags are missing. Also, within <tbody> you should use the <td> tag instead of the <th> tag.
$tableRow .='
<tr>
<td>'.$firstName.'</td>
<td>'.$lastName.'</td>
</tr>
';
Can you try
echo json_encode($JSONData);
instead of
echo $_GET['callback']."(".json_encode($JSONData).")";

Categories