Does anyone know how to bring in all of a mysql tables' results, only show the first X, (say 10), and then hide the rest using jquery? Basically, as I've already got the jquery, I just need to know how to show only the first X results in one div, then the rest in a seperate div.
My aim is to only show the first 10 results, but provide a link at the bottom of the page allowing the user to show all of the results. Was thinking the hyperlink could just re-execute the query but thought it would be easier to show/hide using jquery.
Many thanks in advance. S
Thought I'd add the code I'm using below
$query = "SELECT * FROM ispress WHERE active = '1' ORDER BY YEAR(date) DESC, MONTH(date) DESC LIMIT 0, 7";
$resultSet = mysql_query($query);
if (mysql_num_rows($resultSet))
{
$newsArray = array();
while ($newsResult = mysql_fetch_array($resultSet))
{
$newDate = $newsResult['date'] ;
$timePeriod = date('F Y ',strtotime($newDate));
$bFirstTime = true;
if (!isset($newsArray[$timePeriod]))
{
$newsArray[$timePeriod] = array();
}
$newsArray[$timePeriod][] = $newsResult;
}
foreach ($newsArray as $timePeriod => $newsItems)
{
echo '<div class="date">' . $timePeriod . '</div>' . PHP_EOL;
echo '<ul class="press">' . PHP_EOL;
foreach ($newsItems as $item)
{
if ($bFirstTime) {
echo '<li>';
echo '<img src="'.$wwwUrl.'images/news/'.$item['image'].'" width="'.$item['imgWidth'].'" height="'.$item['imgHeight'].'" title="'.$item['title'].'" alt="'.$item['title'].'" />
<h3>'.$item["title"].'</h3>
<p>'.substr($item['descrip'],0,244).'...</p>
<p>Read more</p>
';
echo '</li>' . PHP_EOL;
$bFirstTime = false;
} else {
echo '<li>';
echo '<img src="'.$wwwUrl.'images/news/'.$item['image'].'" width="'.$item['tnWidth'].'" height="'.$item['tnHeight'].'" title="'.$item['title'].'" alt="'.$item['title'].'" />
<h3>'.$item["title"].'</h3>
<p>'.substr($item['descrip'],0,100).'...</p>
<p>Read more</p>
';
echo '<div class="clear"></div>' . PHP_EOL;
echo '</li>' . PHP_EOL;
}
}
echo '</ul>' . PHP_EOL;
}
echo '<p>Older posts...</p>'. PHP_EOL;
echo '<div id="slickbox">This is the box that will be shown and display the rest of the news results. :)</div>'. PHP_EOL;
}
else
{
echo 'We currently have no press releases available';
}
This will hide the first 10 children. How are you planning on showing the other results? Buttons, fields, jqueryui widgets?
You will just need to add a click event which calls this function.
function limit_results(start, end) {
$('#things > .thing').each(index) {
if(index < end && index >= start) {
$(this).hide();
}
}
}
limit_results(1,10);
If you have your elements in a jQuery object already (say, $('#sql-results') holds all of your results), you can always do this: $('#sql-results:lt(10)') to work with the first ten elements, and $('#sql-results:gt(9)') to work with the rest of the elements.
You have to decide yourself how efficient your approach is for this amount of data you're processing.
Right, so for your specific markup structure, you can add this to your JS:
// Obviously this is untested and probably not bug-/typo-free
(
function($) {
var $slickbox = $('#slickbox').hide();
$('<ul></ul>')
.appendTo($slickbox)
.append('ul.press li:gt(9)');
$('#slick-toggle')
.bind(
'click',
function(){
$slickbox.toggle();
}
);
}
)(jQuery);
This would involve a lot of rewriting but jquery has a datatables plugin that will display the data. To use it you need to do something like
echo '<table id="news-table">'
echo '<thead>';//Datatables needs a thead with the correct number of columns. However you don't need to fill them in.
echo '<th>Date</th>';
echo '<th>Time Period</th>'
echo '</thead><tbody>';
while ($data = my_sql_fetch_array($result)) {
echo '<td>Whatever</td>';
echo '<td>Another Field</td>';
}
echo '</tbody></table>';
The jquery is then
$('#news-table').dataTable();
I'm not sure how it would do custom no data messages and I know that with the code you have written this may not be any good to you right now but I'm posting it because it could be useful for somebody looking for pagination info or for you if you want to do something similar again. Datatables is also useful because the user can choose the number of results they want to show, what column they want to sort by and what direction to sort in.
in your query
limit 0,10
for the rest
limit 11,xxx
When you print out each row's data count each iteration by incrementing a counter. When you get to 11 start a new div that has a different id to that of your 1st div that you already defined an id for. Now using jQuery you can hide and show the 2nd div with the remaining results as you please.
Divide the return values in your php file with a character
ex:
echo "this is first value +";
echo "this is second value +";
echo "this is third value +";
use javascript to separate the return values
ex:
var ajaxArray = ajaxValues.split("+");
now all three values are placed in ajaxArray and you may use anyone you want
ex:
ajaxArray[0] = this is first value
Related
)
I have a question:
I have a databse with the following information:
Name of report [name]
Link to report [link]
The various reports are displayed in tables in my page (using db_tables filed with static, month, week etc)
But i want to generate a link to the report based on "link" and "name"
so i set up a pgsql query :
result = select name, link from db where type = 'week'
This works fine.
To display the above i have:
echo "<div id=\"selMaand\">" ;
echo "<table id = \"t2\">\n ";
echo "\t<tr class=\"head\">\n";
echo "<th colspan=\"2\">Select Maand</th>";
while ($line = pg_fetch_array($result5, null, PGSQL_ASSOC)) {
echo "\t<tr>\n";
foreach ($line as $col_value) {
echo "\t\t<td width=\"100%\">$col_value</td>\n";
}
echo "\t</tr>\n";
}
echo "</table>\n";
echo "</div>";
which works fine to.
Now, the link from database is http://192.168.178.1:8080/etc/etc/page.html"onclick humptydumpty>name
each time i want to adjust something in either the onlclick or address, i have to change all my links.
What can i insert in my querys so i will be able to build a link like;
echo "<a href = "http://192.168.178.1:8080/etc/etc/**$link**"onlclick humptydumpyu>**$name**</a>
I cant figure out how to break down my array!
Thanks in advance
Sjoerd
If you just need a portion of your URL in the database (i.e. only a portion of it would change for each record), then only store that portion of the URL in the database. You can then generate the remaining portion of the URL (call it the URL base) in your code.
So something like this:
define('URL_BASE', 'http://some.url.base/that/you/can/change/globally/');
Then you get the remaining piece of the URL from the database for each item. So you would have something like this inside your query loop to build the full URL.
$link = $line['link'];
$final_url = URL_BASE . $link;
As far as the onclick stuff goes, I would have that set sepearately as well, since I assume the onclick behavior is not dependent on the individual link (if it is you can make a separate DB column for it).
define('LINK_ONCLICK', 'onclick="some_onclick_function()"');
And in your query loop you can put this together like this:
$name = $line['name'];
$link = $line['link'];
$final_url = URL_BASE . $link;
echo '<a href="' . $final_url . '" ' . LINK_ONCLICK . '>' . $name . '</a>';
Note that it is not really necessary to define the strings for the url base and onclick behavior as constants. I just showed it this way as it is common practice to set globally defined values that do not need to change at run-time ion such a manner.
i am doing one website project using php.my result are displayed like this
Detected Result
1. CLEAN MX 0 clean site
2. MalwarePatrol 0 unrated site
3. ZDB Zeus 0 suspicious site
4. K7AntiVirus 0 clean site
i am using this php code to get this result that is
$none = 0; $i = 0; foreach($result->scans as $key => $val) {
if($i==0) {
echo '<th></th>';
echo '<th></th>';
echo '<th>Detected</th>';
echo '<th>Result</th>';
}
echo '<tr>';
echo '<td>'.intval($i+1).'.</td>';
echo '<td>'.$key.'</td>';
if(empty($val->detected)):
echo '<td>'. $none .'</td>';
else:
echo '<td>'. $val->detected .'</td>';
endif;
echo '<td>'.$val->result.'</td>';
echo '</tr>';
$i++; }
but i need to add some graphics into the result page. firstly check the result is clean site or unrated site,suspicious site.then if that site is a clean site display green light image, if that site is unrated site display yellow light,if it is suspicious site display red light image.
like a www.onlinelinkscan.com's result.
finaly if that site gets most number of green light images display overall result is good,if that site gets most number of red light images display overall result is danger else display overall result is neutral.like this
Detected Result
1. CLEAN MX 0 clean site
2. MalwarePatrol 0 clean site
3. ZDB Zeus 0 clean site
overall result:good
overall result:danger
overall result:neutral
please help me friends i do not have such kind of knowledge in php and javascript.
No fancy php or javascript needed. For styling something it is css you need. Definitly not add imgas they are content, and an icon to anacify your table would not be considered content.
I would just add a class to each row to indicate the result. Also I would keep a score to indicate the global result:
outside your foreach, prepare the score var
$score = 0;
inside the foreach:
// determine which class to add
switch $val->result {
case 'clean site':
$class = "clean";
$score++;
break;
case "unrated site":
$class = 'neutral';
break;
case "suspicious site":
$class = 'dirty';
$score--;
break;
default:
// perhaps you should throw an esception here
$class = '';
break;
}
// add it to your row
$out .= '<tr class="' . $class .'">';
Also note that I do not echo anything yet, I store it in a variable. You would have to do that with each echo in your code. An d make sure you do not add the opening <table> tag yet, as we are going to add the 'global score class' here.
After the foreach loop has finished, you would have a global score. You could add this as a class to your table, and prepend it to your prepared output like so:
if ($score < 0) {
$tableClass = 'dirty';
}
if ($score > 0) {
$tableClass = 'clean';
}
if ($score == 0) {
$tableClass = 'neutral';
}
$out = '<table class="' . $tableClass .'">' . $out;
All you need to do now is echo the $out variable.
To apply the colors or icons or whatever you could add some simple css like this:
table.neutral {
border-color: grey;
}
table.clean {
border-color: green;
}
...
tr.clean td:first-child{
background-image: url(icon-clean.png) no-repeat left center;
padding-left: 20px;
}
...
This is simple...
First check your value, and assign an image to variable...
if($val->result=="clean site"){$image = "green-light.png";}
elseif($val->result=="unrated site"){$image = "orange-light.png";}
elseif($val->result=="suspicious site"){$image = "red-light.png";}
Then echo that image inside the table.
echo "<td><img src='images/".$image."'></td>";
This means you have to create 3 images with the names as above.
And put them in your images folder
As for the other part of your question....it will involve counting the elements either with PHP, or better with SQL....but Im not gonna do that part for you.
Heres fuller code...
if(empty($val->detected)):
echo '<td>'. $none .'</td>';
else:
echo '<td>'. $val->detected .'</td>';
endif;
if($val->result=="clean site"){$image = "green-light.png";}
elseif($val->result=="unrated site"){$image = "orange-light.png";}
elseif($val->result=="suspicious site"){$image = "red-light.png";}
echo "<td><img src='images/".$image."'></td>";
I have a list that's being populated from the database it's sorted using the time field by ASC dates. I'm using the <?php foreach() :?> to loop through and populate the list .
<li id="events">
Time: <?php echo $venue['time']; ?>
Event: <?php echo $venue['location']; ?>
</li>
I have a variable in php called ($time_left ) that keeps track of the days left till each event begins I calculate this by taking the time field from the database subtracting today's current date with php date() when this reaches 0 how can I remove the expired event from the start of the list and append it to the end.
This can be done on page refresh I don't need it to be asynchronous. Can I do this just in PHP with DOM manipulation? or should I use Jquery and if so how do I pass the $time_left variable from PHP to my Jquery script?
this looks simple enough. I hope i didn't misunderstand something. it should be something like this.
foreach($venues as $k => $venue) {
$passEvents = array();
$currentTime = time();
if(($venue['time'] - $currentTime) <= 0) {
$passEvents[] = $venue;
} else {
echo '<li id="events">';
echo 'Time: '.$venue['time'];
echo 'Event: '.$venue['location'];
echo '</li>';
}
}
foreach($passEvents as $k => $venue) {
echo '<li id="events">';
echo 'Time: '.$venue['time'];
echo 'Event: '.$venue['location'];
echo '</li>';
}
I'm using the following code to allow an administrator to resort a list. Then I want to update my db with this new sort order.
<div id="item_list">
<ul id="sortable">
<?php
$i=1;
foreach ($row_Item as $row){
echo ("<li><span></span><table><tr><td class=\"input_td\">" . $row['item_name'] . "</td><td class=\"input_td_right\">" . $row['program_sort'] . "</td><td class=\"input_td_right\">$" . number_format($row['prog_earnings'],0,".",",") . "</td><td class=\"input_td_right\">" . $i . "</td></tr></table></li>");
$i=$i+1;
}
?>
</ul>
</div>
The items are intitially ordered by the $row['program_sort'] value which is calculated by a subroutine. This list then needs to be tweaked by the administrator by moving a few items around in list order.
I don't understand how to use the jQuery seralize method to extract the new order as it relates to the $row['item_name'] in each li. Do I have to use ids for each li, maybe equal to the $row['item_name']? What I need is something like item_name1 =>5, item_name2=>2, item_name3=>4 if the user resorts the list to those positons. Then I can update the db with the new sort order.
I always seem to need a little help when using something new to me in jQuery. Could someone please give me a little help?
Thanks
jQuery serialize() needs form elements, but I can't see any in your code. You can use an own script to create the sort order object, e.g.:
function getSortOrder() {
var oList = {};
$('#item_list li').each(function(iIndex, oElement) {
oList[$(oElement).find('td:first').text()] = iIndex + 1;
});
return oList;
}
Also see this example.
So what I'm trying to do is select all the distinct months from my database and then print them in a list. That, I can accomplish. The problem lies in the fact that I need my list to be two column. The way that I achieve this with CSS is by using 2 different div's "left" and "right" which are floated next to each other. This poses a problem with PHP because it needs to echo a div close and a new div open after it echoes the sixth month. Then it needs to start again from where it left off and finish. I can't just list all of the months in the HTML, either because I don't want it to list a month if I don't have any records in the DB for that month, yet. Any ideas? I hope I was clear enough!
Thanks!
-williamg
Something like this should work (the basic idea being to just keep a count of the months an increment it as you loop through them):
<div class="left">
<?php
$x = 1;
foreach($months as $month) {
# switch to the right div on the 7th month
if ($x == 7) {
echo '</div><div class="right">';
}
echo "<div class=\"row\">{$month}</div>";
# increment x for each row
$x++;
}
</div>
<?php
$numberOfMonths = count($months);
$halfwayPoint = ceil($numberOfMonths / 2);
echo "<div class=\"left\">";
for($i=0; $i<$halfwayPoint; $i++){
echo $months[$i] . "<br />";
}
echo "</div><div class=\"right\">";
for($i=$halfwayPoint; $i<$numberOfMonths; $i++){
echo $months[$i] . "<br />";
}
echo "</div>";
?>
Rant: on
When displaying tabular data, use table instead of floating div. It will make sense when viewing the page with css disabled. If you use floated div, then you data will displayed all way down. Not all table usage is bad. People often hate table so much, so using floated div. Table only bad when used for page layout.
Rant: off
When I need to have certain content displayed with some open, close, and in-between extra character, I will make use of implode. This is the example:
$data = array('column 1', 'column 2');
$output = '<div>'.implode('</div><div>', $data).'</div>';
//result: <div>column 1</div><div>column 2</div>
You can extends this to almost anything. Array and implode is the power that php have for many years. You will never needed any if to check if it last element, then insert the closing character, or check if it first element, then insert opening character, or print the additional character between elements.
Hope this help.
Update:
My bad for misread the main problems asked. Sorry for the rant ;)
Here is my code to make a data displayed in 2 column:
//for example, I use array. This should be a result from database
$data = array(1, 2, 3, 4, 5, 6, 7, 8, 9);
//should be 12 month, but this case there are only 9 of it
for ( $i = 0; $i <= 5; $i++)
{
//here I do a half loop, since there a fixed number of data and the item for first column
$output = '<div class="left">'.$data[$i].'</div>';
if ( isset($data[$i+6] )
{
$output = '<div class="right">'.$data[$i+6].'</div>';
}
echo $output."\n";
}
//the result should be
//<div class="left">1</div><div class="right">7</div>
//<div class="left">2</div><div class="right">8</div>
//<div class="left">3</div><div class="right">9</div>
//<div class="left">4</div>
//<div class="left">5</div>
//<div class="left">6</div>
Other solution is using CSS to format the output, so you just put the div top to down, then the css make the parent container only fit the 6 item vertically, and put the rest to the right of existing content. I don't know much about it, since it usually provided by fellow css designer or my client.
Example assumes you have an array of objects.
<div style="width:150px; float:left;">
<ul>
<?php
$c = count($categories);
$s = ($c / 3); // change 3 to the number of columns you want to have.
$i=1;
foreach($categories as $category)
{
echo '<li>' . $category->CategoryLabel . '</a></li>';
if($i != 0 && $i % $s == 0)
{
?>
</ul>
</div>
<div style="width:150px; float:left;">
<ul>
<?php
}
$i++;
}
?>
</ul>
</div>