PHP - How Do I Paginate Results From Sql Database
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 } ?> Similar TutorialsHey 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()); } <?php $image_url = 'images/'; //User defined variables for page settings $rows_per_page = 2; $cols_per_page = 4; //Master array of ALL the images in the order to be displayed $images = array( 'image1.jpg', 'image2.jpg', 'image3.jpg', 'image4.jpg', 'image5.jpg', 'image6.jpg', 'image7.jpg', 'image8.jpg', 'image9.jpg', 'image10.jpg', 'image11.jpg', 'image12.jpg', 'image13.jpg', 'image14.jpg', 'image15.jpg', 'image16.jpg', 'image17.jpg', 'image18.jpg', 'image19.jpg' ); //END USER DEFINED VARIABLES //System defined variable $records_per_page = $rows_per_page * $cols_per_page; $total_records = count($images); $total_pages = ceil($total_records / $records_per_page); //Get/define current page $current_page = (int) $_GET['page']; if($current_page<1 || $current_page>$total_pages) { $current_page = 1; } //Get records for the current page $page_images = array_splice($images, ($current_page-1)*$records_per_page, $records_per_page); //Create ouput for the records of the current page $ouput = "<table border=\"1\">\n"; for($row=0; $row<$rows_per_page; $row++) { $ouput .= "<tr>\n"; for($col=0; $col<$cols_per_page; $col++) { $imgIdx = ($row * $rows_per_page) + $col; $img = (isset($page_images[$imgIdx])) ? "<img src=\"{$image_url}{$page_images[$imgIdx]}\" />" : ' '; $ouput .= "<td>$img</td>\n"; } $ouput .= "</tr>\n"; } $ouput .= "</table>"; //Create pagination links $first = "First"; $prev = "Prev"; $next = "Next"; $last = "Last"; if($current_page>1) { $prevPage = $current_page - 1; $first = "<a href=\"test.php?page=1\">First</a>"; $prev = "<a href=\"test.php?page={$prevPage}\">Prev</a>"; } if($current_page<$total_pages) { $nextPage = $current_page + 1; $next = "<a href=\"test.php?page={$nextPage}\">Next</a>"; $last = "<a href=\"test.php?page={$total_pages}\">Last</a>"; } ?> <html> <body> <h2>Here are the records for page <?php echo $current_page; ?></h2> <ul> <?php echo $ouput; ?> </ul> Page <?php echo $current_page; ?> of <?php echo $total_pages; ?> <br /> <?php echo "{$first} | {$prev} | {$next} | {$last}"; ?> </body> </html> This current code provides an easy way of uploading pictures and having the other pictures move automatically without the need of a database. But I must wonder, if doing this on a database would be faster. Would it be? I mean the example adobe shows I'm only using 19 pictures, but if I ever reach say 1000 pictures, would the php file be too big? Should I just make a database now or it doesn't matter? Also, the code above, which I took from a phpfreak member, has the pagination not working. Anyone care to do a diagnosis? Thanks! Hello all, I am making a database with all the Boeing deliveries sorted by month. I made a index with all the months and when you click on a month you will get a full list of the type and quantity of aircraft that has been deliverd. I have two problems and I can't figure it out. The first problem I have, is that I want to show the visitors which airline has bougt which type of aircraft and how many. The second problem I have is a want to show them the total amount of deliveries, not just per type of aircraft, but a total number. Here are some shots of my problem and what I have: This is how my MYSQL-database lookes like. The columns I have a id, day, month, year, airline, aircraft, amount (just a simple translation of the Dutch words ). As you can see, there are some airlines that received one type of aircraft two times (TUI Travel PLC has received 2x Boeing 737-800). Keep this in mind, I will get back to this. This is the table on my website. The first column shows the type of aircraft. The secon column shows us how many of that type has been deliverd. In the last column I want to have all the airlines that has received that type of aircraft. As I mentioned above, TUI Travel PLC has received 2x B737-800, so in the row of B737-800 I want to have TUI Travel PLC (2x). If the airline received more then 1 aircraft, I would like to have (.....x) (and the amount on the dots --> TUI example: 2 aircraft, so 2x). So you will get TUI Travel PLC (2x). This is the code I have so far (sorry I am a real noobie in PHP/MYSQL so my programming ain't that great ) Code: [Select] <?php mysql_connect(".....", ".....", ".....") or die(mysql_error()); mysql_select_db(".....") or die(mysql_error()); $maand = $_GET['maand']; $jaar = $_GET['jaar']; $query = "SELECT aircraft, jaar, maatschappij, COUNT(maatschappij) FROM deliveries_orders_boeing WHERE maand = '$maand' AND jaar = '$jaar' GROUP BY aircraft"; $result = mysql_query($query) or die(mysql_error()); // Print out result echo "<br /><h3>Boeing deliveries ".$maand." ".$jaar."</h3><br /> <table border='0' width='700'>"; while($row = mysql_fetch_array($result)){ echo "<tr><td id='aircraft'>". $row['aircraft']. "</td><td id='aantal'>". $row['COUNT(maatschappij)'] ."</td><td id='maatschappijen'>different companies</td></tr>"; } echo "<tr><td id='totaal'>Totaal</td><td id='totaal_aantal'>....</td><td></td></tr></table>"; ?> </td> </tr> </table> Maybe a little confusing, but I hope someone can help me with this. Kind regards, Flyboeing Hi Guys I have a product page in mysql as below: id itemnumber order_id 1 348939012 2 2 535432454 1 3 543253424 4 4 987698769 3 I need to order this in my PHP mysql_fetch_assoc by order id. What I mean is I need to list them by order_id: 1,2,3,4 I have used ORDER BY order_id but still it wont work, any ideas? Hi I have got results being displayed after clicking the search button in a form on my home page but it brings up all the results which is ok but how do I get onlt the results a user searches for for example a location or property type etc as its for a property website The coding is below for the results page Also sorry how do I add a background image to the php page, I tried using css but wouldn't work Code: [Select] <style type="text/css"> body {background-image:url('images/greybgone.png');} </style> <?php mysql_connect ("2up2downhomes.com.mysql", "2up2downhomes_c","mD8GsJKQ") or die (mysql_error()); mysql_select_db ("2up2downhomes_c"); echo $_POST['term']; $sql = mysql_query("select * from properties where typeProperty like '%$term%' or location like '%$term%'"); while ($row = mysql_fetch_array($sql)){ echo 'Type of Property: '.$row['typeProperty']; echo '<br/> Number of Bedrooms: '.$row['bedrooms']; echo '<br/> Number of Bathrooms: '.$row['bathrooms']; echo '<br/> Garden: '.$row['garden']; echo '<br/> Description: '.$row['description']; echo '<br/> Price: '.$row['price']; echo '<br/> Location: '.$row['location']; echo '<br/> Image: '.$row['image']; echo '<br/><br/>'; } ?> Hello all, Trying to figure out how to display database results so that they are numbered (for editing and deletion purposes). I want to be able to edit the message text and update the database information with the UPDATE command, but have not gotten that far yet. Current problem is that I am returning no results. Here is my script: Code: [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>My Profile</title> <link href="loginmodule.css" rel="stylesheet" type="text/css" /> </head> <body> <h1>My Profile </h1> <a href="member-index.php">Home</a> | <a href="member-profile.php">My Profile</a> | Update Posts | <a href="logout.php">Logout</a> <br /><br /> <?php $subject = $_POST['subject']; $message_text = $_POST['message_text']; //Connect to mysql server $link = mysql_connect('XXXXXX', 'XXXXXX', 'XXXXXX'); if(!$link) { die('Failed to connect to server: ' . mysql_error()); } //Select database $db = mysql_select_db('ryan_iframe'); if(!$db) { die("Unable to select database"); } // validate incoming values $subject = (isset($_GET['subject'])) ? (int)$_GET['subject'] : 0; $message_text = (isset($_GET['message_text'])) ? (int)$_GET['message_text'] : 0; ob_start(); $id = $_GET['SUBJECT']; $query = sprintf( " SELECT SUBJECT, MSG_TEXT, UNIX_TIMESTAMP(MSG_DATE) AS MSG_DATE FROM FORUM_MESSAGE WHERE SUBJECT = '$id' ORDER BY MSG_DATE DESC", DB_DATABASE, DB_DATABASE, $subject, $subject); $result = mysql_query($query) or die(mysql_error()); $num = mysql_numrows($result); mysql_close(); $i = 0; while ($i < $num) { $subject = mysql_result($result, $i, "SUBJECT"); $message_text = mysql_result($result, $i, "MSG_TEXT"); echo '<div style="width: 400px;padding:20px;">'; echo '<table border=0 width="400px">'; echo '<tr>'; echo '<td style="vertical-align:top;width:auto;">'; echo 'Date: '; echo '</td>'; echo '<td style="vertical-align:top;width:320px;">'; echo date('F d, Y', $row['MSG_DATE']) . '</td>'; echo '</tr>'; echo '<tr>'; echo '<td style="vertical-align:top;width:auto;">'; echo 'Subject: '; echo '</td>'; echo '<td style="vertical-align:top;width:320px;">'; echo '<div>' . htmlspecialchars($row['SUBJECT']) . '</div>'; echo '</td>'; echo '</tr>'; echo '<tr>'; echo '<td style="vertical-align:top;width:auto;">'; echo 'Message: '; echo '</td>'; echo '<td style="vertical-align:top;width:320px;">'; echo '<div>' . htmlspecialchars($row['MSG_TEXT']) . '</div>'; echo '</td>'; echo '</tr>'; echo '<tr>'; echo '<td style="vertical-align:top;width:auto;">'; echo '</td>'; echo '<td style="vertical-align:top;width:320px;text-align:center;">'; echo '<form method="post">'; echo '<input type="hidden" name="update" value="true" />'; echo '<input type="submit" value="Update" />'; echo ' '; echo '<input type="hidden" name="delete" value="true" />'; echo '<input type="submit" value="Delete" />'; echo '</form>'; echo '</td>'; echo '</tr>'; echo '</table>'; echo '<br />'; echo '<hr />'; echo '</div>'; ++$i; } ?> </body> </html> Thanks in advance. Ryan I've been trying to fix this piece of script so i can query the results from a database. What i want to do is to display the results from the database like below: Product Heading price Subproduct - $price Each item would have a check box next to them. I have managed to display the items but not the prices. I've looked over the code several times but i'm lost on what i should do. Anyway here's the code, i hope someone here can view it and let me know what i'm doing wrong or what i'm not doing. <?php $get_cats = "SELECT * FROM sub_service WHERE industry='$industry'"; $run_get = mysql_query($get_cats) or die(mysql_error()); $tmp = array(); $x=1; while($rw = mysql_fetch_assoc($run_get)){ if (!array_key_exists($rw['service'],$tmp)) { $tmp[$rw['service']] = array(); } $tmp[$rw['service']][] = $rw['sub_service']; } foreach ($tmp as $service => $items) { ?> <div id="industry_wrapper"> <h2><?php echo $service ?></h2> </div> <div id="select_all_holder"> <div id="select_all_input"> <input type="checkbox" class="toggleElement" name="toggle" onchange="toggleStatus()" /> </div> <div id="select_all_txt"> <p>Select All Services - $</p> </div> </div> <?php echo' <div class="service_holder"> <table width="650" cellpadding="0" cellspacing="5"> '; foreach ($items as $cat) { ?> <tr> <td width="28" align="center"><input type="checkbox" /></td> <td width="605"><p><?php echo $cat ?> - $<?php echo $tmp['price']; ?></p></td> </tr> <?php } echo'</table></div>'; } ?> Hi, I'm currently learning PHP through tutorials and I am working on a webpage that filters statistics (crime records) from an SQL table and filters them by an option of years that the user has picked from a dropdown box. $desiredyear = $_POST['year'] is the year picked from the drop down box on a different page. I did not encounter any problems simply displaying the entire table until I tried to filter the crimes by year. I keep getting this error message. Warning: sqlsrv_fetch_array() expects parameter 1 to be resource, boolean given in C:\RDEUsers\NET\400792\1.php on line 40 Here is the error line. Code: [Select] while($row = sqlsrv_fetch_array($results, SQLSRV_FETCH_ASSOC)) And here is my code so far Code: [Select] <?php $server = 'SQL2008'; $connectionInfo = array( "Database"=>"rde_400792"); $conn = sqlsrv_connect($server,$connectionInfo); $desiredyear = $_POST['year']; $describeQuery='select year, force, homicide from crime where year = $desiredyear '; $results = sqlsrv_query($conn, $describeQuery); echo '<table border="1" BORDERCOLOR=Black>'; echo '<tr><th bgcolor = "LightBlue">Year</th><th bgcolor = "LightBlue" >Force</th><th bgcolor = "LightBlue">Homicide</th></tr>'; while($row = sqlsrv_fetch_array($results, SQLSRV_FETCH_ASSOC)) { echo '<tr>'; echo '<td >' .$row['year'].'</td>'; echo '<td>' .$row['force'].'</td>'; echo '<td>' .$row['homicide'].'</td>'; echo '</tr>'; } echo '</table>'; sqlsrv_close($conn); Please can somebody help me fix this? It's driving me mad and I've exhausted my limited knowledge on the subject. I just don't understand what I'm doing wrong. How do I access objects inside an array of database results? I have a method that returns MySQL results as an array "$projects". Running print_r($projects) gives me this: array(1) ( "projects" => object Database_MySQL_Result(6) { protected _internal_row => integer 0 protected _query => string(875) "SELECT [skipping remainder of long query]" protected _result => resource(mysql result) protected _total_rows => integer 53 protected _current_row => integer 0 protected _as_object => string(13) "Model_Project" } ) If I do this: foreach($projects as $project) { echo $project->PROJECT_NAME; } I get "Undefined property: Database_MySQL_Result::$PROJECT_NAME" If I do this: foreach($projects as $project) { echo $project[0]; } the browser will display projects.id for the first returned row *only* echo $project[1] returns the project.id for the second row only. And so on. Each returned row contains over a dozen cells. It's almost as if I'm referring to the array incorrectly, or referring to the wrong array. I feel as though I'm making a very simple (and perhaps dumb) mistake here, but can't quite figure out what it is. Thanks. This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=321088.0 Hello everyone; I have a database with about ten thousand entries. Obviously, I'd like to paginate it. I did what I normally do in these situations: I went to Google, and started looking for sample code as a place to start. The problem is that every single sample I could find was apparently written in 1605 by Tibetan Monks or something, because absolutely none of it works. By "doesn't work" I mean "constantly throws errors denying that my Server has ever heard of the syntax being used." Now, I know the DB is set up correctly in all other respects, because I'm able to Query it for all my other processes. I can add to it, display it, edit it, and so forth, so I know it's not a basic connection problem. The errors center around counting the number of rows in the table. I'm five examples in, and so far three of them have told me that "$rows = mysql_num_rows($data)" isn't a real thing, and the other two told me that COUNT(*) "doesn't contain any data". Given that I'm clearly new at this, I'd tend to blame myself, except that I'm not writing a single line of the code. All I'm doing is using the sample code and putting in my connection/database information, using the identical connection info that I'm using to create and display the database in the first place. Soooooo.... my question is this: can anyone steer me towards a current, working sample of pagination code? I'd be forever in your debt. Thanks! Oh, here's the code that's currently failing: Code: [Select] $sql = "SELECT COUNT(*) FROM mytable"; $result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR); $r = mysql_fetch_row($result); $numrows = $r[0]; The error is: Warning: mysql_query(): supplied argument is not a valid MySQL-Link resource Kyle Hi I have been given a task to create some SQL reports. One of the reports is to display all the customers who have purchased a certain product based on user selection and then have those results able to be extracted to a mailing list. So ive got the report done. Some drop down boxes allow a user to select a product and once submitted the results are then displayed. But i dont even know where to begin with extracting those results to a mailing list. Could someone help me please? What method should I use? and where do i begin? BTW im a rookie with PHP/Mysql ive just got my first job since leaving university and this is a task ive been given at work so any quick and helpful replies are greatly appreciated Thanks in advance. Hey all, First off, if this is in the wrong section I apologize. I wasn't sure if it should be here or the mySQL section. What's going on is, I'm in the process of learning the Prepared Statement way of doing things and am changing / updating my code to reflect the changes. Everything was going fine until I attempted to do what I could do using old MySQL methods and that is display the queried results on the same page. I can place a query and display the results as they should be displayed if I only use one block of code. However, if I try to do any additional queries on the same page, they get killed and do not display anything even though I know the query is fine because I can test the exact same syntax below one a different page and it works. Here's a code snippet for an example: Code: [Select] Code: <table> <tr> <td> // The below code will display a selection box containing various strings such as "hello world", "great to be here", "Wowserz", "this is mind blowing" etc. that are stored in the database. <?php echo "<select = \"SpecialConditions\">"; if($stmt->num_rows == NULL){ echo "No results found."; }else{ while($stmt->fetch()){ echo "<option value=\"$specialId\">$specialcondition</option>"; } } echo "</select>"; ?> </td> <td> // If I place another fetch query below the above fetch() query, this one will not show up. This one is supposed to display values 1 - 20 that have been stored in the DB. <?php echo "<select = \"NumberSets\">"; if($stmt->num_rows == NULL){ echo "No results found."; }else{ while($stmt->fetch()){ echo "<option value=\"".$numbers."\">".$numbers."</option>"; } } echo "</select>"; ?> </td> </tr> </table> What am I doing wrong with this? When I use regular SQL queries I can display multiple results on the same page. The results are being pulled from two separate joined tables but I don't think that's the issue. Well, the title says it all, I do have a class named Database and one Users with multiple methods (code below). When i do try to use one user method (find_all) it returns 2 identical results from the database (and there is only one record in the DB). I tried to spot some mistake in the code but i couldn't find it, if you find something please tell... Database Class: Code: [Select] <?php /** * Class Name: MySQLDatabase * * Most of the methods in this class are * database-neutral methods for code reusability. * * Author: hisk */ require_once("config.php"); class MySQLDatabase { private $connection; private $last_query; private $magic_quotes_active; private $real_escape_string; function __construct() { $this->open_connection(); $this->magic_quotes_active = get_magic_quotes_gpc(); $this->real_escape_string = function_exists("mysql_real_escape_string"); } public function open_connection() { $this->connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS); if(!$this->connection) { die("Database connection failed: " . mysql_error()); } else { $db_select = mysql_select_db(DB_NAME, $this->connection); if (!$db_select) { die("Database selection failed: " . mysql_error()); } } } public function close_connection() { if(isset($this->connection)) { mysql_close($this->connection); unset($this->connection); } } public function query($sql) { $this->last_query = $sql; $result = mysql_query($sql, $this->connection); $this->confirm_query($result); return $result; } private function confirm_query($result) { // usable only in query() function (private) if(!$result) { echo "DB Query Failed: " . mysql_error(); // The last query that might got us the problem echo "Last Query Was: " . $this->last_query; } } // agnostic public function num_rows($result) { return mysql_num_rows($result); } public function affected_rows($result) { return mysql_affected_rows($result); } public function insert_id($result) { return mysql_insert_id($result); } public function fetch_array($result) { return mysql_fetch_array($result); } public function escape_value($value) { if($this->real_escape_string) { // undo any magic quote effect so mysql_real_esc_str can work if($this->magic_quotes_active) { $value = stripslashes($value);} $value = mysql_real_escape_string($value); } else { if (!$this->magic_quotes_active) { $value = addslashes($value); } } return $value; } } $database = new MySQLDatabase(); ?> User Class: Code: [Select] <?php // smart to include the database class require_once("database.php"); class User { public static function find_by_id($id=0) { global $database; $result_set = self::find_by_sql("SELECT * FROM users WHERE id = {$id}"); $result = $database->fetch_array($result_set); return $result; } public static function find_all() { global $database; $result_set = self::find_by_sql("SELECT * FROM users"); return $result_set; } public static function find_by_sql($sql="") { global $database; $result_set = $database->query($sql); return $result_set; } } ?> TEST FILE: Code: [Select] <?php require_once("../includes/database.php"); require_once("../includes/user.php"); $users = User::find_all(); $result = $database->fetch_array($users); foreach($result as $user) { echo "<pre>" . $user . "</pre>"; } ?> Hi All, Its been a while since i've posted, its good to be back. I am currently trying to pull two exchange rates against the $ using YQL's restful url. Unfortunately I am having a huge problem returning the results correct.... currently my array will only output a single rate (instead of two) and the hash array returns with the base rate name rather than the expected currency code. I hope someone can help me sort this as it's given me quite a headache! Please see the code below: Code: [Select] <?php require_once('uwe_proxy.php'); /* * To change this template, choose Tools | Templates * and open the template in the editor. */ # use the yahoo YQL rest service to return any number of rates in a hash function get_yahoo_rest_rate ($base, $curr_arr) { $params = ''; $rates = array(); # define the YQL rest url head & tail $yql_base_uri = "http://query.yahooapis.com/v1/public/yql"; $yql_tail_uri = '&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys'; # build up the $params value foreach($curr_arr as $curr) { $params .= $curr.$base.','; } #strip last comma $params = substr($params, 0, -1); # build the query with the params as comma sep. string eg. USDGBP,USDBOB,.. $yql_query = "select * from yahoo.finance.xchange where pair IN ('{$params}')"; # build the the complete YQL query $yql_query_url = $yql_base_uri . "?q=" . urlencode($yql_query) . $yql_tail_uri; # send the query via proxy and get as string and load as simplexml object $yql_response = @simplexml_load_string(file_get_contents_proxy($yql_query_url)); Print_r($yql_query_url); //- debugging only # process simplexml object and return a sorted hash of rates or FALSE on error if ($yql_response) { foreach($yql_response->results->rate as $rate) { if ((float)$rate->Rate>0) { $rates[substr((string)$rate->attributes()->id, -3)] = (float)$rate->Rate; } } ksort($rates); return $rates; } else { return FALSE; }// print_r($yql_response); - debugging only } /////// - debugging only $curr_arr = array('GBP','GBP'); $rates = get_yahoo_rest_rate ('USD', $curr_arr); //PRINT_R($yql_response); print_r($rates); ?> Sorry about dumping the whole lot - but I really don't know where this is going wrong! Thanks in Advance for any help or pointers in the right direction! Hello people, currently i ran into some problem. Currently, i have a database called responses which have the fields of ID, Student_id, question_id, Answer. I had stored my results into the database which appeared to be 1 1 1 Agree 2 1 2 Disagree 3 3 4 Unsatisfied. So any recommendation on how should i do about in generating the result into a graph whereby the graph will show how many students choose "AGree" on that particular question THANKS This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=347091.0 Hi, This has been baffling me for a couple hours now and i cant seem to figure it out. I have some code which creates an array and gets info from a mysql database and then displays in a list. This works great but after adding more and more rows to my database the list is now becoming quite large and doesnt look great on my site. Is it possible to split the list into multiple columns of about 25 and if possible once 3 or 4 columns have been created start another column underneath. To help explain i would be looking at a layout as follows: Code: [Select] line 1 line 1 line 1 line 2 line 2 line 2 ... ... ... line 25 line 25 line 25 line 1 line 1 line 1 line 2 line 2 line 2 ... ... ... line 25 line 25 line 25Im guessing there should be some sort of if statement to check how many items are being displayed and to create a new column if necessary. Is this correct? Thanks, Alex Say a user puts in a support request, and for every request it generates a unqiue string, and enters it into the database. Ok, now say there is a text field, when the user enters their unique string and it finds a match, it displays the data along with it. How can I accomplish this? Im kind of new to mysql, but I know basic SQL. Would be great if somebody could point me in the right direction! Thanks |