Label each row of an HTML table numerically (PHP + MYSQL) - php

All I want is for the first column of each row in my table to display the number of the current row. For example, please see the following table.
Column Header 1 Column Header 2
1 some data
2 more data
3 some more data
4 even more data
I am familiar with JavaScript (I will most likely understand any JS script posted), CSS, and HTML. I am curious as to whether or not I will have to write a JS function to do this, or if I can somehow just create a variable and increase its index by ' 1 ' each time.
I look forward to your responses!

If you're using PHP, try to get an array of strings for data you want to output:
$data = array('here', 'is', 'some', 'data');
// Avoid printing table if there is no data
if (count($data) > 0) {
echo '<table><tr><td>Column Header 1</td><td>Column Header 2</td></tr>';
for ($i = 0; $i < count($data); $i++) {
echo '<tr><td>', $i + 1, '</td><td>', $data[$i], '</td></tr>';
}
echo '</table>';
}

Try CSS autonumbering
http://www.w3.org/TR/CSS2/generate.html#counters
This is the client side solution. Use it if you can not do it on server side.

Does it have to be a table, or could you use an ol?
<ol>
<li>some data</li>
<li>more data</li>
<li>some more data</li>
<li>even more data</li>
</ol>

Based on kisp's approach of CSS numbering, I created a prototype which appears to do almost what you are looking for. The numbering isn't in a separate collumn, it's in the "before" pseudo-element.

Related

PHP - Looping A-Z To Sort Mysql Results using Dynamic Links

I have the following table in mysql:-
id | bandname
1 | a perfect circle
2 | aerosmith
3 | b.b king
4 | cat stevens
I am fetching all of the results in a single query with:-
$result = mysql_query("SELECT id, bandname FROM bands ORDER BY bandname ASC");
On my page I have A-Z anchor links which bring up a new tab:-
<ul class="tabs-nav">
<li class="active">0-9</li>
<?php
// Print a-z link
for ($i=97; $i<=122; $i++) {
$curletter = chr($i);
echo '<li>'.$curletter.'</li>';
}
?>
</ul>
I'm having trouble getting the bands listed under their tab. Currently my code is:-
<div class="tabs-container">
<?php
// Print a-z tabs
for ($i=97; $i<=122; $i++) {
$curletter = chr($i);
?>
<div class="tab-content" id="<?php echo $curletter; ?>">
<?php
while($bands = mysql_fetch_array( $result )) {
$bandname = $bands['bandname'];
$bandid = $bands['id'];
$bandletter = strtolower(substr($bandname , 0 , 1));
}
if($curletter==$bandletter) {
echo '<a href="'.$bandid.'/" title="'.$bandname.'>'.$bandname.'</a>';
}
?>
</div>
<?php } ?>
</div>
I know this is incorrect because I'm calling the while loop inside the for loop and that just doesn't seem right to me - as every iteration of the A-Z tab creation process will have to run through the while loop.
If I will be dealing with say 5,000 bands what is the best approach for this? One sql result looped multiple times, one result with each band then held in an alphabetical array, or an ajax sql query whenever a user clicks on one of the anchor links?
None of this even starts to deal with the 0-9 tab which I think will be an issue itself given my current code. Any pointers really would be appreciated.
I have searched for an answer but not found something similiar to my question :)
Though I wouldn't recommend the method you've used at all, if you want to keep it as simple as you have then you need to extract all of the band names using the while before you enter the name looping foreach by putting them into a temporary array, or better still before any output takes place. This will allow you to use foreach() on this array instead of the while. You could also sort these into arrays by letter too, making it simpler to see which letters have bands that start with it
Some extra tips:
Use range() instead of the for($i = ... ) and chr() for the letters listings
Give your href values more than just the letter as the id (aesthetic but certainly better) such as letter-a letter-b and so on
If you're using 5000+ records you should be serving these on separate pages in my opinion with pagination rather than on one large page of bands
If these are not going to change very often, you'd be best using a caching system of some sort to keep database querying to a minimum
If you use the array by letter method I've given above, you can use the count() function to add the band number counts to the letter listings (and even hiding letters you have no bands for)

Relating PHP to source files

