Making a virtual shelf and populating it via a database - php

I'm trying to make a virtual shelf type of thing which is populated via a MySQL database. The column shelfPos holds the position of the item on the shelf. Each row/'shelf' starts with <div class="shelfRow"> and obviously ends with </div> so it's styled and positioned correctly. Items on the shelves can be moved around using the jQuery UI droppable interaction.
The overall layout is this: http://jsfiddle.net/aRA5D/
Each shelf can hold 5 items (left to right).
I'm having trouble populating the shelves. At the moment I've got this: (This is in the place of the HTML)
<?php
$sql="SELECT * FROM shelf WHERE userID='$userID'";
$result=mysql_query($sql);
if (mysql_num_rows($result) == 0) {
// Show a message of some sort? (No items)
}
else {
$tries = 1;
$times = 10; // How many shelves. (10 = 2 shelves)
while(($row = mysql_fetch_array($result)) && ($tries <= $times)) {
while ($tries <= $times) {
if ($tries == $row['shelfPos']) {
echo '<div class="drop" id="drop'.$tries.'"><div class="boxArt" id="'.$row['gameID'].'">'.$row['gameID'].'</div></div>';
}
else {
echo '<div class="drop" id="drop'.$tries.'"></div>';
}
$tries = $tries + 1;
}
$times = $times + 5;
}
}
?>
There's several things wrong with it. It doesn't include the <div class="shelfRow"> html (didn't know how/where to put it, as it needs to be echoed after every 5 'blank' and real items - for loop maybe?) and it requires me to input the number of shelves (2 in this case). Would it be possible to determine how many shelves are required based on the item's position? It's awkward to do because it also needs to echo 'blank' .drop divs before and after them so that the items can be moved around.
Hope this all makes sense. Thanks for the help!

First u need to get data in order of ShelfPos
"SELECT * FROM shelf WHERE userID='$userID' order by shelfPos asc"
And try this code:
...
$i = 0;
while($row = mysql_fetch_array($result)) {
//Each 5
if($i % 5 == 0) echo '<div class="shelfRow">';
if ($i == $row['shelfPos']) {
echo '<div class="drop" id="drop'.$i.'"><div class="boxArt" id="'.$row['gameID'].'">'.$row['gameID'].'</div></div>';
}
else {
echo '<div class="drop" id="drop'.$i.'"></div>';
}
//close shelfrow div
if($i % 5 == 4) echo '</div>';
$i++;
}
//to complete the loop
$shelv_left = 5 - ($i % 5);
if($shelv_left < 5) {
for($j=0; $j < $shelv_left; $j++) {
echo '<div class="drop" id="drop'.($i+$j).'"></div>';
}
echo '</div>'; // end shelfrow div
}
...

Related

PHP getting <div> in between after row count divided by 4

I need to divided all data into 4 columns. i have used this method but its not coming column property
$stmt1 = $db->prepare($sql1);
$stmt5 = $db->prepare($sql1);
$stmt5->execute();
$rowcount = $stmt5->rowCount();
$pages = ceil($rowcount / 4);
$tempcount = 1;
if ($stmt1->execute(array())) {
while ($row = $stmt1->fetch()) {
?>
<?php if ($tempcount == $pages) { ?>
<div class="column">
<div class="ui bulleted list">
<?php } ?>
<?php
if ($tempcount == $pages) {
$pages = $pages + $pages; ?>
</div>
</div>
<?php }
$tempcount++;
}
} ?>
how i can get this columns after getting count of data i have and add those divs in between.
for an Example 20 data rows 20/4 = 5 after each 5 data, i need start and end to be added
<div class="column">
<div class="ui bulleted list">
</div>
</div>
<div class="column">
<div class="ui bulleted list">
</div>
</div>
// And so on
result will be like this
thank you very much
Here's a proper code with comments
$tempcount = 0;
$pages = ceil($rowcount / 4);
while ($row = $stmt1->fetch()) {
// if result of % (Modulo) is zero - you need to start new column
if ($tempcount % $pages == 0) {?>
<div class="column">
<div class="ui bulleted list">
<?php
}?>
ITEM
<?php
// if result of % (Modulo) is (pages - 1) - you need to close previous column
if ($tempcount % $pages == ($pages - 1)) {?>
</div>
</div>
<?php
}
$tempcount++;
}
// check if you have to close previous column
// because it was not closed in a while loop
if (0 < $rowcount) {
if ($tempcount % $pages != 0) {?>
</div>
</div>
<?php
}
}
Whilst the modulo approach mentioned above will help in these situations, I often find that writing your loops from a different perspective can help in sorting out the situation, and making things more readable.
Rather than looping through every row, and then inserting the columns where you think they need to be. Instead loop every item, but in a controlled count, wrapped by the columns.
I've switched the code to using echo just due to personal preference, you can still use php-breakouts instead if preferred.
Please note this is untested example code, just to illustrate the point:
<?php
$stmt1 = $db->prepare($sql1);
$stmt5 = $db->prepare($sql1);
$stmt5->execute();
$rowcount = $stmt5->rowCount();
$pages = ceil($rowcount / 4);
if ($rowcount) {
$stmt1->execute(array());
do {
$group = '';
$group .= '<div class="column">';
$group .= '<div class="ui bulleted list">';
for ( $i=0; $i<$pages; $i++ ) {
$row = $stmt1->fetch(); if ( !$row ) { break; }
// presumably something would be done with $row here
$group .= '';
}
$group .= '</div>';
$group .= '</div>';
echo $group;
} while ( $row );
}
% modulo will help you PHP operators. While you fetch, use it to create your divider. If using div and if needed, I usually add a tiny div with clear: both to make sure it breaks the line after the 4/8/12... results.
$cell++;
$jumpline = ($cell % 4) ? "" : "<div class=\"spacer\"></div><br />";
$endit = ($cell % 4) ? "" : "</div>";

php sidebar and footer inside main

I help develop my school's website what I can not figure out is why on a certain page the sidebar and footer go into the table main. It only does this for two thing custodial and kitchen even when I think the code for say administrators is the same code and looks the same to me.
This is the code used to generate the teachers page
The link below will take you to the broken page since I can't post pictures
http://gwhs.kana.k12.wv.us/academics/display.php?action=teacher&id=103
While the link below will take you to one that actually works
http://gwhs.kana.k12.wv.us/academics/display.php?action=teacher&id=24
If you want the entire file for this code let me know and I will post a link
function dTeacher() {
global $db, $id;
if ($stmt = $db->prepare("SELECT name, department, schedule, education, whyteach, phone, email, image, quote FROM teachers WHERE id = ?"))
{
$stmt->bind_param('i', $id);
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_assoc();
$stmt->close();
$schedule = array();
$schedule = explode(",",$row['schedule']);
$education = explode(",",$row['education']);
$noshow = array(20, 14, 25, 15, 24, 21, 23);
print '<h1>Viewing '.$row['name'].'\'s Profile!</h1>';
if ($row['image']) {
print '<img style="max-width:40%; display: block; margin: 2% auto;" src="'.$row['image'].'" alt="Teacher Image Here">';
}
if (!(in_array($row['department'], $noshow))) {
print '<h3>Schedule</h3>
<table id="maindata">
<tr id="head"><td style="width:30%;">Period</td><td style="width:70%;">Class</td></tr>';
for ($i=0; $i<count($schedule); $i++)
{
$oddeven = ($i%2==0) ? "even" : "odd";
$scnum = $schedule[$i];
$scresult = $db->query("SELECT id, name FROM classes where id = {$scnum} LIMIT 1");
$scrow = $scresult->fetch_assoc();
if ($scnum == 1337) {
$scrow['name'] = "OFF";
} //off periods
print '<tr id="'.$oddeven.'"><td style="width:30%;">'.$i.'</td><td style="width:70%;">'.$scrow['name'].'</td></tr>';
}
}
if ($row['education']) {
print "</table><h3>Education</h3>";
for ($i=0; $i<count($education); $i++)
{
$oddeven = ($i%2==0) ? "even" : "odd";
print '<table id="maindata"><tr id="'.$oddeven.'"><td>'.$education[$i].'</td></tr>';
}
print '</table>';
}
if ($row['phone'] || $row['email']) {
print '
<h3>Contact</h3>
<table id="maindata"><tr id="even"><td style="width:30%;">Phone</td><td>'.$row['phone'].'</td></tr>
<tr id="odd"><td style="width:30%;">Email</td><td>'.$row['email'].'</td></tr></table>';
}
if ($row['whyteach'] != "") {
print '<h3>Why do you teach?</h3>
<table id="maindata"><tr id="even"><td><p>'.$row['whyteach'].'</p></td></tr></table>';
}
if ($row['quote'] != "") {
print '<h3>Favorite Quote</h3>
<table id="maindata"><tr id="even"><td><p>'.$row['quote'].'</p></td></tr></table>';
}
}
else {
print "Error with your request.";
die();
}
}
You have a bug here, you are not closing table tag:
if (!(in_array($row['department'], $noshow))) {
print '<h3>Schedule</h3>
<table id="maindata">
<tr id="head"><td style="width:30%;">Period</td><td style="width:70%;">Class</td></tr>';
for ($i=0; $i<count($schedule); $i++)
{
$oddeven = ($i%2==0) ? "even" : "odd";
$scnum = $schedule[$i];
$scresult = $db->query("SELECT id, name FROM classes where id = {$scnum} LIMIT 1");
$scrow = $scresult->fetch_assoc();
if ($scnum == 1337) {
$scrow['name'] = "OFF";
} //off periods
print '<tr id="'.$oddeven.'"><td style="width:30%;">'.$i.'</td><td style="width:70%;">'.$scrow['name'].'</td></tr>';
}
echo "</table>";
}
Because of this, when the profile has Schedule the table is not closed and the page will display bad.
And closes it here:
if ($row['education']) {
print "<h3>Education</h3>";
With two modifications the web should do its work fine.
Take a look this HTML validator, it will help you:
http://validator.w3.org/check?uri=http%3A%2F%2Fgwhs.kana.k12.wv.us%2Facademics%2Fdisplay.php%3Faction%3Dteacher%26id%3D103&charset=%28detect+automatically%29&doctype=Inline&group=0
Best regards.
First words: You should re-think the layout. Creating multiple tables to display page content is not the best approach and furthermore IDs have to be unique. So for valid HTML you can't have multiple tables with the ID maindata.
As mentioned by cmorrissey in the comments, you're not closing the first table, unless you enter the next if statement. Furthermore this part
if ($row['education']) {
print "</table><h3>Education</h3>";
for ($i=0; $i<count($education); $i++) {
$oddeven = ($i%2==0) ? "even" : "odd";
print '<table id="maindata"><tr id="'.$oddeven.'"><td>'.$education[$i].'</td></tr>';
}
print '</table>';
}
of your code closes the previous <table id="maindata"> but opens a new one in each iteration of the loop. After the loop, your closing just one of them. So if it is correct, that you want to create multiple of these tables, you should close them in the loop as well:
for ($i=0; $i<count($education); $i++) {
$oddeven = ($i%2==0) ? "even" : "odd";
print '<table id="maindata"><tr id="'.$oddeven.'"><td>'.$education[$i].'</td></tr>';
print '</table>';
}

close div tag after 4 entries - mysql loop

i want my script to add a closing div tag after every fourth entrie of the db. i tried something like this:
<div class="row">
$ergebnis = $mysqli->query("SELECT name FROM pages Where city = '1';");
while($zeile = $ergebnis->fetch_array()) {
echo "<div class=\"col-sm-4 col-md-3\">
echo "<h3>".$zeile['name']."</h3>";
..
echo "</div>";
$i=0;
i++;
if ($i == 4){
echo "</div>";}
}
?>
would be great if you can help me here. thx
1) Get names of all cities
2) Initiate an indexing variable
3) Ieterate through the loop
4) Open <div class="row"> when $i==0 (Very First time) OR $i%4==0 (When fifth entry is to be printed). (Remember you are using 0 based indexing i.e. initializing $i=0).
5) Close the div tag for <div class="row"> when fourth city name has been printed i.e. $i%3==0 (Remember you are using 0 based indexing i.e. initializing $i=0).
Here's the code:
<?php
$ergebnis = $mysqli->query("SELECT name FROM pages Where city = '1';");
$i=0;
while($zeile = $ergebnis->fetch_array()) {
if ($i == 0 || $i%4==0){ // <div class="row"> opens on first entry and every fifth entry
echo "<div class=\"row\">";
}
echo "<div class=\"col-sm-4 col-md-3\">";
echo "<h3>".$zeile['name']."</h3>";
/*
Rest of your code
*/
echo "</div>";
$i++;
if ($i % 3 == 0){
echo "</div>"; // <div class="row"> closes here on every fourth entry
}
}
?>
Try this code,
<div class="row">
$ergebnis = $mysqli->query("SELECT name FROM pages Where city = '1';");
$i=0;
while($zeile = $ergebnis->fetch_array()) {
echo "<div class=\"col-sm-4 col-md-3\">
echo "<h3>".$zeile['name']."</h3>";
..
echo "</div>";
$i++;
if ($i == 4){
echo "</div>";
$i = 0;
}
}
?>

