PHP - Paginate Ajax Returned Content
Hello all,
I feel pretty good that I got my AJAX filter working properly. But it still needs some help. Now I am returning the content with Ajax that I want from the search filter of dropdown option (keep in mind there are several options to filter by). But the content returned is often to much to fit on one page - so I need to paginate the successfully returned html from my AJAX call.
Here is where I get stumped. Do I setup a normal page nav outside the AJAX area?
</div><!-- AJAX return container--> <nav class="pagenav"> <ul id="pag-link"> <li class="old"><?php next_posts_link('« Older Sermons', $sermons_query->max_num_pages) ?></li> <li class="new"><?php previous_posts_link('Newer Sermons »', $sermons_query->max_num_pages) ?></li> </ul> </nav>IF so, how do I update the links info? or do I keep the page nav inside the AJAX area but use some custom code to retrieve the proper link? (I tried using the normal wordpress page nav functions in my php function but they provide the url of the page that the php function is on, not the actual page being viewed). Do I need to make a separate AJAX call to a function that just builds my links? or is there a way to do it with my main call? Here is my AJAX call: //Listen for the menu's to change except the main filter_by dropdown var ids = ['filter_preacher_dropdown', 'filter_sort_by_dropdown', 'filter_per_page_dropdown', 'filter_series_dropdown', 'filter_service_dropdown', 'filter_tag_dropdown', 'filter_book_dropdown', 'filter_year_dropdown']; $('#' + ids.join(',#')).change(function(e) { var pt = [ "preacher","series","service" ]; if($.inArray(this.name, pt)!==-1){ var mk = this.name; var mv = $(this).val(); var ppp = $("#filter_per_page_dropdown").val(); var ob = $("#filter_sort_by_dropdown").val(); var data = { action: 'filter_sermons', meta_key: mk, meta_value: mv, posts_per_page: ppp }; $.post(mbsb_ajaxurl, data, function(response) { $('#sermonlists').fadeOut('slow', function() { $(this).html(response) }).fadeIn('slow'); }); }and here is my php function (slightly paired down for viewing ease): //ajax for sermons filter add_action('wp_ajax_filter_sermons', 'check_ajax'); add_action('wp_ajax_nopriv_filter_sermons', 'check_ajax'); function check_ajax() { global $wpdb, $paged, $max_num_pages; //check if filter is on post_type if($_POST['meta_key']){ $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $mk = '"'.$_POST['meta_key'].'"'; $mv = intval($_POST['meta_value']); $ppp = intval($_POST['posts_per_page']); $offset = ($paged - 1) * $ppp; $sermons = $wpdb->get_results("SELECT SQL_CALC_FOUND_ROWS sermons.* FROM {$wpdb->prefix}posts AS sermons, {$wpdb->prefix}postmeta WHERE meta_key = {$mk} AND meta_value = {$mv} AND sermons.ID = {$wpdb->prefix}postmeta.post_id LIMIT {$offset}, {$ppp}", OBJECT); $sql_posts_total = $wpdb->get_var( "SELECT FOUND_ROWS();" ); $max_num_pages = ceil($sql_posts_total / $ppp); }elseif($_POST['name']){ //another custom query }elseif ($_POST['book_number']){ //another custom query } $posts = get_posts(); // returns posts in an array if($sermons) { global $post; foreach ($sermons as $post){ setup_postdata($post); //custom query info returned here } //Would the Pagination for the AJAXED content go here? }else{ ?> <h2 class="center">Not Found</h2> <p class="center">Sorry, but you are looking for something that isn't here.</p> <?php } die(); } Similar TutorialsHello, I've been trying this for hours now, looking at different examples and trying to change them to work for me, but with no luck... This is what I am trying to do: I have a simple form with: - 1 input field, where I can enter a number - 1 Submit Button When I enter a number into the field and click submit, I want that number to be send to the php file that is in the ajax call, then the script will take that number and run a bunch of queries and then return a new number. I want that new number to be used to call the php script via ajax again, until no number is returned, or something else is returned like the word "done" or something like that, at which point is simply makes an alert or populated a div with a message... The point is, that depending on the number entered it could take up to an hour to complete ALL the queries, so I want the script that is called to only run a fixed amount of queries at a time and then return the number it is currently at (+1), so that it can continue with the next number when it is called again. I would like to use jquery, but could also be any other way, as long as I get this to work. I already have the php script completed that needs to be called by the ajax, it returns a single number when being called. Thank you, vb Hi All,
Am hoping someone can point out my perhaps obvious issue here.
I've a series of links that are dynamically created:
<a class="team-link" rel="<?php the_ID(); ?>" href="#">When a link is clicked, I'm trying to get content to load into this DIV: <div id="single-post-container"></div>I have the following jquery: <script> $(document).ready(function(){ $.ajaxSetup({cache:false}); $(".team-link").click(function(){ var post_id = $(this).attr("rel"); $.ajax({ url : "http://www.domain.co.uk/wp-content/themes/name/loop.php", data : {"the_team": post_id }, type : "POST", dataType : "html", success: function(response) { $("#single-post-container").html(response); } return false; }); }); </script>This is my loop.php file: require_once('../../../wp-load.php'); // Our variables $the_team = (isset($_GET['post_id'])) ? $_GET['post_id'] : 0; echo $the_team; query_posts(array( 'post_type' => 'work', 'meta_key' => 'author_name', 'meta_value' => $the_team )); // our loop if (have_posts()) { while (have_posts()){ the_post(); ?> <h1><?php the_title(); ?></h1> <?php the_content(); ?> <hr /> <?php } } wp_reset_query();However, when you click the link, nothing happens. I know loop.php works as I can specify a value and manually browse to it to see the content. I feel I'm missing something obvious as I'm new to AJAX. Your help/patience is very much appreciated Stop posting non-PHP questions in the PHP Coding Help section. We have many sub-forums, including both a JavaScript forum and one dedicated entirely to Ajax. This topic has been moved to Ajax Help. http://www.phpfreaks.com/forums/index.php?topic=327454.0 I am using the following search code with a paginate. the code works fine but how do i hide the paginate if the search results are less than the default settings Code: [Select] mysql_connect ("localhost", "user","pword") or die (mysql_error()); mysql_select_db ("database"); $term = $_GET['term']; $cat = $_GET['cat']; //max display per page $per_page = 4; //get start variable $start = $_GET['start']; // cout records $record_count = mysql_num_rows(mysql_query("SELECT * FROM table")); //count max pages $max_pages = $record_count / $per_page; //may count as decimal if (!$start) $start =0; $sql="SELECT * FROM table WHERE productname like '%$term%' and category like '%$cat%' LIMIT $start, $per_page"; $result = mysql_query($sql); $sql = mysql_query("SELECT COUNT(*) as total FROM table"); list($number) = mysql_fetch_row($sql); if (!mysql_num_rows($result)) { die("NO RECORD FOUND") ; exit; } else { echo "Your matches for: <b>$term</b><br><br>"; } while ($row = mysql_fetch_array($result)){ $num_rows = mysql_num_rows($number); if (!$i++) echo "Total records $number"; ?> <br /> <br /> <?php echo 'ID: '.$row['id']; ?> <br /> <?php echo '<br/> Product Name: '.$row['productname'];?> <br /> <?php echo '<br/> Price: '.$row['price']; ?><br /> <?php echo '<br/> category: '.$row['category']; ?> <br /> <?php } ?> <?php //setup prev and next variables $prev = $start - $per_page; $next = $start + $per_page; // show prev button if(!($start<=0)) echo " <a href='ttr.php?start=$prev'>Prev </a>"; //set var for first page $i=1; for ($x=0;$x<$record_count;$x=$x+$per_page) { if ($start!=$x) echo "<a href='page.php?start=$x'>$i</a> "; else echo "<a href='page.php?start=$x'><b>$i</b></a> "; $i++; } //show next button if (!($start>=$record_count-$per_page)) echo " <a href='page.php?start=$next'>Next</a>"; ?> Hoping someone can help me. I am trying to limit the number of results from a sql database and I assume that I should use pagination. How do I do this with the following code? Thanks in advance. Code: [Select] <?php if ($_GET[search] == 1) $qstring = "WHERE TITLE LIKE '%$_POST[search]%'"; if ($_GET[search] == 2) { $qstring = "WHERE CATEGORY LIKE '%-$_POST[search_cat]-%'"; $SQL3 = "SELECT * from CATEGORIES WHERE ID = '%-$_POST[search_cat]-%'"; $result3 = @mysql_query( $SQL3 ); $row3 = @mysql_fetch_array( $result3 ); } if ($_GET[search] == 3) { $qstring = "WHERE PACKAGE = '$_POST[search_package]'"; } $setpage = 'add_listings'; $return = 'manage_listings'; $table = "LISTINGS"; if (empty($qstring)) $qstring = 'ORDER BY TITLE ASC'; $qstring = "$qstring"; ?> <?php if ($rowxxx[HELPBOX] == $nil || $rowxxx[HELPBOX] == Show) { ?> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td class="td3" colspan="2"><b> Tool Tips</b></td> </tr> <tr> <td class="td4" valign="top"> <p><img src="../images/Help.png" width="64" height="64"></p> </td> <td class="td4" width="100%" valign="top"> <table width="100%" align="center" cellpadding="0" cellspacing="0" border="0"> <tr> <td> <div align="center"><img src="../images/edit_listing.jpg" border="0" alt="Edit this listing" width="22" height="22" /></div> </td> <td class="font1" width="100%"> Edit this listing.</td> </tr> <tr> <td> <div align="center"><img src="../images/delete-page-red.gif" alt="Delete this listing" border="0" width="14" height="14" /></div> </td> <td class="font1" width="100%"> Delete this listing.</td> </tr> <tr> <td> <div align="center"><img src="../images/user-group3.gif" width="14" height="14"></div> </td> <td class="font1" width="100%"> Duplicate this listing and edit its clone.</td> </tr> <tr> <td><a href="?page=add_photos&id=<?php echo $row[ID]; ?>"><img src="../images/Iphoto.png" width="22" height="22" border="0"></a></td> <td class="font1" width="100%"> Add photos.</td> </tr> <tr> <td> </td> <td class="font1" width="100%"> <?php $sql_active_accounts = "SELECT count(*) FROM LISTINGS"; $res_active_accounts = @mysql_query($sql_active_accounts); $row_active_accounts = @mysql_fetch_row($res_active_accounts); ?> <b> ( <?php echo " $row_active_accounts[0] "; if ($row_active_accounts == $nil) echo " 0 "; ?> ) </b>Listings in your database.</td> </tr> </table> </td> </tr> </table> <br> <?PHP } ?> <form action="?page=<?php echo $_GET[page]; ?>&search=2" method="post" name="form1" id="form1"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td class="td3"> <b>Find Listings by Category</b></td> </tr> </table> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td class="td4" nowrap width="100%"> Select Category</td> <td class="td4"> <select name="search_cat"> <option selected> <?PHP ECHO $row3[TITLE]; ?> </option> <?PHP $SQLcaT = "SELECT * from CATEGORIES ORDER BY TITLE ASC"; $resultcaT = @mysql_query( $SQLcaT ); while( $rowcaT = @mysql_fetch_array( $resultcaT ) ) { $sql2 = "SELECT count(*) FROM LISTINGS WHERE CATEGORY LIKE '%-$rowcaT[ID]-%'"; $res2 = @mysql_query($sql2); $row2 = @mysql_fetch_row($res2); ?> <option value = "<?php echo $rowcaT[ID]; ?>"> <?php echo "$rowcaT[TITLE]"; if (empty($row2[0])) echo ' [ 0 ]'; else echo " [ $row2[0] ]"; ?> </option> <?PHP } ?> </select> </td> <td class="td4"> <input type="submit" name="Submit" value="Search" /> </td> </tr> </table> </form> <br> <form action="?page=<?php echo $_GET[page]; ?>&search=3" method="post" name="form1" id="form1"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td class="td3"> <b>Find Listings by Package</b></td> </tr> </table> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td class="td4" nowrap width="100%"> Select Package</td> <td class="td4"> <select name="search_package" id="search_package"> <option selected value ="<?php echo $row[DEFAULTPACKAGE]; ?>"> <?PHP $SQLlu = "SELECT * from PACKAGES WHERE ID = '$row[DEFAULTPACKAGE]'"; $resultlu = @mysql_query( $SQLlu ); $rowlu = @mysql_fetch_array( $resultlu ); ?> <?PHP echo $rowlu[NAME]; ?> </option> <?PHP $SQL3 = "SELECT * from PACKAGES ORDER BY NAME ASC"; $result3 = mysql_query( $SQL3 ); while( $row3 = mysql_fetch_array( $result3 ) ) { ?> <option value="<?php echo $row3[ID]; ?>"> <?php echo $row3[NAME]; ?> </option> <?PHP } ?> </select> </td> <td class="td4"> <input type="submit" name="Submit" value="Search" /> </td> </tr> </table> </form> <br> <form action="?page=<?php echo $_GET[page]; ?>&search=1" method="post" name="form1" id="form1"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td class="td3"> <b>Find Listing by Name</b></td> </tr> </table> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td class="td4" nowrap width="100%"> Listing Title</td> <td class="td4"> <input type="text" name="search" value="<?php echo $_POST[search]; ?>" size="40" /> </td> <td class="td4"> <input type="submit" name="Submit" value="Search" /> </td> </tr> </table> </form> <br> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td class="td3"> <b>Last Listing Added</b></td> </tr> </table> <?php $SQL = "SELECT * from $table ORDER BY ID DESC LIMIT 1"; $result = @mysql_query( $SQL ); while( $row = @mysql_fetch_array( $result ) ) { $check = 1; ?> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <?PHP $filename = "$svr_rootscript/product_images/thumb/$row[IMAGENAME].jpg"; if (file_exists($filename)) { ?> <td nowrap class="td4" align="center" valign="top"> <a href="?page=add_photos&id=<?php echo $row[ID]; ?>"><img src="../product_images/thumb/<?php echo "$row[IMAGENAME]"; ?>.jpg" border="1" /></a> </td> <?PHP } ?> <td class="td4" colspan="2" width="100%"><b> <?php echo "<a href = \"?page=$setpage&id=$row[ID]&qt=update\">$row[TITLE]</a>"; ?> </b><br> <span class="font3">Category(s): <?PHP $pieces = explode("-", $row[CATEGORY]); foreach ($pieces as $cats => $value) { if ($value != $nil && $value != '-' && $value != '--') { $SQLCat = "SELECT * from CATEGORIES WHERE ID = '$value'"; $resultCat = @mysql_query( $SQLCat ); $rowCat = @mysql_fetch_array( $resultCat ); echo "$rowCat[TITLE], "; } } ?> </span></td> <td nowrap class="td4"><a href="?page=add_photos&id=<?php echo $row[ID]; ?>"><img src="../images/Iphoto.png" width="22" height="22" border="0"></a></td> <td class="td4"><a href="<?php echo "?page=$setpage&id=$row[ID]&qt=insert&clone=1"; ?>"> <img src="../images/user-group3.gif" border="0" alt="Edit this listing" width="14" height="14" /></a> </td> <td class="td4"><a href="<?php echo "?page=$setpage&id=$row[ID]&qt=update"; ?>"> <img src="../images/edit-comment-orange.gif" border="0" alt="Edit this listing" width="14" height="14" /></a> </td> <td class="td4"><a href="../library/delete.php?id=<?php echo $row[ID]; ?>&return=<?php echo $return; ?>&type=<?php echo "$table"; ?>"> <img src="../images/delete-page-red.gif" alt="Delete this listing" border="0" width="14" height="14" /></a> </td> </tr> </table> <?php } ?> <br> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td class="td3"> <b>Your Listings</b></td> </tr> </table> <?php $SQL = "SELECT * from $table $qstring"; $result = @mysql_query( $SQL ); while( $row = @mysql_fetch_array( $result ) ) { $check = 1; ?> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <?PHP $filename = "$svr_rootscript/product_images/thumb/$row[IMAGENAME].jpg"; if (file_exists($filename)) { ?> <td nowrap class="td4" align="center" valign="top"> <a href="?page=add_photos&id=<?php echo $row[ID]; ?>"><img src="../product_images/thumb/<?php echo "$row[IMAGENAME]"; ?>.jpg" border="1" /></a> </td> <?PHP } ?> <td class="td4" colspan="2" width="100%"><b> <?php echo "<a href = \"?page=$setpage&id=$row[ID]&qt=update\">$row[TITLE]</a>"; ?> </b><br> <span class="font3">Category(s): <?PHP $pieces = explode("-", $row[CATEGORY]); foreach ($pieces as $cats => $value) { if ($value != $nil && $value != '-' && $value != '--') { $SQLCat = "SELECT * from CATEGORIES WHERE ID = '$value'"; $resultCat = @mysql_query( $SQLCat ); $rowCat = @mysql_fetch_array( $resultCat ); echo "$rowCat[TITLE], "; } } ?> </span> </td> <td nowrap class="td4"><a href="?page=add_photos&id=<?php echo $row[ID]; ?>"><img src="../images/Iphoto.png" width="22" height="22" border="0"></a></td> <td class="td4"><a href="<?php echo "?page=$setpage&id=$row[ID]&qt=insert&clone=1"; ?>"> <img src="../images/user-group3.gif" border="0" alt="Edit this listing" width="14" height="14" /></a> </td> <td class="td4"><a href="<?php echo "?page=$setpage&id=$row[ID]&qt=update"; ?>"> <img src="../images/edit-comment-orange.gif" border="0" alt="Edit this listing" width="14" height="14" /></a> </td> <td class="td4"><a href="../library/delete.php?id=<?php echo $row[ID]; ?>&return=<?php echo $return; ?>&type=<?php echo "$table"; ?>"> <img src="../images/delete-page-red.gif" alt="Delete this listing" border="0" width="14" height="14" /></a> </td> </tr> </table> <?php } ?> <?PHP if (empty($check)) { ?> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td nowrap class="td4">No listings found.</td> </tr> </table> <?PHP } ?> I have a MySQL query that returns rows containing date_add column like below:
DATE(date_add) 2014-01-07 2014-01-07 2014-01-07 2014-01-07 2014-01-08 2014-01-15 2014-01-20 2014-01-20 2014-01-20 2014-01-26 2014-01-28 2014-02-16 2014-02-16 2014-02-16 2014-02-16 2014-02-16 2014-02-16 2014-02-16 2014-02-18 2014-02-18 2014-03-08 2014-03-08How can I have pagination based on dates and show rows with the same date in a page and not just based on predefined limit number? kinda new in php so hope somebody can help me im about to get mad with this i have 2 pages index.htm and list_tbl.php in the index.htm i have a textbox so the customers write what they want to find in my site with a search button like this : <form id="form1" name="form1" method="post" action="list_tbl.php" target="_blank"> in the list_tbl.php is like this <?php $srch = $_POST['prod_search']; $se = "%"; '$all' = $se.$srch.$se; $msj="You look for : "; $msj2=$mensaj.$srch; $regis=" your search match :"; $regis2=" Items"; $conn = mysql_connect('localhost','root','pass') or trigger_error("tbl_die", E_USER_ERROR); . . . . . works fine if i write 4 example "blue metal" in the index the php page get me You Look for blue metal Your search match XX items but if the filter get more then 1 page when i clik in the next link the filter is gone the "blue metal" string is lost and i have all the items in the table why the $_post Value is lost after paginate??? 1000 TNX How to acheive it friends? i want my current codes to show results accouding to current month followed by year, the precious month goes to the page two.
would really appreciate if someone could help me acheive it
$tableName="records"; Edited by lovephp, 02 December 2014 - 11:50 AM. Hey there, I have never really done pagination before and I was wondering if anyone can take a look at my code and help me with coding pagination? This database will be storing a lot of information and I am going to have the need to break it into multiple pages. The following code is the code from my results page, which is where I assume I will need to code the pagination. This is the page that displays all of the results after everything is processed and entered into the database in a different php file. <?php $username="removed_for_this_post"; //Database Username $password="removed_for_this_post"; //Database Password $database="removed_for_this_post"; //Database Name mysql_connect("localhost",$username,$password); //Connection to database @mysql_select_db($database) or die("ALERT! Database not found!"); //Selection of database $query="SELECT * FROM leads ORDER by id DESC"; //Database table to query $result=mysql_query($query); $num=mysql_numrows($result); mysql_close(); ?> <html> <head> <link href="db_style.css" rel="stylesheet" type="text/css" media="screen" /> </head> <body> <div id="wrap"> <div id="header"> <div id="hdr_content"> </div> </div> <br><br><br><br> <center> <table border="1" bordercolor="#000000" cellspacing="2" cellpadding="10"> <tr> <th bgcolor="#01337f"><font face="Arial, Helvetica, sans-serif" size="2">Name</font></th> <th bgcolor="#01337f"><font face="Arial, Helvetica, sans-serif" size="2">E-Mail</font></th> <th bgcolor="#01337f"><font face="Arial, Helvetica, sans-serif" size="2">Age</font></th> <th bgcolor="#01337f"><font face="Arial, Helvetica, sans-serif" size="2">Gender</font></th> <th bgcolor="#01337f"><font face="Arial, Helvetica, sans-serif" size="2">Location</font></th> <th bgcolor="#01337f"><font face="Arial, Helvetica, sans-serif" size="2">Home Phone</font></th> <th bgcolor="#01337f"><font face="Arial, Helvetica, sans-serif" size="2">Other Phone</font></th> <th bgcolor="#01337f"><font face="Arial, Helvetica, sans-serif" size="2">Best Time to Reach</font></th> <th bgcolor="#01337f"><font face="Arial, Helvetica, sans-serif" size="2">Referrer</font></th> <th bgcolor="#01337f"><font face="Arial, Helvetica, sans-serif" size="2" color="#FFFFFF">Options</font></th> </tr> </div> <div id="footer"> <div class="footer_content"> <font class="footer_header"> </div> </div> <?php $i=0; while ($i < $num) { $id=mysql_result($result,$i,"id"); //Unique ID Field $name=mysql_result($result,$i,"name"); //Name $email=mysql_result($result,$i,"email"); //EMail Address $age=mysql_result($result,$i,"age"); //Age $gender=mysql_result($result,$i,"gender"); //Gender $location=mysql_result($result,$i,"location"); //City of Residence $homephone=mysql_result($result,$i,"homephone"); //Home Phone Number $otherphone=mysql_result($result,$i,"otherphone"); //Secondary Phone Number $besttime=mysql_result($result,$i,"besttime"); //Best Time to Reach $referrer=mysql_result($result,$i,"referrer"); //Referrer ?> <tr> <td align="center" bgcolor="#CCCCCC"><font class="lead_txt"><? echo $name; ?></font></td> <td align="center" bgcolor="#CCCCCC"><font face="Arial, Helvetica, sans-serif" size="2" class="lead_txt"><? echo $email; ?></font></td> <td align="center" bgcolor="#CCCCCC"><font face="Arial, Helvetica, sans-serif" size="2" class="lead_txt"><? echo $age; ?></font></td> <td align="center" bgcolor="#CCCCCC"><font face="Arial, Helvetica, sans-serif" size="2" class="lead_txt"><? echo $gender; ?></font></td> <td align="center" bgcolor="#CCCCCC"><font face="Arial, Helvetica, sans-serif" size="2" class="lead_txt"><? echo $location; ?></font></td> <td align="center" bgcolor="#CCCCCC"><font face="Arial, Helvetica, sans-serif" size="2" class="lead_txt"><? echo $homephone; ?></font></td> <td align="center" bgcolor="#CCCCCC"><font face="Arial, Helvetica, sans-serif" size="2" class="lead_txt"><? echo $otherphone; ?></font></td> <td align="center" bgcolor="#CCCCCC"><font face="Arial, Helvetica, sans-serif" size="2" class="lead_txt"><? echo $besttime; ?></font></td> <td align="center" bgcolor="#CCCCCC"><font face="Arial, Helvetica, sans-serif" size="2" class="lead_txt"><? echo $referrer; ?></font></td> <td bgcolor="#01337f""><a href="db_edit.php?id=<?php echo $id; ?>"><img src="edit.png" width="25" height="25" alt="Edit"></a> <a href="db_remove.php?id=<?php echo $id; ?>"><img src="delete.png" width="25" height="25" alt="Delete"></a> <a href="email_lead.php?id=<?php echo $name, $email; ?>"><img src="email.png" width="25" height="25" alt="E-Mail"></a></td> </tr> </center> </font> </body> </html> <?php $i++; } echo "</table>"; ?> Hey there. Not sure how to word this. I've been flying blind as a newbie trying to figure out some pagination for a left joined query. I've got syntax errors trying to set up the SELECT COUNT function that adds up the results of the search on a previous page so it knows how many results matched both tables. Right now, I've got this mess, and it's giving me a syntax error, "You have an error in your SQL syntax; .... near 'LEFT JOIN plantae ON (descriptors.plant_id = plantae.pla' at line 12" Code: [Select] $data = "Select (SELECT COUNT(*) FROM descriptors ) AS count1, (SELECT COUNT(*) FROM plantae ) AS count2 LEFT JOIN plantae ON (descriptors.plant_id = plantae.plant_name) WHERE `leaf_shape` LIKE '%$select1%' AND `leaf_venation` LIKE '%$select3%' AND `leaf_margin` LIKE '%$select4%'"; $result = mysql_query ($data); if (!$result) { die("Oops, my query failed. The query is: <br>$data<br>The error is:<br>".mysql_error()); } Right now I redirect to index page after I delete a record. However I am looking to make it so that I can delete a record without redirecting the page. I know this can be accomplised using Ajax. I have spent countless hours before trying to make it work, but it did not work.
So here is a basic setup I created. Can you please update it with ajax code so that I can see how it's done properly?
<!DOCTYPE HTML> <html lang="en"> <head> <meta charset="UTF-8"> <title>Home Page</title> </head> <body> <div class="record" > <a href="record.php?id=<?php echo $record_id ?>"><?php echo $record_name; ?></a> <div class="delete-record"> <a href="delete.php">Delete Record</a> </div> </div> </body> </html> Edited by man5, 18 August 2014 - 08:55 PM. When I submit the login form its not returning anything and it was working until I added in the $remember part so I'm wondering why its still not returning TRUE. Code: [Select] /** * Login user on the site. Return TRUE if login is successful * (user exists and activated, password is correct), otherwise FALSE. * * @param string * @param string * @param int * @return bool */ function login($username, $password, $remember) { $this->ci->load->model('kow_auth/users'); $user_data = $this->ci->users->get_user_by_username($username); if ($user_data) { $regenFromPostPW = $this->ci->genfunc->reGenPassHash($password, $user_data->password2); if ($regenFromPostPW == $user_data->password) { $this->ci->session->set_userdata(array( 'xtr' => 'yes', 'user_id' => $user_data->user_id, 'username' => $user_data->username, 'status' => $user_data->users_statuses_id, 'role' => $user_data->users_roles_id )); if ($remember == 1) { $timeTOexpire = time()+(60*60*24*31*2); $this->input->set_cookie('xtrcook', '1', $timeTOexpire); } else { $cookie = trim(get_cookie('xtrcook')); if ($cookie || is_numeric($cookie)) { delete_cookie('xtrcook'); } } $this->clear_login_attempts($user_data->user_id); $this->ci->users->insert_session($this->ci->session->userdata('session_id'), $this->ci->session->userdata('user_id'), $this->ci->genfunc->getRealIpAddr(), $this->ci->genfunc->getUserOS()); return TRUE; } else { $this->increase_login_attempt($user_data->user_id); } } else { return NULL; } } It's been quite a while since I have coded in PHP and I am running into difficulties looping through the returned response from an API. I am pretty comfortable in my PHP skills, but for some reason I keep getting caught up trying to loop through the following... Many of the returns from the API include several more layers of Objects, the example below is about the most simplistic return from the API.
I'm sure I'm just missing something easy and any help or example code simply looping through and echoing each result would be greatly appreciated!! Ideally I would like to be able to loop through both of the scenarios below.
I did a var_dump on the response and here is what I get:
array (size=1) 'Body' => object(stdClass)[6] public 'userContext' => object(stdClass)[8] public 'convCred' => object(stdClass)[10] ... public 'valid' => boolean true public 'isPasswordExpired' => boolean false public 'cbId' => int 0083802121 public 'cnId' => int 1000545 public 'locale' => string 'en_US' (length=5) public 'tncVersion' => int 2 public 'applicationId' => string 'ECFDA1FDBC00270772870CDC1786FFED' (length=32) public 'cbConvCred' => object(stdClass)[9] ... public 'preferenceInfo' => object(stdClass)[7] ... public 'lastLoginTime' => int 1406729928 public 'loginCount' => int 282 public 'passwordRecovered' => boolean false public 'emailAddress' => string 'abc@123.com' (length=11) public 'loginName' => string 'TEST' (length=8) public 'userId' => int 15932274 public 'userType' => object(stdClass)[14] public 'userTypeId' => int 1 public 'userTypeName' => string 'normal_user' (length=11) public 'isConfirmed' => boolean falseIf I jsonencode and jsondecode the response this is what I get: object(stdClass)[13] public 'Body' => object(stdClass)[17] public 'userContext' => object(stdClass)[18] public 'convCred' => object(stdClass)[19] ... public 'valid' => boolean true public 'isPasswordExpired' => boolean false public 'cbId' => int 0083802121 public 'cnId' => int 1000545 public 'locale' => string 'en_US' (length=5) public 'tncVersion' => int 2 public 'applicationId' => string 'ECFDA1FDBC00270772870CDC1786FFED' (length=32) public 'cbConvCred' => object(stdClass)[20] ... public 'preferenceInfo' => object(stdClass)[21] ... public 'lastLoginTime' => int 1406729953 public 'loginCount' => int 283 public 'passwordRecovered' => boolean false public 'emailAddress' => string 'abc@123.com' (length=11) public 'loginName' => string 'TEST' (length=8) public 'userId' => int 15932274 public 'userType' => object(stdClass)[24] public 'userTypeId' => int 1 public 'userTypeName' => string 'normal_user' (length=11) public 'isConfirmed' => boolean false Hi I have a couple of phpbb forums on my web space. One is randomly throwing people off and it is getting far worse. I have traced down the issue to the IP address. Phpbb stores the IP address and session id and checks that they match. If not it throws the user out. The session ids seem to be there OK, but the IP addresses aren't. When it causes a problem the IP address seems to be returned as "::" (yes, 2 colons). I have used the following routine to try and obtain a relevant IP address and it to returns "::" Code: [Select] function getRealIpAddr() { if (!empty($_SERVER['HTTP_CLIENT_IP'])) //check ip from share internet { $ip=$_SERVER['HTTP_CLIENT_IP']; } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) //to check ip is pass from proxy { $ip=$_SERVER['HTTP_X_FORWARDED_FOR']; } else { $ip=$_SERVER['REMOTE_ADDR']; } return $ip; } Any ideas? All the best Keith Need some help finding out why this is returning a null result set:
The below code is giving me a result set of an integer set to "0" (the id), a "word"and "def" both set to NULL. It's failing at my "Error #2" point. var_dumps on $id, $word, and $def all give the null output. Each $category is being shown when I var_dump($category).
I know this shouldn't be the case because when I run this straight in PHPMyAdmin I get a non-null result set.
(Not sure why my indentation is not carrying over to the forum. Sorry about that.)
<?php session_start(); if(!isset($_SESSION['loopcatch']) || $_SESSION['loopcatch']==null || !is_int($_SESSION['loopcatch'])){ $_SESSION['loopcatch']=0; } if($_SESSION['loopCatch'] > 1){ //Email error die(); } require 'dbConnect.php'; $categories=array('business', 'music', 'film', 'drum'); //Pull Quotes //Query to Pull random quote $mainQuery="SELECT `r1`.`id`, `r1`.`word`, `r1`.`def` FROM `dictionary` AS `r1` JOIN (SELECT (RAND() * (SELECT MAX(`id`) FROM `dictionary`)) AS `id`) AS `r2` WHERE `r1`.`id` >= `r2`.`id` AND `category`=? AND `checked`=0 ORDER BY `r1`.`id` ASC LIMIT 1"; //prepare quotes query if($prepareQuote=mysqli_prepare($conn, $mainQuery)){ //filter through each category foreach($categories as $category){ //Bind the variable to the quotes query mysqli_stmt_bind_param($prepareQuote, "s", $category); //execute quotes statement mysqli_stmt_execute($prepareQuote); //Store quotes result set mysqli_stmt_store_result($prepareQuote); //Check how many rows are returned if(mysqli_stmt_num_rows($prepareQuote) > 0){ //Bind results to variables mysqli_stmt_bind_result($prepareQuote, $id, $word, $def); //If $id, $word, or $def is null abort and email error if(!is_null($id) && is_numeric($id) && !is_null($word) && !is_null($def)){ while($row=mysqli_stmt_fetch($prepareQuote)){ mysqli_autocommit($conn, FALSE); //Input into second table $updateQuery="UPDATE `quotes` SET `word`=?, `def`=? WHERE `category`=?"; //prepare insert query if($updateQuote=mysqli_prepare($conn, $updateQuery)){ //Bind the variables to the insert query mysqli_stmt_bind_param($updateQuote, "sss", $word, $def, $category); //execute insert statement mysqli_stmt_execute($updateQuote); //Store insert quote result set mysqli_stmt_store_result($updateQuote); //Check how many rows are returned on insert quote query if(mysqli_stmt_affected_rows($updateQuote) > 0){ //If query run sucessfully insert and update; if not rollback. //mark quote checked $checkedQuery="UPDATE `dictionary` SET `checked`=1 WHERE `id`=?"; //prepare checked query if($checkedQuote=mysqli_prepare($conn, $checkedQuery)){ mysqli_stmt_bind_param($checkedQuote, "i", $id); //execute checked statement mysqli_stmt_execute($checkedQuote); //Store checked quote result set mysqli_stmt_store_result($checkedQuote); //Check how many rows are returned on checked quote query if(mysqli_stmt_affected_rows($checkedQuote > 0)){ mysqli_commit($conn); } else{ echo 'Error #6 '; mysqli_rollback($conn); } } else{ echo 'Error #5'; //Email error die(); } } else{ echo 'Error #4'; mysqli_rollback($conn); } } else{ echo 'Error #3'; //Email error die(); } } } else{ echo 'Error #2'; //Query returned blank result set - Email Error } } else{ //If zero rows returned, uncheck rows in table for that specific category and re-run the query. $uncheckQuery="UPDATE `dictionary` SET `checked`=0 WHERE `category`=?"; if($uncheckQuotes=mysqli_prepare($conn, $uncheckQuery)){ //Bind the variable to the query mysqli_stmt_bind_param($uncheckQuotes, "s", $category); //execute statement mysqli_stmt_execute($uncheckQuotes); //Store result set mysqli_stmt_store_result($uncheckQuotes); //Check how many rows are returned if(mysqli_stmt_affected_rows($uncheckQuotes) > 0){ $_SESSION['loopCatch']++; header("Location: ./pullDailyQuotes.php"); } else{ //Email error } } } } } else{ //Email error echo 'Error #1'; die(); } ?> Edited by HDRebel88, 01 June 2014 - 08:54 PM. Hi all, I really need some help getting values from the usps api Well not getting them but using them. I get the values but I need to extract the info to use in a form. This is the class im using Code: [Select] <?php require_once("xmlparser.php"); class USPS { var $server = "http://testing.shippingapis.com/ShippingAPITest.dll"; var $user = "****"; var $pass = "****"; var $service = ""; var $dest_zip; var $orig_zip; var $pounds; var $ounces; var $container = "None"; var $size = "REGULAR"; var $machinable; var $country = "USA"; function setServer($server) { $this->server = $server; } function setUserName($user) { $this->user = $user; } function setPass($pass) { $this->pass = $pass; } function setService($service) { /* Must be: Express, Priority, or Parcel */ $this->service = $service; } function setDestZip($sending_zip) { /* Must be 5 digit zip (No extension) */ $this->dest_zip = $sending_zip; } function setOrigZip($orig_zip) { $this->orig_zip = $orig_zip; } function setWeight($pounds, $ounces=0) { /* Must weight less than 70 lbs. */ $this->pounds = $pounds; $this->ounces = $ounces; } function setContainer($cont) { $this->container = $cont; } function setSize($size) { $this->size = $size; } function setMachinable($mach) { /* Required for Parcel Post only, set to True or False */ $this->machinable = $mach; } function setCountry($country) { $this->country = $country; } function getPrice() { if($this->country=="USA"){ // may need to urlencode xml portion $str = $this->server. "?API=RateV2&XML=<RateV2Request%20USERID=\""; $str .= $this->user . "\"%20PASSWORD=\"" . $this->pass . "\"><Package%20ID=\"0\"><Service>"; $str .= $this->service . "</Service><ZipOrigination>" . $this->orig_zip . "</ZipOrigination>"; $str .= "<ZipDestination>" . $this->dest_zip . "</ZipDestination>"; $str .= "<Pounds>" . $this->pounds . "</Pounds><Ounces>" . $this->ounces . "</Ounces>"; $str .= "<Container>" . urlencode($this->container) . "</Container><Size>" . $this->size . "</Size>"; $str .= "<Machinable>" . $this->machinable . "</Machinable></Package></RateV2Request>"; } else { $str = $this->server. "?API=IntlRate&XML=<IntlRateRequest%20USERID=\""; $str .= $this->user . "\"%20PASSWORD=\"" . $this->pass . "\"><Package%20ID=\"0\">"; $str .= "<Pounds>" . $this->pounds . "</Pounds><Ounces>" . $this->ounces . "</Ounces>"; $str .= "<MailType>Package</MailType><Country>".urlencode($this->country)."</Country></Package></IntlRateRequest>"; } $ch = curl_init(); // set URL and other appropriate options curl_setopt($ch, CURLOPT_URL, $str); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // grab URL and pass it to the browser $ats = curl_exec($ch); // close curl resource, and free up system resources curl_close($ch); $xmlParser = new xmlparser(); $array = $xmlParser->GetXMLTree($ats); //$xmlParser->printa($array); if(count($array['ERROR'])) { // If it is error $error = new error(); $error->number = $array['ERROR'][0]['NUMBER'][0]['VALUE']; $error->source = $array['ERROR'][0]['SOURCE'][0]['VALUE']; $error->description = $array['ERROR'][0]['DESCRIPTION'][0]['VALUE']; $error->helpcontext = $array['ERROR'][0]['HELPCONTEXT'][0]['VALUE']; $error->helpfile = $array['ERROR'][0]['HELPFILE'][0]['VALUE']; $this->error = $error; } else if(count($array['RATEV2RESPONSE'][0]['PACKAGE'][0]['ERROR'])) { $error = new error(); $error->number = $array['RATEV2RESPONSE'][0]['PACKAGE'][0]['ERROR'][0]['NUMBER'][0]['VALUE']; $error->source = $array['RATEV2RESPONSE'][0]['PACKAGE'][0]['ERROR'][0]['SOURCE'][0]['VALUE']; $error->description = $array['RATEV2RESPONSE'][0]['PACKAGE'][0]['ERROR'][0]['DESCRIPTION'][0]['VALUE']; $error->helpcontext = $array['RATEV2RESPONSE'][0]['PACKAGE'][0]['ERROR'][0]['HELPCONTEXT'][0]['VALUE']; $error->helpfile = $array['RATEV2RESPONSE'][0]['PACKAGE'][0]['ERROR'][0]['HELPFILE'][0]['VALUE']; $this->error = $error; } else if(count($array['INTLRATERESPONSE'][0]['PACKAGE'][0]['ERROR'])){ //if it is international shipping error $error = new error($array['INTLRATERESPONSE'][0]['PACKAGE'][0]['ERROR']); $error->number = $array['INTLRATERESPONSE'][0]['PACKAGE'][0]['ERROR'][0]['NUMBER'][0]['VALUE']; $error->source = $array['INTLRATERESPONSE'][0]['PACKAGE'][0]['ERROR'][0]['SOURCE'][0]['VALUE']; $error->description = $array['INTLRATERESPONSE'][0]['PACKAGE'][0]['ERROR'][0]['DESCRIPTION'][0]['VALUE']; $error->helpcontext = $array['INTLRATERESPONSE'][0]['PACKAGE'][0]['ERROR'][0]['HELPCONTEXT'][0]['VALUE']; $error->helpfile = $array['INTLRATERESPONSE'][0]['PACKAGE'][0]['ERROR'][0]['HELPFILE'][0]['VALUE']; $this->error = $error; } else if(count($array['RATEV2RESPONSE'])){ // if everything OK //print_r($array['RATEV2RESPONSE']); $this->zone = $array['RATEV2RESPONSE'][0]['PACKAGE'][0]['ZONE'][0]['VALUE']; foreach ($array['RATEV2RESPONSE'][0]['PACKAGE'][0]['POSTAGE'] as $value){ $price = new price(); $price->mailservice = $value['MAILSERVICE'][0]['VALUE']; $price->rate = $value['RATE'][0]['VALUE']; $this->list[] = $price; } } else if (count($array['INTLRATERESPONSE'][0]['PACKAGE'][0]['SERVICE'])) { // if it is international shipping and it is OK foreach($array['INTLRATERESPONSE'][0]['PACKAGE'][0]['SERVICE'] as $value) { $price = new intPrice(); $price->id = $value['ATTRIBUTES']['ID']; $price->pounds = $value['POUNDS'][0]['VALUE']; $price->ounces = $value['OUNCES'][0]['VALUE']; $price->mailtype = $value['MAILTYPE'][0]['VALUE']; $price->country = $value['COUNTRY'][0]['VALUE']; $price->rate = $value['POSTAGE'][0]['VALUE']; $price->svccommitments = $value['SVCCOMMITMENTS'][0]['VALUE']; $price->svcdescription = $value['SVCDESCRIPTION'][0]['VALUE']; $price->maxdimensions = $value['MAXDIMENSIONS'][0]['VALUE']; $price->maxweight = $value['MAXWEIGHT'][0]['VALUE']; $this->list[] = $price; } } return $this; } } class error { var $number; var $source; var $description; var $helpcontext; var $helpfile; } class price { var $mailservice; var $rate; } class intPrice { var $id; var $rate; } ?> This is how Im getting the info Code: [Select] <?php require("usps.php"); $usps = new USPS; //http://production.shippingapis.com/ShippingAPI.dll //http://testing.shippingapis.com/ShippingAPITest.dll $usps->setServer("http://production.shippingapis.com/ShippingAPI.dll"); $usps->setUserName("****"); //Express, First Class, Priority, Parcel, Library, BPM, Media, or ALL $usps->setService("All"); $usps->setDestZip("21061"); $usps->setOrigZip("85284"); $usps->setWeight(4, 2); $usps->setContainer("Flat Rate Box"); $usps->setCountry("USA"); $usps->setMachinable("true"); $usps->setSize("Regular"); $price = $usps->getPrice(); print_r($price); ?>and that gives me this result Code: [Select] USPS Object ( [server] => http://production.shippingapis.com/ShippingAPI.dll [user] => **** [pass] => **** [service] => All [dest_zip] => 21061 [orig_zip] => 85284 [pounds] => 4 [ounces] => 2 [container] => Flat Rate Box [size] => Regular [machinable] => true [country] => USA [zone] => 8 [list] => Array ( [0] => price Object ( [mailservice] => Express Mail Hold For Pickup [rate] => 49.70 ) [1] => price Object ( [mailservice] => Express Mail [rate] => 49.70 ) [2] => price Object ( [mailservice] => Express Mail Flat Rate Envelope Hold For Pickup [rate] => 18.30 ) [3] => price Object ( [mailservice] => Express Mail Flat Rate Envelope [rate] => 18.30 ) [4] => price Object ( [mailservice] => Priority Mail [rate] => 18.35 ) [5] => price Object ( [mailservice] => Priority Mail Flat Rate Envelope [rate] => 4.95 ) [6] => price Object ( [mailservice] => Priority Mail Small Flat Rate Box [rate] => 5.20 ) [7] => price Object ( [mailservice] => Priority Mail Medium Flat Rate Box [rate] => 10.95 ) [8] => price Object ( [mailservice] => Priority Mail Large Flat Rate Box [rate] => 14.95 ) [9] => price Object ( [mailservice] => Parcel Post [rate] => 12.29 ) [10] => price Object ( [mailservice] => Media Mail [rate] => 4.05 ) [11] => price Object ( [mailservice] => Library Mail [rate] => 3.85 ) ) ) I would like to be able to just pull out some of the mailservice and rate portions to use them later on in the form, like say a dropdown box but I do not know how to just isolate each item. For instance turn that result into a 3 item select box with these options Express Mail - $49.70 Priority Mail - $18.35 Parcel Post - $12.29 Hope that makes sense. Any help appreciated. So I am accessing a web service and it returns a bunch of values, I am able to grab and print the first value, but I can't figure out how to print the second value. PHP Code that works Code: [Select] <?php //Web service that works fine $client = new SoapClient("http://www.domain.com/sc001.asmx?WSDL"); $sc001 = $client->$NT(array('var1'=>$var1)); //Grab the value tag and print it from web service call and in this case prints 001 $tag = $sc001->NTResult->results->TaggedText->tag; echo $tag; ?> But how do I get it to print the second tag that equals 120? I've tried this Code: [Select] <?php $tag2 = $sc001->NTResult->taggedResults->tag; ?> and this Code: [Select] <?php $tag2 = $sc001->NTResult->taggedResults->TaggedText->tag; ?> and this Code: [Select] <?php $tag2 = $sc001->NTResult->results->TaggedText->taggedResults->TaggedText->tag; ?> But neither work. The var_dump for is sc001 is: Code: [Select] object(stdClass)#9 (1) { ["NTResult"]=> object(stdClass)#10 (2) { ["count"]=> int(1) ["results"]=> object(stdClass)#11 (1) { ["TaggedText"]=> object(stdClass)#12 (2) { ["tag"]=> string(3) "001" ["taggedResults"]=> object(stdClass)#13 (1) { ["TaggedText"]=> array(27) { [0]=> object(stdClass)#14 (2) { ["tag"]=> string(4) "120" ["textArray"]=> object(stdClass)#15 (1) { ["string"]=> array(2) { [0]=> string(28) "Rocks " [1]=> string(14) "Big Rocks" } } } } } } } } } } } and the XML return from the service is: Code: [Select] <?xml version="1.0" encoding="utf-8" ?> - <TaggedTextArray xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.domain.com/sc001"> <count>1</count> - <results> - <TaggedText> <tag>001</tag> - <taggedResults> - <TaggedText> <tag>120</tag> - <textArray> <string>Rocks</string> <string>Big Rocks</string> </textArray> </TaggedText> Maybe the question is, how do you handle a SOAP returned array? I'm not sure, any help is appreciated. Thanks, sanchez Am currently using this code, and actually thinking about it should split the query to an include in order to allow for other database drivers, on the chance we may decide to ditch the old MySQL. But I digress from the question. Code: [Select] include($lib."dbconfig.php"); $q = 'SELECT * FROM file WHERE this = "'.$that'"; $result = mysql_query($q); if (mysql_num_rows($result) > 0) If the query doesn't pick up a row I'm getting this error yo, Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in D:\webpages\*\*\admin.php on line 553 So what would be a better way of testing if the query was successful? |