PHP - Getting Objects From Array Of Database Results
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. Similar TutorialsHello all!
I have this array of objects:
Array ( [0] => stdClass Object ( [first_name] => test [last_name] => test [title] => test [id] => 34 [type] => 4 [manager] => 4 [email] => p@yahoo.com [date] => 2014-09-21 07:23:12 [status] => 2 [approval_date] => 2014-09-21 07:31:10 [assessment_id] => 1 [supervisor_approval] => 1 [manager_approval_date] => 2014-09-21 07:31:27 [mainmanger] => 3 ) [1] => stdClass Object ( [first_name] => test [last_name] => test [title] => test [id] => 34 [type] => 4 [manager] => 4 [email] => p@yahoo.com [date] => 2014-09-20 07:39:55 [status] => 2 [approval_date] => 2014-09-20 07:40:41 [assessment_id] => 3 [supervisor_approval] => 1 [manager_approval_date] => 2014-09-20 07:41:07 [mainmanger] => 3 ) [2] => stdClass Object ( [first_name] => jimmy john john [last_name] => john [title] => Lorad and Master [id] => 32 [type] => 4 [manager] => 3 [email] => j@j.com [date] => 2014-09-21 07:38:50 [status] => 2 [approval_date] => 2014-09-19 07:39:25 [assessment_id] => 2 [supervisor_approval] => 1 [manager_approval_date] => 2014-09-19 07:39:25 [mainmanger] => 0 ) )Where "id" = the user ID. If there are two or more entries for a user, I want to remove all but the most recent by the "approval_date",... So for the above example it would return: Array ( [0] => stdClass Object ( [first_name] => test [last_name] => test [title] => test [id] => 34 [type] => 4 [manager] => 4 [email] => piznac@yahoo.com [date] => 2014-09-21 07:23:12 [status] => 2 [approval_date] => 2014-09-21 07:31:10 [assessment_id] => 1 [supervisor_approval] => 1 [manager_approval_date] => 2014-09-21 07:31:27 [mainmanger] => 3 ) [1] => stdClass Object ( [first_name] => jimmy john john [last_name] => john [title] => Lorad and Master [id] => 32 [type] => 4 [manager] => 3 [email] => j@j.com [date] => 2014-09-21 07:38:50 [status] => 2 [approval_date] => 2014-09-19 07:39:25 [assessment_id] => 2 [supervisor_approval] => 1 [manager_approval_date] => 2014-09-19 07:39:25 [mainmanger] => 0 ) )I'm having a hard time wrapping my head around this concept, so I don't have any example code. And I don't really need or expect someone to code this for me,. just a push in the right direction would be awesome. Our product is running on LAMP(PHP) architecture. For MySQL operation PDO library has been used. We are in the process of moving the product to a new Linux server. On the new server we are facing MySQL query output related issue. At the end of the post I have listed the server configuration details of both the servers and the sample PHP program with the output. It works fine in server 1 but when the same code moved to Server 2, the output is not correct. Would appreciate any points to solve this problem The following piece of code is tested and output is also given. <?php /*** mysql hostname ***/ $hostname = 'localhost'; /*** mysql username ***/ $username = 'ram'; /*** mysql password ***/ $password = 'tellmehow'; try { $dbh = new PDO("mysql:host=$hostname;dbname=inhouse", $username, $password); $sql = "SELECT first_name,last_name,user_id,email FROM users LIMIT 1"; $stmt = $dbh->prepare($sql,array(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => TRUE)); $stmt->execute(); $result = $stmt->fetch(PDO::FETCH_OBJ); $stmt->closeCursor(); /*foreach($result as $key=>$val) { echo $key.' - '.$val.'<br />'; }*/ print_r($result); $dbh = null; } catch(PDOException $e) { echo $e->getMessage(); } ?> Output for server 1: stdClass Object ( [first_name] => super [last_name] => admin [user_id]=>1 [email] => ram@greynium.com ) output for server 2: stdClass Object ( [first_name] => super [last_name] => admin [users] => ram@greynium.com ) On server 2 I am not getting the output for field 'user_id' from the table 'users'. For the field 'email' from 'users' table, it is displaying the name of the table itself (users). Not sure what is wrong. The configuration of the servers are given below Server 1 -------- OS Details: Linux 2.6.9-5.ELsmp PHP Details: PHP 5.2.3 (cli) (built: Aug 28 2007 11:48:30) Copyright (c) 1997-2007 The PHP Group Zend Engine v2.2.0, Copyright (c) 1998-2007 Zend Technologies with Suhosin v0.9.22, Copyright (c) 2007, by SektionEins GmbH PDO details: PDO PDO support => enabled PDO drivers => sqlite2, sqlite, mysql PDO Driver for MySQL, client library version => 5.0.37 PDO Driver for SQLite 3.x => enabled Server 2 --------- OS Details: Linux 2.6.18-8.el5 PHP Details: eAccelerator requires Zend Engine API version 220060519. The Zend Engine API version 220090626 which is installed, is newer. Contact eAccelerator at http://eaccelerator.net for a later version of eAccelerator. PHP 5.3.2 (cli) (built: Jul 6 2010 17:57:31) Copyright (c) 1997-2010 The PHP Group Zend Engine v2.3.0, Copyright (c) 1998-2010 Zend Technologies PDO Details: PDO PDO support => enabled PDO drivers => mysql, sqlite, sqlite2 PDO Driver for MySQL => enabled PDO Driver for SQLite 3.x => enabled What is the better way, in terms of best practice and also speed of storing PHP objects in a database? Is it: Serialize Code: [Select] $SQL = "INSERT INTO my_table (my_object) VALUES ('" . seralize($php_object). "')"; OR JSON Code: [Select] $SQL = "INSERT INTO my_table (my_object) VALUES ('" . json_encode($php_object). "')"; Any idea which is faster serialize() / unserialize() or json_ecode() / json_decode()? Hi I am trying to connect to my database but i am having some problems where the server( WAMP) crashes and does not load this page. here is the php coding
<?php $db = new PDO("mysql:host=localhost;dbname=test;port=80", "root", ""); var_dump($db);when i run this no error comes the page doesnt load. anyone know why? when using PDO do i have to do some sort of configuration changes to wamp? i have even changed the directory of the file and still same issue. any suggestions would be wonderful. Phew, okay, I'm at my wits end on how to accomplish this task. My client wants a forum program, but she wants it different from normal in that the forum page won't show just the main threads where you would have to click to see the replies, etc - she wants the forum page to display threads and replies in a tiered fashion. Something like this: Code: [Select] - Thread 1 - Reply 1-1 - Reply 1-1-1 - Reply 1-2 - Reply 1-3 - Reply 1-3-1 - Reply 1-3-1-1 - Reply 1-3-1-1-1 - Reply 1-3-1-2 - Reply 1-3-2 - Thread 2 - Thread 3 - Reply 3-1 etc So, the threads should be arranged in order of their property timeLastChanged (which is updated on replies to it, replies to replies of it, edits, etc) which produces the "bumping" functionality. Then the replies under it should be arranged in order of their property timeStarted (which is the timestamp of when it got created). Now, I have the script so far to the point where I have 3 arrays of objects (stickyObjs, mainsObjs, replyObjs) and these objects are instances of Post with their properties being their database values (author, timeStarted, subject, etc). Now, I have thought to arrange these arrays into one big array of objects in the order that they should appear on the page (don't worry about the indent, that's done elsewhere.) Anyway, how would I go about sorting these arrays into one big array of objects in the order they should appear with those two sorting criteria above (sorting criteria is stickies, 1st main in the order of last available timeLastChanged, any replies to mains, replies to replies, ad nauseum in order of timeStarted, then the next main in the order of timeLastChanged, etc.) I have gone through many possible ways, all of which are incredibly complex and involve many copies of arrays and pointers to objects in arrays and iteration counters and GAH! Does anyone know of an easy way to accomplish this sorting? Here is what I have so far: Code: [Select] class Category { public $title; public $majCatID; public $catID; public $modLevel; public $postingLevel; public $hostedByUID; public $order; public $shortName; public $info; public $stickyObjs; public $mainsObjs; public $replyObjs; private $database; public function __construct($catID) { $this->database = new TBDatabase; $result = $this->database->getIntRow(CAT_TABLE, 'catID', $catID); $row = $this->database->fetchAssoc($result); $this->title = $row['title']; $this->majCatID = $row['majCatID']; $this->catID = $row['catID']; $this->modLevel = $row['modLevel']; $this->postingLevel = $row['postingLevel']; $this->hostedByUID = $row['hostedByUID']; $this->order = $row['order']; $this->shortName = $row['shortName']; $this->info = $row['info']; $this->pointer = 0; } public function sortPosts() { $table = $this->shortName."_threads"; $this->getStickyObjs(); $numStickies = count($this->stickyObjs); $this->getMainObjs(); $numMains = count($this->mainsObjs); $this->getReplyObjs(); $numReplies = count($this->replyObjs); } private function getStickyObjs() { $result = $this->database->getPostResources($this->shortName, $this->catID, "AND isSticky = 1"); if (!$result) { $this->stickyObjs = false; return; } $i = 1; while ($row = $this->database->fetchAssoc($result)) { $this->stickyObjs[$i] = new Post($row); $i++; } return; } private function getMainObjs() { $result = $this->database->getPostResources($this->shortName, $this->catID, "AND isReply = 0"); if (!$result) { $this->mainsObjs = false; return; } $i = 1; while ($row = $this->database->fetchAssoc($result)) { $this->mainsObjs[$i] = new Post($row); $i++; } return; } private function getReplyObjs() { $result = $this->database->getPostResources($this->shortName, $this->catID, "AND isReply != 0"); if (!$result) { $this->replyObjs = false; return; } $i = 1; while ($row = $this->database->fetchAssoc($result)) { $this->replyObjs[$i] = new Post($row); $i++; } return; } } Thanks! Originally, I would get both, and unfortunately would inconsistently use both. Then, I wanted more consistently, so configured php.ini to only return objects as I felt accessing them was more concise. And then later, I found myself needing arrays more often, and initially would just typecast them to arrays but eventually my standard was to set the PDO's fetch style to an array. And now I find myself almost always explicitly requesting arrays and occasionally requesting columns or named values. Do you configure ATTR_DEFAULT_FETCH_MODE, and if so to what? PS. Anyone use FETCH_CLASS, FETCH_INTO or FETCH_NUM? If so, what would be a good use case? 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? 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 } ?> 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 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 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 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 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. 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 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>"; ?> 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>'; } ?> This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=321088.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 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 |