Setting the default pagination page (Something to do with the loop?)

I am currently using the plugin WP-CommentNavi for comments pagination but whenever a page is clicked it goes to the highest comments page (oldest comments). My comments are purposely displayed newest first and therefore I need the default pagination page to be 1 whenever a link is clicked.
I notice there is the same default for other pagination plugins too whereby the highest pagination page (ie if there are 5 pages) page 5 is displayed.
At the moment when I load page tellhi####.com/newcastle the page that will be loaded is tellhi####.com/newcastle/comment-page-2/ whereas I want tellhi####.com/newcastle/comment-page-1/ to be loaded
I can't be sure this is the relevant code to what I am trying to achieve but I feel the answer might lie in here (below). If not, please tell me and disregard this code.
### Function: Comment Navigation: Boxed Style Paging
function wp_commentnavi($before = '', $after = '') {
global $wp_query;
$comments_per_page = intval(get_query_var('comments_per_page'));
$paged = intval(get_query_var('cpage'));
$commentnavi_options = get_option('commentnavi_options');
$numcomments = intval($wp_query->comment_count);
$max_page = intval($wp_query->max_num_comment_pages);
if(empty($paged) || $paged == 0) {
$paged = 1;
}
$pages_to_show = intval($commentnavi_options['num_pages']);
$pages_to_show_minus_1 = $pages_to_show-1;
$half_page_start = floor($pages_to_show_minus_1/2);
$half_page_end = ceil($pages_to_show_minus_1/2);
$start_page = $paged - $half_page_start;
if($start_page <= 0) {
$start_page = 1;
}
$end_page = $paged + $half_page_end;
if(($end_page - $start_page) != $pages_to_show_minus_1) {
$end_page = $start_page + $pages_to_show_minus_1;
}
if($end_page > $max_page) {
$start_page = $max_page - $pages_to_show_minus_1;
$end_page = $max_page;
}
if($start_page <= 0) {
$start_page = 1;
}
if($max_page > 1 || intval($commentnavi_options['always_show']) == 1) {
$pages_text = str_replace("%CURRENT_PAGE%", number_format_i18n($paged), $commentnavi_options['pages_text']);
$pages_text = str_replace("%TOTAL_PAGES%", number_format_i18n($max_page), $pages_text);
echo $before.'<div class="wp-commentnavi">'."\n";
switch(intval($commentnavi_options['style'])) {
case 1:
if(!empty($pages_text)) {
echo '<span class="pages">'.$pages_text.'</span>';
}
if ($start_page >= 2 && $pages_to_show < $max_page) {
$first_page_text = str_replace("%TOTAL_PAGES%", number_format_i18n($max_page), $commentnavi_options['first_text']);
echo ''.$first_page_text.'';
if(!empty($commentnavi_options['dotleft_text'])) {
echo '<span class="extend">'.$commentnavi_options['dotleft_text'].'</span>';
}
}
previous_comments_link($commentnavi_options['prev_text']);
for($i = $start_page; $i <= $end_page; $i++) {
if($i == $paged) {
$current_page_text = str_replace("%PAGE_NUMBER%", number_format_i18n($i), $commentnavi_options['current_text']);
echo '<span class="current">'.$current_page_text.'</span>';
} else {
$page_text = str_replace("%PAGE_NUMBER%", number_format_i18n($i), $commentnavi_options['page_text']);
echo ''.$page_text.'';
}
}
next_comments_link($commentnavi_options['next_text'], $max_page);
if ($end_page < $max_page) {
if(!empty($commentnavi_options['dotright_text'])) {
echo '<span class="extend">'.$commentnavi_options['dotright_text'].'</span>';
}
$last_page_text = str_replace("%TOTAL_PAGES%", number_format_i18n($max_page), $commentnavi_options['last_text']);
echo ''.$last_page_text.'';
}
break;
case 2;
echo '<form action="'.admin_url('admin.php?page='.plugin_basename(__FILE__)).'" method="get">'."\n";
echo '<select size="1" onchange="document.location.href = this.options[this.selectedIndex].value;">'."\n";
for($i = 1; $i <= $max_page; $i++) {
$page_num = $i;
if($page_num == 1) {
$page_num = 0;
}
if($i == $paged) {
$current_page_text = str_replace("%PAGE_NUMBER%", number_format_i18n($i), $commentnavi_options['current_text']);
echo '<option value="'.clean_url(get_comments_pagenum_link($page_num)).'" selected="selected" class="current">'.$current_page_text."</option>\n";
} else {
$page_text = str_replace("%PAGE_NUMBER%", number_format_i18n($i), $commentnavi_options['page_text']);
echo '<option value="'.clean_url(get_comments_pagenum_link($page_num)).'">'.$page_text."</option>\n";
}
}
echo "</select>\n";
echo "</form>\n";
break;
}
echo '</div>'.$after."\n";
}
}
In short I need, anytime a page is clicked, for the comments pagination to be on page 1, not the highest page available. Just so you know I have tried the discussion settings on the wordpress dashboard. Nothing on google either!
Failing a full answer, does anyone know the actual php code that determines what pagination page is loaded by default?
I received this response via an e-mail but due to my PHP knowledge am unable to implement it, any ideas? ...
Just reverse the loop. That'll fix it. Here's the relevant part:
http://pastie.org/8166399 You need to go back, i.e. use $i--
Would this change the default start page or just reverse the comments? Hope I have been clear in my question! Will appreciate any response at all.
Thanks in advance, Paul
The option was in Wordpress all along. See picture: http://oi40.tinypic.com/35aj3pt.jpg
If anyone has the answer to the specific code you manipulate, still answer the question here because someone doing this without Wordpress could very well encounter this problem also.

