PHP - When Could Database Queries Be Reduced?
Let me give you a couple of examples.
For the first example, I have a table which includes all the pages I have on a website, and includes information about them such as some directory path, the minimum user access level to view, etc. The only time it will change is if I add a page or modify settings on an existing one. Instead of performing the query each time, maybe I should do it once for each user session and store the results in a session array? But if I do, how do I force a reload should I ever make a change. Or maybe I should do it once for all users, but this probably doesn't make much sense.
For a second example, I have a bunch of sites which use common code. Each has their own subdomain which in turn identifies a primary key which with multiple joins makes each site unique. The user could change the settings, however, will rarely do so. Instead of querying the big query each time, should I store the settings in a session, and only query the database if some part of the session is not set or if the session "last_updated" value is different than that stored in the database? Yes, I will still need a query, but it will be small and hopefully more efficient).
For a third example, I have some JSON data available to the client. Most clients will cache the data, so I shouldn't have much problems there. I could also server cache it, but again, how do I know when to force a reload?
Thank you, and Happy New Year!
Similar TutorialsI have this function and for some reason it is running over 100 queries on page load. I'm not sure what I am doing wrong. Can I please get some guidance on this? Code: [Select] <?php function fetch_users($page = 1, $per_page = 20, $type = null, $country = null, $state = null) { $start = (int)(($page - 1) * $per_page); $per_page = (int)$per_page; $type = (int)$type; $country = (int)$country; $state = (int)$state; $sql = "SELECT `users`.`id`, `users`.`firstname`, `users`.`lastname`, `users`.`username`, `users`.`email`, `users`.`gender`, `users`.`accounttype`, `users`.`personalweb`, `users`.`guestviews`, `users`.`iviews`, `users`.`eviews`, `users`.`credentials`, `users`.`specialties`, `users`.`country`, `users`.`city`, `users`.`state`, `users`.`phonenumber`, `users`.`dateofbirth` AS `dob`, `users`.`mail_status`, `users`.`status`, `investor_info`.`investor_type`, DATE_FORMAT(`users`.`dateofbirth`,'%D') AS `dayofbirth`, DATE_FORMAT(`users`.`dateofbirth`,'%c') AS `monthofbirth`, DATE_FORMAT(`users`.`dateofbirth`,'%Y') AS `yearofbirth`, DATE_FORMAT(`users`.`dateofbirth`,'%D \of %M %Y') AS `dateofbirth`, DATE_FORMAT(`users`.`signupdate`,'%h:%i %p %M %e, %Y') AS `signupdate`, SUM(`investor_info`.`capital_available`) AS `totalavailable`, `companytype`, `capital` FROM `users` LEFT JOIN `investor_info` ON `users`.`id` = `investor_info`.`uid` LEFT OUTER JOIN employees ON users.id = employees.userid LEFT OUTER JOIN ( SELECT companies.companyid, companies.companytype AS `companytype`, SUM(companies.capital) AS `capital` FROM `companies` GROUP BY companies.companytype) SumCompanies ON employees.companyid = SumCompanies.companyid WHERE `users`.`status` > 2 "; if($type != null) { $acctype = $type - 1; $sql.= "AND`users`.`accounttype` = {$acctype} "; } if($country != null) { $sql.= "AND`users`.`country` = {$country} "; } if($state != null) { $sql.= "AND`users`.`state` = {$state} "; } $sql.= "GROUP BY `users`.`id` ORDER BY `users`.`id` DESC LIMIT {$start}, {$per_page}"; $result = mysql_query($sql) or die(mysql_error()); $users = array(); $i = 0; while($row = mysql_fetch_assoc($result)) { $users[$i] = array( 'id' => $row['id'], 'firstname' => $row['firstname'], 'lastname' => $row['lastname'], 'username' => $row['username'], 'email' => $row['email'], 'gender' => $row['gender'], 'accounttype' => $row['accounttype'], 'guestviews' => $row['guestviews'], 'iviews' => $row['iviews'], 'eviews' => $row['eviews'], 'credentials' => $row['credentials'], 'specialties' => $row['specialties'], 'country' => $row['country'], 'state' => $row['state'], 'city' => $row['city'], 'phonenumber' => $row['phonenumber'], 'dob' => $row['dob'], 'mail_status' => $row['mail_status'], 'status' => $row['status'], 'investor_type' => $row['investor_type'], 'dayofbirth' => $row['dayofbirth'], 'monthofbirth' => $row['monthofbirth'], 'yearofbirth' => $row['yearofbirth'], 'dateofbirth' => $row['dateofbirth'], 'signupdate' => $row['signupdate'], 'totalavailable' => $row['totalavailable'], 'companytype' => $row['companytype'], 'capital' => $row['capital'], ); $i++; } return $users; } ?> Hello, I've created a function whereby I want to return the school_id associated with a particular user. Each user will be associated with exactly one school. My query below works, but the thing that it returns is an array; I need to make use of it as a variable (say $instructor_school_id). Any idea how to make the conversion from a single element array into a non-array variable? Thank you.... function getInstructorSchool($read, $user_id) { $sql = "SELECT school_id FROM users WHERE user_id = $user_id"; return $read->fetchRow($sql); } I have been reading in Larry Ullmans book "Visual QuickPro Guide PHP 6 and MySQL 5" and I find it well-written. Since it is from 2008, it does not contain anything about MySQL PDO, but rather does it in the mysqli_* way. Larry suggest placing the secret database password and more along with a database connection script in a connect.php file, placed above the webroot if possible. Then later, when he is creating queries and executing them in other php files, he includes the connect.php file before making the queries.
Now I know it is very important to be careful with the Error handling, so the script won't output errors, which could reveal something about the database making it less secure. Therefore I am wondering how to structure things when using PDO. I need to write error-handling scripts for the following situations:
a) Connection to the database doesn't succeed
b) The execution of the queries doesn't succeed
c) User input in HTML forms are not appropriate
and probably more. The recommended way of handling errors when using PDO seems to be writing some try-catch code. But then I don't see how I can keep the connection to the database completely inside the connect.php file. Either I will need to use a die() or exit() inside this file or I will need to give up my idea to keep everything which concerns the connection to the database in the file mentioned AND write nested try-catch sentences - first make sure the connection works, then make sure the query will execute properly.
I don't like either of those approaches. Firstly I have been told that using exit() is bad programming and secondly it seems to get more complicated using nested try-catch code and to let database connection take part in diverse php-files.
Maybe somebody have a smart, convenient and secure way to do it?
Erik
As we know the total number of hits to database is proportional to the number of page views if page views * queries per page is more than the capacity of your database, then mysql queries may show problem. is there any way to calculate the database capacity ? I googled someone says 128Mb cache is there for mysql. I am just new to relational algebra probably a pre-step before learning SQL queries. Can you help me make the expressions of relational algebra expression for each of the following queries. This is the table contained inside a bus driver database.
driver ( driver_id, driver_name, age, rating ); bus ( bus_id, bus_name, color); reserves ( driver_id, bus_id, date);a. Find the names of drivers who have reserved at least three busses. b. Find the names of drivers who have reserved all busses. c. Find the names of drivers who have reserved all busses called Shuttle. d. Find the IDs of drivers whose rating is better than some driver called Paul. I would be grateful if somebody can help me here. Hey guys, i'm new to this site and would need some help with coding. So i'm making a car part website which should has brand/model search. It's a dropdown search which will get the brand / model from database and should display all the parts for that exact model, from folder. Database structure which i have is id, master, name. ( Here's some pictures to clear out what i'm doing. http://imgur.com/a/7XwVd ) So the problem is that it does not get the images from folder named ex: *_audi_a3.jpg. And link to codes what have been written already. Parts.php: http://pastebin.com/q6vdypge Update.php: http://pastebin.com/DymhGQ17 Search_images.php: http://pastebin.com/LF5Q0i8f Core.js: http://pastebin.com/bgc0y4TS I don't know what's wrong with it sadly. One thing i noticed when i used firebug it gives error on category when searching error:true. Hope you guys understand what i mean here, and also all help is appreciated. And move this post if it's in wrong place. Thanks! Edited by aeonius, 17 October 2014 - 12:15 PM. Hi im new to php and I need help making webpage that queries a mysql database based on a 3 check boxes and displays results on the same page or on another page. The table being queried has 4 columns, name, gps, wifi, bluetooth. So for example a row in the table would be like, samsung galaxy s2, yes, yes, yes. The idea is for it to be a website that will display phones according to their features. So the idea is depending on if the boxes were ticked the samsung galaxy would be displayed as a result. So i need some help understanding how to make this. Some1 gave me the code below in attempt to help me (im not sure it works or not) but im not sure how fully use it, ie what pages i need to make and how i create the connection to the mysql database, and how to use the query that they wrote to display the results thanks code: Code: [Select] <form action="?do=filter" method="post"> <table cellspacing="0" cellpadding="3" border="1"> <tr> <td>GPS<input type="checkbox" name="gps" value="checked"></td> <td>Wifi<input type="checkbox" name="wifi" value="checked"></td> <td>Bluetooth<input type="checkbox" name="bluetooth" value="checked"></td> </tr> <tr><td><input type='submit' name='filter' value='Filter'></td></tr> </table> </form> </html> <?php function filterMe($filter){ if(isset($_POST[$filter])){ return "Yes"; }else{ return "No"; } } if(isset($_POST['filter'])){ echo "Gps - " . filterMe('gps'); echo " Wifi - " . filterMe('wifi'); echo " Bluetooth - " . filterMe('bluetooth'); } ?> All you need to do is use a query something like SELECT name,gps,wifi,bluetooth FROM `product` WHERE `gps`='".filterMe('gps')."' AND `wifi`='".filterMe('wifi')."' AND `bluetooth`='".filterMe('bluetooth')."' noob question: I have following two queries I'd like to combined into one - how is this done? $temp = @mysql_query("SELECT * FROM purchased_leads WHERE leadID = '{$_REQUEST[leadid]}'"); "SELECT refundNotes FROM leads WHERE leadID = '{$_REQUEST[leadid]}'" Good day everyone. I go by the nickname Sbosh and I am a newbie in PHP. I am currently learning php using video tutorials. I need help with regards to php queries. I have the following code: "SELECT 'food', 'calories' FROM 'diet' ORDER BY 'id'" which is supposed to display content from a table inside phpmyadmin which i created manually using phpmyadmin. But It gives an error saying i must check the MariaDB version on how to right this query, something like that. Please assist on the proper way of writing this code. Again I am a newbie in PHP and just starting to learn, so your help will be highly appreciated. Hello all, I've tried several ways to calculate a commission in the multi level marketing script, but it all ended up with nothing, recursive functions, nested sets nothing worked, and i'm running out of time to keep trying I've made multiple queries on the same table, and it's working, but only the first 3 queries, not more, I tried to perform it 4 times (although I need the queries to be performed 13 times) but still only 3 times example: A recruited B and C, and B recruited D, and D recruited E.... what's supposed to happen is A takes a commission on B, C, D, and E but now it only takes commission on the first three, and no commission for anyone comes after that, and the same for B, C, D, and E each takes commission on only 3 members down the line, and no more here is the queries Code: [Select] <? $result = mysql_query("SELECT * FROM users"); echo "<table width='589' border='1'> <tr> <th>ID</th> <th>Name</th> <th>National ID</th> <th>Commission</th> </tr>"; while($row = mysql_fetch_array($result)) { $query = mysql_query("SELECT * from users where recruiteris = '".$row['id']."'"); $num_rows=mysql_num_rows($query); $id1 = $row['id']; $commission = $num_rows; $_SESSION['id1'] = $id1; echo "<tr>"; while ($roww = mysql_fetch_array($query)) { $querry=mysql_query("select * from users where recruiteris = '".$roww['id']."'"); $num_rowss = mysql_num_rows($querry); while ($rowws= mysql_fetch_array($querry)) { $var3= '10'; $querrys=mysql_query("select * from users where recruiteris = '".$rowws['id']."'"); $num_rowsss = mysql_num_rows($querrys); while ($rowwss= mysql_fetch_array($querrys)) { $querryss=mysql_query("select * from users where recruiteris = '".$rowwss['id']."'"); $num_rowssss = mysql_num_rows($querryss); while ($rowwsss= mysql_fetch_array($querryss)) { $querryr=mysql_query("select * from users where recruiteris = '".$rowwsss['id']."'"); $num_rowssr = mysql_num_rows($querryr); } } } } $total= ($commission + $num_rowws + $num_rowwss + $num_rowwsss + $num_rowss + $num_rowssr) * $var3; echo "<td><a href=\"user.php?id=".$row['id']."\">".$row['id']."</a></td>"; echo "<td>" . $row['fname'] .''. $row['lname'] ." </td>"; echo"<td> ". $row['nid'] ." </td>"; echo "<td>".$total."</td> </tr>"; } echo "</table>"; ?> ive had these queries working okay until i checked on it today, it's not working anymore.. these are the errors::: Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in C:\wamp\www\arrastre\add.php on line 105 Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in C:\wamp\www\arrastre\add.php on line 117 if(isset($_POST['add'])){ if($billnmbr=="" or $orno=="" or $payor=="" or $arrastre=="" or $wharfage=="" or $total=="" or $date=="" or $tcl==""){ echo "At least one field was left blank."; } else{ $query = mysql_query("select * from `arrastre` WHERE `billnmbr`='$billnmbr'"); /*****************this is my line 105************/ $count = mysql_num_rows($query); if($count==1){ echo "This billnumber is already in the database."; } else{ $bll = strtoupper($billnmbr); $payr = strtoupper($payor); $query="insert into `arrastre` (`billnmbr`, `orno`, `payor`, `arrastre`, `wharfage`, `total`, `date`, `tcl`) values ('$bll', '$orno', '$payr', '$arrastre', '$wharfage', '$total', '$date', '$tcl')"; $result=mysql_query($query); $query = mysql_query("select * from `arrastre` where `billnmbr`= '$billnmbr'", $link); /************and this is my line 117*************/ $count = mysql_num_rows($query); if($count==1){ echo "last bill number added: ".$billnmbr; } } Thank you very much for your time and have a nice day. Hey guys - me again! I have a discount box, where i wish to check two "if" queries. These are i) the 'uniquecode' and ii) the 'uses' - so a code can only be used a set amount of times. 1) How do i state that question in php, bearing in mind the "if uses > 0" needs to relate to the same row as the unique code entered? 2) Also, i have stored the session price in $_SESSION['sessionprice'] - is this the best way to do this, and if not how should i store the current price. 3) Lastly, and how do I do the php mathematics of "$_SESSION['sessionprice'] minus the discount" - again bearing in mind the "discount" needs to relate to the same row as the unique code entered? (as different codes will have different discounts). This is how far i've gotten: Code: [Select] <?php //connection settings bla bla bla $uniquecode = $_POST['discountcode']; mysql_connect($localhost,$username,$password); @mysql_select_db($database) or die( "Unable to select database"); $discountcodecheck = mysql_query("SELECT uniquecode FROM discounttable WHERE uniquecode = '".$uniquecode."'"); $remainingusescheck = mysql_query("SELECT uses FROM discounttable WHERE uniquecode = '".$uniquecode."'"); if (mysql_num_rows($discountcodecheck) > 0) and if (mysql_num_rows($remainingusescheck) > 0) // <-- this "and if" doesn't work { // discount calculation: // session price minus the unique code's corresponding discount // update $_session['discountammount'] } else { ?><script type="text/javascript"> alert("Discount Code Entered Is Either Not Valid Or Has Been Previously Used."); history.back(); </script><?php } // rest of code and close connection ?> Any help or comments will, as always be politely welcomed and appreciated Cheers, Tom. I need two queries cause I don't know how to put them into one. Problem here is I need to know the field Liters from the database in the first query to subtract it from the second query to be able to calculate the average fuel consumption of the chosen range.
This is my code, hope you can help
function getContent() { include 'connection.php'; $dx = date('m', strtotime('today - 30 days')); if (!isset($_POST["month_select"])) { $month = $dx; $year = "2014"; } else { $month = $_POST["month_select"]; $year = $_POST["year_select"]; } //last fuel fill value $query2 = "SELECT d.liter as FirstFill FROM members AS m LEFT OUTER JOIN diesel AS d ON d.userid = m.id WHERE YEAR(dato) = $year AND MONTH(dato) = $month AND d.liter > 0 ORDER BY d.id ASC LIMIT 1"; $sql2=$oDB->prepare($query2); $sql2->execute(); $row2 = $sql2->fetchAll(); return $row2; $FirstFill = $row2['FirstFill']; $query = "SELECT m.username, m.id, 10 * (SUM(d.liter) - $FirstFill) / (MAX(d.km) - MIN(d.km)) as AvgFuel FROM members AS m LEFT OUTER JOIN diesel AS d ON d.userid = m.id WHERE YEAR(dato) = $year AND MONTH(dato) = $month AND d.liter > 0 GROUP BY m.id ORDER BY AvgFuel ASC"; $sql=$oDB->prepare($query); $sql->execute(); $row = $sql->fetchAll(); return $row; } Edited by Aero77, 23 May 2014 - 12:39 PM. Ive just implemented a function which shows how many queries have been run on the specific page. Since the result returned 38 queries on the index page alone i need a way of listing all of these queries. I could just go through the code and find them all but there are several pages to go through. so does anyone know of a function which will list all the queries that have been run? This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=319917.0 Hi everyone I have the following PHP code $sql.= "INSERT INTO `data` (`info`, `write`, `date`) VALUES"; $sql.= "("; for ($c=0; $c < $num; $c++) { $sql.= '"'.str_replace('"', "", $data[$c]).'",'; } $sql.= "'".date('Y-m-d')."');"; If I print $sql; I get Code: [Select] INSERT INTO `data` (`info`, `write`, `date`) VALUES("data99","n",'2010-10-05'); INSERT INTO `data` (`info`, `write`, `date`) VALUES("data101","y",'2010-10-05'); INSERT INTO `data` (`info`, `write`, `date`) VALUES("data876","n",'2010-10-05'); what would I need to do to my PHP code in order for it to process each QUERY either all at once or one at a time Whatever I try, it either inserts nothing, or just does the first INSERT Any ideas? Thanks I have two seperate piece of code. One which sorts description and one which sorts price. However, I am looking to almalgamate them into one. I have tried the following however I appear to be way off. I want to select a product description with one link and then select a price range. However, I want the price range to read the description. <?phpif( isset($_GET['description' ; 'price' ])) $description = $_GET['description' ; 'price']; $query = "SELECT * FROM productfeed WHERE description like '%$description%' LIMIT 0, 10"; $query = "SELECT * FROM productfeed WHERE price like '%$price%' LIMIT 0, 10"; $fetchdata = mysql_query($query) or die("query: $query<br> This has an error: " . mysql_error() . '<br>');while($row = mysql_fetch_array($fetchdata)) { $id = $row['id']; $image = $row['awImage']; $link = $row['link']; $description = $row['description']; $fulldescription = $row['fulldescription']; $price = $row['price']; <?phpif( isset($_GET['description'])) $description = $_GET['description']; $query = "SELECT * FROM productfeed WHERE description like '%$description%' LIMIT 0, 10"; $fetchdata = mysql_query($query) or die("query: $query<br> This has an error: " . mysql_error() . '<br>');while($row = mysql_fetch_array($fetchdata)) { $id = $row['id']; $image = $row['awImage']; $link = $row['link']; $description = $row['description']; $fulldescription = $row['fulldescription']; $price = $row['price']; <?phpif( isset($_GET['price'])) $price = $_GET['price']; $query = "SELECT * FROM productfeed WHERE price like '%$price%' LIMIT 0, 10"; $fetchdata = mysql_query($query) or die("query: $query<br> This has an error: " . mysql_error() . '<br>');while($row = mysql_fetch_array($fetchdata)) { $id = $row['id']; $image = $row['awImage']; $link = $row['link']; $description = $row['description']; $fulldescription = $row['fulldescription']; $price = $row['price']; Can any boy clarify these queries. How do I find out if an array has values posted to each of its elements? I need to know that EVERY element has been filled out. How can I send variables from a PHP script to another URL using POST without using forms and hidden variables? Hi there everyone! I've got a problem combining two queries. The situation is this. I've got a list of links and I want to allow the user to get a result list of all, only unread, all in a particular category and then only unread in a particular category. My query for all: /* No filtering and no unread */ $q_urls = "SELECT * FROM shortenified_urls WHERE is_social = '1' AND active = '1' ORDER BY date_added DESC"; My query for in a particular category: /* All links in a particular category */ $q_urls = " SELECT * FROM shortenified_urls WHERE shortenified_urls.primary_cat = $vu_cat_view OR EXISTS ( SELECT link_id FROM linkcats WHERE link_id = shortenified_urls.id AND cat_id = $vu_cat_view ) AND shortenified_urls.is_social = '1' AND shortenified_urls.active = '1' ORDER BY date_added DESC" ;My query for Unread in all cats: /* Unread only for all categories */ $q_urls = "SELECT * FROM shortenified_urls WHERE shortenified_urls.date_added > $vu_mark_as_read AND NOT EXISTS ( SELECT lid FROM linkviews WHERE lid = shortenified_urls.id AND uid = $viewing_user_id ) AND shortenified_urls.is_social = '1' AND shortenified_urls.active = '1' ORDER BY date_added DESC" ; These seem to be working well. It's the next one that isn't working for me. I tried to combine the "All in a particular category" and "Unread in all categories" using the two above as starting points. The result, however, seems to be that I'm getting all in a particular category. It seems to be ignoring the unread status. /* Unread links in a particular category */ $q_urls = " SELECT * FROM shortenified_urls WHERE shortenified_urls.primary_cat = $vu_cat_view AND shortenified_urls.date_added > $vu_mark_as_read OR EXISTS ( SELECT link_id FROM linkcats WHERE link_id = shortenified_urls.id AND cat_id = $vu_cat_view ) AND NOT EXISTS ( SELECT lid FROM linkviews WHERE lid = shortenified_urls.id AND uid = $viewing_user_id ) AND shortenified_urls.is_social = '1' AND shortenified_urls.active = '1' ORDER BY date_added DESC" ;I'm not smart enough to know why it's not working, but it seems to me like I need to somehow bracket the first two parts containing the category retrieval to make this work right. The only problem is I don't know how to do that. Any help on how to get this to work would be greatly appreciated! |