Sorry if the title is a bit vague, couldn't think of a better way to phrase it, anyway.
I'm attempting to make a page system for a website. Where you predictably start on page one, and then click page two and a different set of images appear. Each page has 12 images which are all thumbnail images. You click on the thumbnail image and lightbox brings up the high res shot.
My current problem is that I cannot link the PHP script to the images correctly. To me it looks correct but it doesn't work, so clearly not.
Info:
Thumbnails are name "thumb1.jpg" from 1-24, full images are name "img1.jpg" from 1-24
<?php
$imgs = array(12, 12, );
if(!empty($_GET["page"]))
{
$currPage = $_GET["page"];
}
else
{
$currPage = 1;
}
for($i = 1; $i<$imgs[$currPage-1]+1;$i++)
{
echo "<a href='albums/norfolk weekender 2012/img'.$imgs[$currPage][$i].'.jpg' rel='lightbox[group]'><img src='albums/norfolk weekender 2012/thumb'.$imgs[$currPage][$i].'.jpg'/></a>";
}
?>
.
Anyway, I'm unsure why it doesn't work, and any help will be much appreciated.
Ta.
John.
'.$imgs[$currPage][$i].'
It looks like you should be using " instead of ' to wrap round this embedded variable both times you reference it in the code, since your echo is distinguished by ".
Either way, looking at this it doesn't seem this array structure you've got going on is working.
"albums/norfolk weekender 2012/img".$imgs[$currPage][$i].".jpg"
Have you not considered something like this (care, it's rough); with $pageNo representing $_GET["page"]
for ( $i = ($pageNo - 1) * 12 + 1; $i <= ($pageNo * 12); $i++ )
{
echo "<a href='albums/norfolk weekender 2012/img".$i.".jpg' rel='lightbox[group]'><img src='albums/norfolk weekender 2012/thumb".$i.".jpg'/></a>";
}
If presentation (i.e. checking to see if an image exists before displaying it) is a major concern, you could use file_exists( filename ). By creating an Array like this...
$imgs = array(12, 12, );
...you are simply creating an array containing two elements of 12 (and possibly a blank element, I'm not entirely sure.) I think where you went wrong is you attempted to declare the size in the "constructor" of Array; in PHP this is not the case.

Dynamically increase height of a div as many times a loop runs in PHP

I have a PHP multidimensional array which will store information depending on parameters input.
Now as many times the loop runs, I want it the background div height to increase. The structure of HTML layout is as below:
for($i=0; $i < count($array); $i++)
{
<div id='outer div'> --------------------------background color rounded corner
for($j = 0; $j< $array[$i]; $i++)
{
<div id='inner div'>
contents
</div>
}
</div>
}
Please advice.
I know I should use javascript code like $("#outer div").height(), but how to pass this value to javascript?
Thanks a lot...
Mark and Krister,
Thanks for helping me out and telling me that I can use the inline way to set height. However your code had problem.
Instead of: height = $array[$i] * 10; This worked: height = count($array[$i]) * 10; // remember it was array of arrays (Multidimensional array).
You could use inline css like this:
<div id='outer div' style="height:<?php echo $i*10; ?>px;">
There's no reason to use such a complex solution, just give the div no height and it will expand dynamically. You also need to look a templating solution instead of hardcoding HTML in your code.

Split Data into 3 columns

I have a MySQL table that contains people's names.
Using PHP, what's the best way of dividing these names up and displaying them in 3 columns.
This could be achieved using an HTML table, but would it be possible to do this using only <div>'s?
I heard that this can be done using the % operator. Would this be the best way, and how would this be done?
You could do this using the modulus operator, however it's actually possible with just CSS.
Using display: inline-block, you can get a good column effect. Take a look at this JSFiddle here. I'm only using JavaScript because I'm lazy; the <div> list would be generated by PHP in your case. If you want to confine them to a certain width, just put them in a container <div> with a fixed width.
I've come up with a solution using tables, which is really what you should be doing (you haven't given any special use cases). The code is below, as well as a working demo here.
$columns = 4; // The number of columns you want.
echo "<table>"; // Open the table
// Main printing loop. change `30` to however many pieces of data you have
for($i = 0; $i < 30; $i++)
{
// If we've reached the end of a row, close it and start another
if(!($i % $columns))
{
if($i > 0)
{
echo "</tr>"; // Close the row above this if it's not the first row
}
echo "<tr>"; // Start a new row
}
echo "<td>Cell</td>"; // Add a cell and your content
}
// Close the last row, and the table
echo "</tr>
</table>";
And to finish off, we have our column-centric layout, this time going back to divs. There's some CSS here; this should be put in a separate file, not left inline.
<?php
$rows = 10; // The number of columns you want.
$numItems = 30; // Number of rows in each column
// Open the first div. PLEASE put the CSS in a .css file; inline used for brevity
echo "<div style=\"width: 150px; display: inline-block\">";
// Main printing loop.
for($i = 0; $i < $numItems; $i++)
{
// If we've reached our last row, move over to a new div
if(!($i % $rows) && $i > 0)
{
echo "</div><div style=\"width: 150px; display: inline-block\">";
}
echo "<div>Cell $i</div>"; // Add a cell and your content
}
// Close the last div
echo "</div>";
?>

Can (should) I use PHP to alter HTML page before serving, based on class attribute values

I'd like an easy way for content contributors with limited coding experience to designate the expiration date for selected content on existing HTML (PHP) pages on our site. I'd prefer to remove the content server-side so it isn't still available in the source code.
Illustration of a potential solution I am mulling over:
<div class="story"> ... </div>
Let's say I'd like the above div and its contents to disappear starting on June 1, 2011. So I would add a value to the class attribute:
<div class="story disappears-20110601"> ... </div>
Then I would have to write some code (xpath?) to locate all elements that have a class value with a pattern like ="... disapears-YYYYMMDD". If the date reference is valid, and that date is today or earlier, the code would remove the entire div and its contents from the DOM, and then serve the page without the expired div.
Before I try to set this up, what do you think of the concept? Is it feasible? If implemented sitewide, would it be a horrible resource hog?
A much better way is to store the content in a database table and assign the expiration date via a DATETIME field. Using a css class for this is a little square-peg.
Here is code for you:
<?php
$content = <<<EOF
<div>
some text 1
<div class="story disappears-20110101"> 20110101 </div>
<div class="story disappears-20110601"> 20110601 </div>
some text 2
</div>
EOF;
$doc = new DOMDocument();
$doc->loadHTML($content);
$xpath = new DOMXPath($doc);
$expired = $xpath->query('//*[contains(#class, \'disappears-\')]');
$remove = array();
foreach ($expired as $n)
if (preg_match('~disappears-(\d{4})(\d{2})(\d{2})~', $n->getAttribute('class'), $m))
if (time() > mktime(0, 0, 0, $m[2], $m[3], $m[1]))
$remove[] = $n;
foreach ($remove as $n)
$n->parentNode->removeChild($n);
echo $doc->saveHTML();
Have a nice day.
Well, you could do that using Regexp, but I assume it /could/ (doesn't meant it will) get a little bit messy. I suggest using a database if you have access to one, if not store the stories into separate files (in one directory) and then load/delete/edit them via file-name.
Doing that through HTML would be unpleasant, in my opinion.
EDIT:
<?php
$html_content = file_get_contents('...');
preg_match('/class="story disappears-(\d*)"/i', $html_content, $match_array)
foreach($match_array as $val) {
if (intval($val) < intval(date('Ymd'))) {
$new_html_content = preg_replace('/(<div class="story disappears-'. $val .'">.*<\/div>)/', '', $html_content);
echo $new_html_content;
}
}
?>
Just a side note, you should try debugging this first, I might've done some mistake since I didn't use php in a while. However, if you stumble upon any errors, let me know in the comments, so I can update the code.
I mean there has to be a database available. Even if the pages are hand-coded, you can have them upload each page to your server, and have the back-end create a database entry that correlates to the uploaded page. this database entry could store info about the uploaded page such as the expire date. This also makes it easier organize/serve the page.
This XPath 1.0 will select the desired elements:
//*[
20110601
>=
substring-before(
substring-after(
concat(
' ',
normalize-space(#class),
' '
),
' disappears-'
),
' '
)
]

Categories