Drawing a box around results of php - syntax - php

I am trying to create a page of results from a mysql database using php, encasing each line of results (which contains an image and some other lines of detail) in a box.
Currently, page.php gets the data from the db, and uses result.inc to format the data into rows of information three cells per row.
Address1 Picture Comment
Address2 Picture2 Comment2
etc.
I would like to encase each row in pretty box (or even just a box). This produces one empty (but bordered) box before the table, then the table as normal.
How to close off the box with the results inside?
<style>
p {
outline-style: solid;
outline-width: 5px;
}
</style>
for($i=1; $i <= $num_rows; $i++) {
$row = mysql_fetch_array($result);
print("<p>");
print("<TR>");
include("includes/result.inc");
print("</TR>");
print("</p>");
}

You can't just put p-tags between table rows. Instead, style the table rows themselves:
<style>
tr {
outline-style: solid;
outline-width: 5px;
}
</style>
And the php:
for($i=1; $i <= $num_rows; $i++) {
$row = mysql_fetch_array($result);
print("<TR>");
include("includes/result.inc");
print("</TR>");
}

Related

I would like to loop through my table called actors_videos which contains the id's from the actors and videos tables

I would like to loop through my table called actors_videos which contains the id's from the actors and videos tables.
The reason why I want to loop through is because I want to display the actors_name and use it as an anchor text. The actors_id should be included in the url as shown in the echo statement below.
The current code is only displaying one of the actors for the specified video-id which is wrong. I want it to loop through and display all the actors related to the video-id.
I would greatly appreciate any help from the community. I have been struggling to find the solution to this problem.
Regards,
This is the code that I have: loop through the actors_videos table
//get stars
$result4 = $conn->query("SELECT actors_videos_id
FROM actors_videos
WHERE videos_actors_id={$_GET['video-id']}")
or die($mysqli->error);
$stars = $result4->fetch_assoc();
$stars = is_array($stars)? array_values($stars): array();
//loop through stars
for ($i = 0; $i < count($stars);$i++) {
$star = $conn->query("SELECT *
FROM actors
WHERE actors_id = '{$stars[$i]}'")
->fetch_assoc();
$s = count($stars) > 1 ? 's' : '';
echo $i == 0 ? "<p><strong>Actor$s: </strong>" : '';
echo "<a href='actors.php?actors-id=".$star['actors_id'].
"&clean-url=".$star['actors_clean_url'].
"' title='".$star['actors_name'].
"' style='display: inline-block; border: 1px solid #cecece; line-height: 15px; padding: 3px 8px 4px; border-radius: 3px; margin: 2px; box-shadow: 0 0px; text-decoration: none;'>".
$star['actors_name']."</a>";
}
Well fetch_assoc fetches only one table row. So the first call to fetch_assoc will fetch one actor id. You need to use fetch_all. It will fetch ids of all actors.

Importing data from MySQL into array and into table with PHP?

I have a database that contains donor information and then have PHP pages that pull that data and display it under the donor's specific category.
The code I am using is as follows:
// 10,000 DONORS
echo "<p><b>$10,000 cont.</b></p>";
$sql = "SELECT * FROM donor WHERE DonationAmount = 10000 AND Category = '1' or DonationAmount = 10000 AND Category IS NULL ORDER BY LastName ASC LIMIT 10000 OFFSET 6";
$result = mysqli_query($conn, $sql);
$i = 0;
$total_rows = $result->num_rows;
echo "<table><tr>";
if (mysqli_num_rows($result) > 0) {
// output data of each row
while ($row = mysqli_fetch_assoc($result)) {
// test if the DisplayName field is empty or not
echo "<td>";
if (empty($row['DisplayName'])) {
// it's empty!
if (empty($row['FirstName'])) {
echo $row['LastName'];
}
else {
echo $row["LastName"] . ", " . $row["FirstName"];
}
} else {
// Do stuff with the field
echo $row["DisplayName"] . "";
}
echo "</td>";
$i++;
if ($i % 2 == 0 && $i != $total_rows) {
echo "</tr><tr>";
}
}
} else {
} echo "</tr></table>";
My question is as follows: right now the names are inserted into the table in a manner that makes the read left->right->left->right etc. I need them to show up like a normal list works and reads top to bottom, and rolls to the next column when it is told to (counter?). How can I do this?
Here is a preview off the page
EDIT: tried this code:
$sql = "SELECT * FROM donor WHERE DonationAmount = 1000 AND Category = '1' or DonationAmount = 1000 AND Category IS NULL ORDER BY LastName ASC";
$result = mysqli_query($conn, $sql);
$i = 0;
$count = 0;
$total_rows = $result->num_rows;
$halfsize = $total_rows / 2;
$FirstArray = array();
$SecondArray = array();
while ($row = mysqli_fetch_assoc($result)){
while ($count <= $halfsize){
$FirstArray[] = $row['DisplayName'];
//echo "$FirstArray[$count]";
$count++;
}
$SecondArray[] = $row['DisplayName'];
//echo "$SecondArray[$count]";
}
echo "<table>";
for($j=0; $j<count($FirstArray); $j++){
echo "<tr><td>". $FirstArray[$j] . "</td><td>" . $SecondArray[$j] . "</td> </tr>";
}
echo "</table>";
And I just get the same field (the first result) for all of the first column (The First Array?) and then the second column (SecondArray) contains all of the results.
Your issue is not your PHP or your MySQL but your output handling.
So there's an array of data that's being dumped on your HTML and you need to order it to look nice . Two columns reading left to right in a table format.
The <table> tag is perfect for this, and while most people hate the table tag, it is useful for tabled data.
It's worth noting that due to the flexibility and accommodating nature of CSS/HTML that this is not the only correct way but one of many ways this issue can be addressed
Method:
You have a while loop outputting one unit at a time, a unit in this case being a name in a <td></td> block. So that's your unit:
while {
print "unit";
}
So if you have two columns you want to arrange then you need to tell the while loop to distinguish between the first and the second column, this can be done with detecting if the counter (+1 for each itteration) is odd or even.
You can do this with the modulus divisor in PHP:
while {
counter++
if (counter%2) == 1 ){
//odd number.
}
}
So to sum it all up and give you a basic example:
$output = "";
$rowsTotal = mysqli_num_rows($result); //from your original code.
$counter = 0;
while ($row = mysqli_fetch_assoc($result)) {
$counter++; //plus 1 each itteration
if (($counter%2) == 1){
/// is odd so open the row of the table.
$output .= "<tr>";
}
$output .= "<td>";
if (empty($row['DisplayName'])) {
// it's empty!
if (empty($row['FirstName'])) {
$output .= $row['LastName'];
}
else {
$output .= $row["LastName"] . ", " . $row["FirstName"];
}
}
else {
// Do stuff with the field
$output .= $row["DisplayName"] . "";
}
$output .= "</td>";
if (($counter%2) == 0){
// if even so close the row of the table.
$output .= "</tr>";
}
// special case: If there area total of odd number of outputs
if($counter == $rowsTotal && $counter%2 == 1){
// so the last counter value is an odd number so force closure
// of </tr> (or add a blank space)
$output .= "<td> </td></tr>
}
} //end while.
...
print "<table>";
print $output;
print "</table>";
I don't want to dive deep into getting really creative with CSS but you can use CSS to finesse and improve the core HTML output setout above with some wonderful Cascading Style sheets, but above is a very rough outline of the sortof approach you could use to simulate a base level intelligence for the script to output names in the layout you are looking for.
Good luck.
CSS example:
table td {
background-color:#000;
color: #fff;
font-size:1.5rem;
text-align:left;
width:49%; /* 50% sometimes causes overflow, so set a tiny bit smaller */
padding:0.25rem;
margin:0;
box-sizing: border-box;
}
VERSION 2
From comments, OP Needs the results from the SQL query to be two columns, rather than two rows. This means that table (a row structure) is inappropriate for this output and so instead we should use a more customised CSS / div tag set:
The layout would be two columns of approximatly 49% width each, and then each column contains block elements, This blob of blocks will then need to be split in half and a divider added to generate two shorter columns from one long one.
The block elements are output in a foreach loop and once the halfway point is met then an extra HTML code is inserted to break the elements up into a second <div> . this is a little bit hacky it feel to me, but, does the job.
requirements:
A predefined counter of result rows. One can easily be generated. And that the SQL query is already ordered in the intended way, using MySQL ORDER BY.
Semi-Pseudo code:
$array = SQL data result.
$counter = counter of how many array rows are returned.
$divisorCount = ceil($counter /2);
$foreachCount = 1
foreach ($array as $row){
$foreachCount++;
$block[] = "<div class='block'>".$row['data']."</div>\n";
if($foreachCount > $divisorCount){
$foreachCount = 0; //reset, as this will not be true again.
end($block);
$key = key($block); //most recent block array reference.
$block[$key] .= "</div><div class='column'>"; //the insert.
}
}
unset($row,$key,$foreachCount,$divisorCount); //tidyup.
The above generates a bunch of array elements, one for each name. There is an inserted splitter that ends the initial column and starts a second column, finally we wrap the whole block array into a final <div> wrapper.
$output = "<div class='tableContainer'>
<div class='column'>".implode($block)."</div>
</div>";
The above output will be the opener for the first column but the closer for the second column. Within output we now have the complete columns for two columns of all results contained in a Div Container element.
The following CSS classes would need some tweaking to get right but should be a start:
CSS
.block{
line-height: 2rem;
display:block;
padding:0.25rem;
box-sizing:border-box;
}
.column{
width: 49%;
min-width:150px; /* or whatever. */
display:inline-block;
}
.tableContainer{
max-width: 800px; /* or whatever. */
min-width: 300px; /* or whatever. */
width:100%;
margin:auto; //centres it.
}
The CSS would be 49% rather than 50% because box sizes can have a tendancy to overflow on different browsers (Firefox especially), but the $output would finally be:
HTML
<div class='tableContainer'>
<div class='column'><div class='block'>My Name</div>
<div class='block'>Your Name</div>
<div class='block'>His Name</div></div>
<div class='column'><div class='block'>Their Name</div>
<div class='block'>Her Name</div>
<div class='block'>Smacked HorseBombs</div>
</div>
</div>
You could also possibly substitute display:inline-block for float:left, but thats the basics, have a play on jsfiddle to tweak as you need.
I won't use tables for this. There may be some other css tricks. But for the sake of question, I'm answering.
Create two arrays.
Get the size of resultset with mysqli_num_rows, and divide it by two, then walk through this first array and move them until halfsize into array1. And then remainig into array2.
At the end you'll have something like this
Array 1 Array 2
------- -------
[0] Row 1 [0] Row 4
[1] Row 2 [1] Row 5
[2] Row 3
Then walk through it and fill your html table. (with controlling them against being empty)
for($i=0; $i<count($array1); $i++){
echo '<tr><td>'.$array1[$i].'</td><td>'.$array2[$i].'</td></tr>';
}

Dynamic drop down menus using CSS and PHP/MySQL

I want to create a dynamic drop down menu using PHP and MySQL. Menus is OK but not the way I wanted.
I want the menu like this as below (sorted vertically and limiting number of items vertically and horizontally)
I tried achieving this as per below code:
<?php foreach ($result as $riw) { ?>
<div class="four columns">
<li><a href="<?php echo $riw['fmprmlink']; ?>"><?php echo
$riw['remedy_name']; ?></a> </li>
</div>
<?php } ?>
By above approach i am getting this as a result which is not rquired
and without using <div class="four columns"> the result is as below which is again not required
I want items to be arranged and shown alphabetically vertically.
A simple possibility of sorting first, then second, then etc. column.
Can something be improved.
Shows one of many possibilities.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>4 columns</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<?php
function setline($conte,$i,$count,$ILines){
$act1 = $i;
$act2 = 1*$ILines + $i;
$act3 = 2*$ILines + $i;
$act4 = 3*$ILines + $i;
echo "<li>".$conte[$act1]."</li>\n"; // 0
if ($act2 < $count){ echo "<li>".$conte[$act2]."</li>\n";}
if ($act3 < $count){ echo "<li>".$conte[$act3]."</li>\n";}
if ($act4 < $count){ echo "<li>".$conte[$act4]."</li>\n";}
}
//-----------main---------------
echo "<ul id=\"quad\">";
$anArry = array("CSS","XHTML","Semantics","Accessibility","Usability","Web Standards","PHP","Typography","Grids","CSS3","HTML5");
sort($anArry);
$count = count($anArry);
$Idiv = (int)($count/4);
if ($count - ($Idiv * 4)>0) {$ILines = $Idiv+1;} else {$ILines = $Idiv;}
for ($i = 0; $i < $ILines; $i++) {
setline($anArry,$i,$count,$ILines);
}
echo "<ul/>";
?>
</body>
</html>
Next is the normal standard look of a 4 column list.
To get it we changed only the for loop.
Sorted from left to right ( not what OP wants)
for ($i = 0; $i < $count; $i++) {
echo "<li>".$anArry[$i]."</li>\n";
}
Now that we know the matrix ...
1| 0-2 3-5 6-8 9-11
col| 1 2 3 4
---|---------------
r 1| 0 3 6 9
o 2| 1 4 7 10
w 3| 2 5 8 11
... we can write a simpler function.
function sortfor4c($cont,$i,$ILines,&$ICol,&$IRow){
echo "<li>".$cont[$ICol * $ILines - $ILines + $IRow -1]."</li>\n";
$ICol++;
if ($ICol > 4) {
$ICol = 1;
$IRow++;
}
}
....
$ICol = 1;
$IRow = 1;
for ($i = 0; $i < $count; $i++) {
sortfor4c($anArry,$i,$ILines,$ICol,$IRow);
}
style.css
body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6{
margin:0;
padding:0;
}
ol,ul{
list-style:none;
}
body{
font-family:Georgia, "Times New Roman", Times, serif;
color:#333;
}
ul{
width:760px;
margin-bottom:20px;
overflow:hidden;
border-top:1px solid #ccc;
}
li{
line-height:1.5em;
border-bottom:1px solid #ccc;
float:left;
display:inline;
}
#quad li { width:25%; }
Presumably, you would want to use some sort of for loop to order the data appropriately. You could do this with PHP or you could do it with JavaScript.
Either way, you will need to process the entries returned by the server so as to limit the number of rows added to each column. The way you'll process the data depends on how it is returned by the server. If the server sends JSON data representing the data cells in question (and you're using AJAX), you'll likely need to take a javascript approach. If you plan to load all menu field data upon the initial page load, you can probably use PHP to create the menu entries.
This is an example of using a for loop to create a table using PHP. You should be able to do the same thing with either list items and/or divs. If this answer is confusing, there are numerous other examples on both SO and the internet at large.
<?php
echo "<table border='1'><br />";
for ($row = 0; $row < 5; $row ++) {
echo "<tr>";
for ($col = 1; $col <= 4; $col ++) {
echo "<td>", [YOUR MENU ENTRY GOES HERE], "</td>";
}
echo "</tr>";
}
echo "</table>";
?>
The following code uses 2 loops to create a 4 column table from an assoc array. $z is calculated to sort rows in each column in ascending order.
$count = count($result);
$rows= floor($count/5);
for ($x = 0; $x <= $rows; $x++) {
for ($y = 0; $y <= 4; $y++) {
$z=($rows*$y)+$x+$y;
if($z<$count){
$html .="<td>".$result[$z]['fmprmlink']."</td>\n";
}else{
$html .="<td></td>\n";
}
}
$html .="</tr>\n";
}
$html .="</table>";
echo $html;

