I'm working on a website and am pulling category names from a db table (category_names). I then display them on the website using php on to an html unordered list. I want to limit the number of category_names and then using jquery(or anything else but I prefer jQuery) retrieve more category_names and add a less button to go back.
I hope I made this question easy to understand, and thank you for any help!
Basically use AJAX to pull in more. Start off by loading in a few by using LIMIT.
<ul id="categories">
<?php
$res = mysql_query('SELECT * FROM `category_names` LIMIT 10'); // change limit to suit
while ($row = mysql_fetch_array($res)) {
echo '<li>'.$row['name'].'</li>'; // or whatever your field is called
}
?>
</ul>
<span id="loadmore" num_loaded="10">Load More</span>
Then use the following jQuery to load more:
$('#loadmore').click(function() {
var loaded = $(this).attr('num_loaded');
$.ajax({
url:'load_categories.php',
type:'get',
data:{'from':loaded,'to':loaded+10},
success: function (res) {
var categories = $.parseJSON(res);
categories.each(function() {
$('#categories').append('<ul>'+this+'</ul>');
});
$('#loadmore').attr('num_loaded',loaded+10);
}
});
});
Finally you'll need to create the PHP page that the AJAX calls - load_categories.php
<?php
if (!isset($_GET['from'])) exit;
if (!isset($_GET['to'])) exit;
$from = $_GET['from'];
$to = $_GET['to'];
$diff = $from-$to;
// connect / select db
$res = mysql_query('SELECT * FROM `category_names` LIMIT '.$from-1.','.$to.';');
$arr = array();
while ($row = mysql_fetch_array($res)) {
array_push($arr,$row['name']);
}
echo json_encode($arr);
?>
There are a number of different approaches that work better or worse depending upon your needs.
Approach 1 (simpler, less efficient, scales poorly): execute the full query, and store all of the results on the DOM, just hiding them using jQuery (jQuery expander is a simple plugin you may want to try out, though I have found it limiting in customization).
Approach 2 (more complicated, but more efficient/scalable, also faster): Use MySQL limit, you can actually send a second mysql request on click, however, you would want to make sure this is asynchronous so as to not delay the user's interactions.
http://php.about.com/od/mysqlcommands/g/Limit_sql.htm
This is similar to: PHP/MySQL Show first X results, hide the rest
Or you could do something simpler:
$get = mysqli_queury ($link, "SELECT * FROM db_name WHERE blank='blank' LIMIT 5"
if (isset($_POST['button']; {
$get = mysqli_query ($link, "SELECT * FROM db_name WHERE blank='blank' LIMIT 10"
}
?>
<form action="showmore.php" method="POSt">
<input type="button" id="button" name="button">
</form>
Hope that helps!
Use a datagrid with pagenation. I think datatable JQuery pluggin will work well for you
Related
i'm trying to make a simple webpage for making invoices. to select/load customer info i'm using a select dropdown filled with all the customers in the database.
after selecting a customer i want php to get all the values of that customer from the database and echo somewhere else on the page.
thought it would be something simple but tried everything and cant seem to get it to work.
any help?
after deleting all the code that didn't work anyway this is what i'm left with:
<select name="selectCustomer">
<option selected>Klantnaam</option>
<?
$result = mysql_query('SELECT * FROM '.$c_tbl_name);
while($row = mysql_fetch_array($result)) {
echo '<option value="'.$row['c_id'].'">';
echo $row['c_name'];
echo '</option>';
}
?>
</select>
You need some small AJAX function to do that:
jQuery(document).ready(function($){
$('[name="selectCustomer"]').change(function(){
$('#result').load('load_data_from_db.php', {
customer : $(this).val();
});
});
});
You than need a script load_data_from_db.php which takes the selected customer, generates the content and returns it to the client where it would be placed into an element with the ID result.
Try
$result = mysql_query('SELECT * FROM '.$c_tbl_name) or die(mysql_error());
and this will give info if the query failed.
Furthermore, you should really consider upgrading from mysql() as it is now deprecated. Try google search for 'php PDO'.
I have the following query that I ran on my database to remove some data:
delete subscriber, subscription from subscriber,subscription where subscription.status = 0 and subscription.snid=subscriber.snid;
But I now need to make the a php function that runs when I press a button called clean
then print out all the subscriber data that was deleted.
Not quitesure where to start with this.
this is my html so far:
<form id="form1" name="form1" method="post" action="">
Clean subscribers:
<input type="submit" name="clean" id="clean" value="Clean" />
</form>
Any help or advice with this is very much appreciated.
C
You'll need the button to submit a form to a handler page, the handler page would then run the query, and collect+print the data.
If you don't want to refresh the page (or have your users diverted into another page), you'll want to use Ajax.
That's where you start.
Is abvious you made no effort! but I will answer you anyway.
<?php
$con = mysql_connect("serverUrl","login","password");
mysql_select_db("dbName", $con);
$result = mysql_query("SELECT * FROM subscriber, subscription where subscription.status = 0 and subscription.snid=subscriber.snid;");
while($row = mysql_fetch_array($result))
{
echo $row['subscriber.name']; //assuming you have a field {name} in your table
echo "<br />";
}
mysql_query("delete subscriber, subscription from subscriber,subscription where subscription.status = 0 and subscription.snid=subscriber.snid;");
?>
First you'll need to select the data you're about to delete.
Then you'll need to delete it and return the selected rows.
$rows = array();
mysql_connect(...);
$res = mysql_query(...select query here...);
while($row=mysql_fetch_assoc($res)) {
$rows[] = $row;
}
$res = mysql_query(...delete query here...);
return $rows;
You might not want to totally delete the subscriber. If I were you I would include a field named "deleted" or something along those lines, indicating whether or not the subscriber has been deleted. Then query according to whether or not that field is true or false.
I am trying to show the results of the status of a bidding item using jQuery every second on every row in MySQL table, however only the result of the last row of the table is returned.
<?php
$query = "SELECT item, description, price, imageData, status, username, item_id FROM items";
$result = mysql_query($query) or die(mysql_error());
$z=0;
while($row = mysql_fetch_array($result))
{
//echo other columns here//
echo "<td><div id=status$z></div></td>";
?>
<script type=text/javascript>
function updatestatus(itemnum)
{
var url="updatestatus.php?auc=<?php echo $row['item_id']; ?>";
jQuery('#status' + itemnum).load(url);
}
setInterval("updatestatus(<? echo $z?>)", 1000);
</script>
<?
$z++;
}
?>
When I view source in the browser, the values for #status and auc for every row are correct. What am I missing here?
Here's the code for updatestatus.php
<?php
session_start();
require_once("connect.php");
$id = $_GET['auc'];
$getstatus = mysql_query("SELECT status FROM items WHERE item_id = '$id' ");
$row = mysql_fetch_array($getstatus);
echo"$row[status]";
?>
Everything looks good, save for the fact that it looks like you're creating multiple references to your updatestatus() function.
In Javascript, if you create multiple functions with the same name, calling them will only result in one of them running, usually the first or last one (depending on the implementation), so all the code you need to run in those functions needs to sit together in one function body.
If you're determined to use the code you've created, you'd need to throw all those update calls into one function body. There would be better ways to achieve what you need, but doing it with the code you've created, this would probably work better:
<?php
$query = "SELECT item, description, price, imageData, status, username, item_id FROM items";
$result = mysql_query($query) or die(mysql_error());
$javascript = "";
$z=0;
while($row = mysql_fetch_array($result))
{
//echo other columns here//
echo "<td><div id=status$z></div></td>";
// build the javascript to be put in the function later over here...
$javascript .= "jQuery('#status". $z ."').load('updatestatus.php?auc=". $row['item_id'] ."');";
$z++;
}
?>
...and then further down the page, create the javascript (modified slightly):
<script type=text/javascript>
function updatestatus()
{
<?php echo $javascript; ?>
}
setInterval(updatestatus, 1000);
</script>
So you're basically building up the Javascript that you'll need in your function, echoing it out inside the function body, and then setting the interval will call all that code, in this case, every second.
Like I said, there are definitely more efficient ways to achieve what you're trying to do, but this should work fine for now. I hope this makes sense, but please let me know if you need any clarity on anything! :)
I don't see that you're populating data using a incrementor. Is this supposed to be adding content to a page or replacing the content? from what it looks like it will just display one item, and then replace that one item with the next until it's done, which is why you see only the last row.
OR ...
the jquery update isn't being fed the $i variable .. change the function to
function updatestatus(itemnum) {
and then jquery echo to jQuery('#status' + itemnum).load(url);
then you can add the on-click/ or whatever to include the number
onclick='updatestatus("1")'
on the other hand you might be needing to pass the total number of items to the function and then creating an if there to cycle through them (not tested, but you get the idea i hope)
function updatestatus(numitems) {
var url = "";
var itemID = "";
for (i = 1; i <= numitems; i++) {
itemid = getElementById('#status'+numitems).getAttribute("itemID")
url="updatestatus.php?auc="+itemID;
jQuery('#status'+numitems).load(url);
}
}
setInterval("updatestatus()", 1000);
and the html element for "#status1" as created by the PHP should look like this:
<div id="status1" itemid="23455">
</div>
I'm building a simple web form (or tying to!) which displays a list of football teams. This list of teams is located in a single column mysql table. How can I make it so that if a team has been selected on the web form, that it cannot be selected again on the form? i.e. to make sure they are not accidentally selected to play each other, or play twice at the same time. My code so far is as below, which seems to be working fine. It includes several other iterations of the same code for the other home teams and away teams. Any pointers/help greatly appreciated.
<select name="hometeam">
<?php
$query = "SELECT * FROM teams order by teamname";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
echo "<option value=\"".$row['teamname']."\">".$row['teamname']."</option>\n ";
}
?>
</select>
<select name="hometeam2">
<?php
$query = "SELECT * FROM teams order by teamname";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
echo "<option value=\"".$row['teamname']."\">".$row['teamname']."</option>\n ";
}
?>
</select>
I Method: A possible and simple solution of this can be through javascript. That is, once the selection has been made at both the combo-boxes, then before submitting the form to the server, you can compare the two values and if they are found to be same then you can alert the user about this.
Also, just to add, though you validate using javascript, but its always advisable to re-validate at the server side to avoid any hack. Hope this helps.
II Method: If you don't want to show the team chosen in one drop-down in other drop-down then for this you will have to use Ajax in following manner:
On selection of a value in one drop-down - fire an ajax request - sending the chosen value from the dropdown to the server. Now, modify the query at the server to select all the values excluding this value and then send the values back to the client. This way the user will be able to see the values excluding the chosen one.
Hope this helps.
jQuery would make this quite simple:
<script type="text/javascript">
$(document).ready(function() {
$("select[name=hometeam]").change(function() {
if ( $(this).val() == $("select[name=hometeam2]").val() ) {
alert("This team cannot play itself!");
}
});
$("select[name=hometeam2]").change(function() {
if ( $(this).val() == $("select[name=hometeam]").val() ) {
alert("This team cannot play itself!");
}
});
});
</script>
http://jquery.com/
i am trying to implement pagination. A set of 9 products are displayed at a time. then upon clicking on a "View More" button, the content of a div should refresh by AJAX and show the next set of 9 products..here's the php code
if(!isset($_SESSION['current'])){
$query = "SELECT MAX(addedon) AS addedon FROM tags";
$result = mysql_query($query);
report($result);
$dated = mysql_fetch_assoc($result);
$recent = $dated['addedon'];
$_SESSION['current'] = $recent;
}
$query = "SELECT id, addedon
FROM tags
WHERE addedon <= '{$_SESSION['current']}'
ORDER BY addedon DESC
LIMIT 9
";
$result = mysql_query($query);
report($result);
while($row = mysql_fetch_assoc($result)){
$_SESSION['current'] = $row['addedon'];
$id = $row['id'];
$query = "SELECT name, image, cost
FROM tags, stock
WHERE tags.id={$id} AND stock.tagid = tags.id
";
$result1 = mysql_query($query);
report($result1);
$prodInfo = mysql_fetch_assoc($result1);
$pname = $prodInfo['name'];
$pimg = $prodInfo['image']; //the path to the actual image
$pcost = $prodInfo['cost'];
echo "<div class=\"oneproduct\">";
echo "<h3>{$pname}</h3><br />";
echo "<img src=\"{$pimg}\" height=\"{$ht}\" width=\"85px\" alt=\"prodImg\" /><br />";
echo "<span>Rs. {$pcost}</span>";
echo "<input type=\"image\" src=\"images/addcart.png\" class=\"addBtn\" />";
echo "</div>";
}
after all the products would be fetched and displayed, the last product on the page is stored as 'current' variable of SESSION.
problem is: the ajax thing always returns the initial set of 9 products and as soon as i refresh the page, the next set of products are coming..how do i make my link change the content?
The ajax code:
$("#viewMore").bind('click', function(){
$.ajax({
url:'showNineProds.php',
type:'POST',
dataType:'html',
success:function(data){
$("div#nineproducts").html(data);
},
error:function(xhr, status){
alert("Problem");
},
complete:function(xhr, status){
}
});
});
showNineProds.php simply calls a function that has been written above..
The correct way to do this is for the client-side code to specify with parameters to the AJAX call which "page" of records to be fetched. By using a session variable like this, the server has no concept of which records to get at which time. It's always going to return the "next" result. So any time you load that web page, it's going to serve the "next" set of records. There's no way to page backward in the result set.
Basically, you would store in local JavaScript values (or hidden form elements on the page, however you feel comfortable storing a value on the page) the information of the current result set and your AJAX call would send the necessary information to the server to return the requested result set.
For example, you could have a local JavaScript value that says which start record you're seeing and your page size:
startRecord = 1;
pageSize = 10;
Then if you click your "next" button the AJAX call would supply parameters to the server telling it what to fetch:
startRecord + pageSize, pageSize
You'd want to add a little bit of logic to determine if you're on the first or last page to disable "prev" and "next" functionality, of course. And there's a lot more you can do (variable page sizes, filtering and searching, sorting, etc.) but this is the basic gist of it.
You don't seem to be sending back the info from the ajax call. basically yoi might be fetching the values on the DB but don't seem to be sending the data back to the call..
do you echo the result set in some format? I can't see that in the code. in any case you can't access the $session variables from the js... these are accessible server side in php.