PHP Pagination Link Generation

I have this script below which i found on SO to generate pagination and broadly speaking, its working great, however because its a cut and paste job from me, i don't understand how to actually generate the links which are echoed in the script with the variable $pagination.
What it echos is:
1< a href="index.php?page=2">2< a href="index.php?page=3">3< a hr_ef="?page=2"> Next
None of which are working (clickable) links, and i also want to be able to style them so would rather output them in HTML, rather than a php echo, something like:
<p><?php 1< a href="index.php?page=2">2< a href="index.php?page=3">3< a hr_ef="?page=2"> Next ?> </p>
Below is the script i'm using:
<?php
/* Set current, prev and next page */
$page = (!isset($_GET['page']))? 1 : $_GET['page'];
$prev = ($page - 1);
$next = ($page + 1);
/* Max results per page */
$max_results = 10;
/* Calculate the offset */
$from = (($page * $max_results) - $max_results);
/* Query the db for total results.*/
$result = mysql_query("...");
$total_results = mysql_num_rows($result);
$total_pages = ceil($total_results / $max_results);
$pagination = '';
/* Create a PREV link if there is one */
if($page > 1)
{
$pagination .= '< a href="?page='.$prev.'">Previous</a> ';
}
/* Loop through the total pages */
for($i = 1; $i <= $total_pages; $i++)
{
if(($page) == $i)
{
$pagination .= $i;
}
else
{
$pagination .= '< a href="index.php?page='.$i.'">'.$i.'</a>';
}
}
/* Print NEXT link if there is one */
if($page < $total_pages)
{
$pagination .= '< a hr_ef="?page='.$next.'"> Next</a>';
}
/* Below is how you query the db for ONLY the results for the current page */
$query ="SELECT * FROM ... LIMIT $from, $max_results";
$result=mysql_query($query) or die(mysql_error());
$rsjobinfo=mysql_fetch_assoc($result);
do {?>
<div>
[Individual Row Output]
</div>
<?php } while ($rsjobinfo=mysql_fetch_assoc($result));
echo $pagination;
?>
Can someone help? I imagine its a small fix but as always, would appreciate a kick in the right direction.
Thanks
Dan
Maybe it's just an editing error, but in your output the <a>-tags don't seem to be closed again. Also, there should be no space like < a> at the beginning of the tag. And < a hr_ef= ... is obviously wrong.
In order to style them, you can add a class attribute to the tags while building the string and do the style-stuff in css.

Categories