How can i put pieces of text into a grid-like layout without using tables?

I have a variable amount of 1 word text items being outputted from a mysql database query.
In order to make them presentable and spread in an aesthetic manner in the div, i figured i could put them into a table, this way no matter how many outputs i have, they will be sorted and organized.
I figured i can use php to pop the output into an array, and based on the number of elements in the array i can modify the formatting accordingly using control statements.
However upon doing some research i've heard it's bad to use tables for formatting because i should keep content and layout separate.
Does that really apply in this case? If so, how could i make a desirable layout in a div when i dont know whether there will be 5, 10, or 20 elements?
If your dataset is something like a long list of single words or short phrases (like a list of categories), lists are the most appropriate markup. Using the columns property, you can get something that somewhat resembles a table.
http://jsfiddle.net/b8Vw5/ (shows 3 lists: short, medium, and very long)
ul {
-webkit-columns: 3; /* I think I got all of the prefixes here... */
-moz-columns: 3;
-o-columns: 3;
columns: 3;
padding-left: 0;
}
li {
list-style-type: none;
}
Here is an example of how to put your query into a table.
$mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
if ($mysqli->connect_errno)
{
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
$mysqli->close();
}
$values = $mysqli->query("YOUR SELECT GOES HERE");
$cols = 3;
$i =1;
echo "<table>".PHP_EOL;
echo "<tr>".PHP_EOL;
while($row = $values->fetch_assoc())
{
if (is_int($i / $cols))
{
echo "<td >".PHP_EOL;
//what ever you want to include goes here
echo "</td>".PHP_EOL;
echo "</tr>".PHP_EOL;
echo "<tr>".PHP_EOL;
}
else
{
echo "<td >".PHP_EOL;
//what ever you want to include goes here
echo "</td>".PHP_EOL;
}
$i++;
}
echo "</tr>".PHP_EOL;
echo "</table>".PHP_EOL;
you can set the amount of rows with the $cols variable
When people say "using tables for formatting is bad", they're referring to the ancient technique of using empty table cells with set width/height as "padding", rather than using CSS. There is absolutely nothing wrong with the <table> element.
That said, if yours is a list of words, it would make more sense semantically to place them in a list. To that end, try this CSS:
#mylist {list-style:none}
#mylist>li {
display:inline-block;
width:100px;
white-space:nowrap;
overflow:hidden;
text-overflow:ellipsis;
}
Then have your HTML output be:
<ul id="mylist">
<li>Word</li>
<li>Another</li>
<li>Derp</li>
<li>Blah</li>
<li>UNICORNS!</li>
...
</ul>

How can I create an HTML table layout with rows from a MySQL query?

On my "popular tags" page, I am fetching all of the tags from the database with this PHP & SQL in order from most popular to least popular:
$sql = "SELECT t.tagid, t.name, t.desc, COUNT(qt.id) AS total
FROM tags t
LEFT JOIN question_tags qt ON t.tagid=qt.tag_id
GROUP BY t.tagid, t.name
ORDER BY total DESC";
$result = mysql_query($sql) or die(mysql_error());
while($row=mysql_fetch_assoc($result)) {
echo '<div class="tag-list-box" id="tag-'.$row['tagid'].'">
<a href="/tags/'.strtolower($row['name']).'" class="tag">
<span class="label label-inverse label-tag">'.strtolower($row['name']).'</span>
</a> <strong>× '.$row['total'].'</strong><br />
<p>'.($row['desc']!==null ? $row['desc'] : '<em>This tag has no description.</em>').'</p>
</div>';
}
I don't have it in an HTML table right now because I thought I could do it the more "modern way" with divs and CSS, but as you can see in this screenshot below, the rows get messed up when a tag has a description because the height of the box is greater than the others:
My CSS for the boxes is:
.tag-list-box {
width: 20%;
padding: 5px;
background-color: #f0f0f0;
border: 1px solid #ccc;
float: left;
margin-right: 2%;
margin-bottom: 10px;
}
I am thinking I should put it in a table which should fix the problem but my question is how do I make every 4 rows from the query have their own <tr> so there can be 4 in each table row?
I can't figure it out — I tried doing a count and incrementing it in the while loop but then I just don't know where to go from there.
Use the modulo operator to see if your count is divisible by 4:
if($count % 4 == 0)
If you want to keep your css solution, you can also set a height for your divs and then set overflow to hidden to handle descriptions that are too long.
Yeah I would check to see if you have 4 in a row like Scott said, however. You can use divs. After every 4 just add a div that clears the left float. I would NOT use a set height because you never know how tall the items will get. Example of what I would do:
$count = 0;
while($row=mysql_fetch_assoc($result)) {
echo '...'; //YOUR CURRENT ECHO STATEMENT HERE
$count++;
if($count % 4 == 0) echo "<div style='clear: left;'></div>";
}

Categories