PHP - Two Queries And A Variable From One To The Other
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. Similar TutorialsI am generating a few different reports through mysql querys and displaying tables. I have a mail script that stores html code into a variable called $message. How can I store all of my queried data into the variable $message? Example of one of the three tables I am displaying and I am wanting to store this whole table into the variable $message. Code: [Select] echo"<h3>Margin Less than 15% for $datequery</h3>"; echo"<table border=1 cellpadding=3><tr><td><center><b>Invoice Number</b></center></td><td><center><b>Invoice Date</b></center></td><td><center><b>Customer Number</b></center></td><td><center><b>Company</b></center></td><td><center><b>Margin</b></center></td></tr>"; while($row = mysql_fetch_array($result, MYSQL_ASSOC)) { $invoice=$row['INVNO']; $invoicedate=$row['INVDTE']; $customernumber=$row['CUSTNO']; $company=$row['COMPANY']; $invoicetotal=$row['ITOTAL']; $invoicecost=$row['ICOST']; @$ABOVE30= @($invoicecost * 100) / $invoicetotal; @$FINAL30=100 - $ABOVE30; $FINAL30=number_format($FINAL30, 2, '.', ''); IF($FINAL30<="15") { echo "<tr><td><center>$invoice</center></td><td><center>$invoicedate</center></td><td><center>$customernumber</center></td><td><center>$company</center></td><td><center>$FINAL30%</center></td></tr>"; } } echo"</table><hr />"; 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]}'" 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. 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>"; ?> 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. 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. This must be easy enough, but I'm a noob so go easy on me, please :-)
I have two pieces of code and they're working well on their own. All I need is to put these two conditions into one query.
The first one:
<?php function childtheme_cat_limited_blog( $query ) { if ( $query->is_home() && $query->is_main_query() ) { $query->set( 'events_categories', 'mycategory1' ); } } add_action( 'pre_get_posts', 'childtheme_cat_limited_blog' ); ?>And the second: <?php function childtheme_cat_limited_blog( $query ) { if ( $query->is_home() && $query->is_main_query() ) { $query->set( 'category_name', 'mycategory2' ); } } add_action( 'pre_get_posts', 'childtheme_cat_limited_blog' ); ?>I'm sure it's a piece a cake for you guys, but I can't figure it out for the life of me, so any help would be greatly appreciated! Thank you! (My goal is here to display posts from two categories on a homepage of a Wordpress site, but to complicate things the two categories are from two different post types.) I've been playing around with PDO lately, and I've been trying to get use to the basic functions as I've mentioned in some of my other posts/questions. Recently I switched to the ? bind/token (can't remember it's called), so I reformatted my processQuery. I've also tried to add in a fetching option in the method, but I can't seem to get anything to work. I've looked up several internet tutorials but it seems like I'm doing everything the same. Yet, the query doesn't seem to run. :/ $database->processQuery2("INSERT INTO test (test, testa) VALUES (?, ?)", array('noob', 'newb2'), false); Now for my method: public function processQuery2($query, array $binds, $fetch) { $query_handle = $this->dbc->prepare($query); if(count($binds) > 0) { $i = 1; $value = array(); foreach($binds as $bind) { $query_handle->bindParam($i, $value[$i]); $value[$i] = $bind; $i++; } } $query_handle->execute(); //if($fetch == true) //{ //return $query_handle->fetchAll(); //} } Any reasons to why it's not working? No errors are outputted, either. The first query goes through but the second does not just seeing if I'm missing something. <?php // Include the database page require ('../inc/dbconfig.php'); if (isset($_POST['submittitle'])) { $titlename = mysqli_real_escape_string($dbc, $_POST['titlename']); $titleshortname = mysqli_real_escape_string($dbc, $_POST['titleshortname']); $titlestyle = mysqli_real_escape_string($dbc, $_POST['titlestyle']); $titlestatus = mysqli_real_escape_string($dbc, $_POST['titlestatus']); $query = "INSERT INTO `titles` (titlename, titleshortname, style_id, status_id, creator_id, datecreated) VALUES ('$titlename','$titleshortname','$titlestyle','$titlestatus', 1, NOW())"; mysqli_query($dbc, $query); $query_id = mysqli_insert_id($dbc); $query1 = "INSERT INTO `champions` (title_id) VALUES ('$query_id')"; mysqli_query($dbc, $query1); } ?> Hi all, I've built a few amateur sites in the past but am keen to utilize php combined with mysql for my current project. However, I have little knowledge of php and am just picking it up as I go (same way I've done for all my computer knowledge) What I'm looking for may sound simple, but I really don't know where to start and I'm hoping there are some kind souls here that will lend a hand. I've got some fantastic help here before and am hoping I'll get lucky again. SQL Database meetingid venue 001 new york 002 chicago 003 new york 004 new york 005 new york 006 texas 007 texas 008 chicago 009 new york 010 new york Question If I hard code everything around it, I'm just looking for the code I would need to have it display as follows: (hard coded text in blue) "New York has been used * times." (Where * would count the number of times "New York" appears in the venue column of the database.) "The most consecutive times New York has been used is % ." (Where % would count the maximum number of consecutive times "New York" appears in the venue column of the database.) Giving the output: New York has been used 6 times. The most consecutive times New York has been used is 3. 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! I'm trying to figure out how to combine these queries, to decrease server load and load time, but I'm not so good with MySQL queries. Does anyone have any ideas, any help is greatly appreciated, I've been tinkering with this for days now.
$Actv = 0; $ActvCount = -1; $ActvUpgrade = 0; $ActvRenewal = 0; $ActvVehicleAdds = 0; $result2 = mysql_query("SELECT * FROM tblOperators WHERE OperatorLocale = 'USA' and OperatorStatus = 'ACTIVE' and Team = 'RENEWALS'"); while($row2 = mysql_fetch_array($result2)) { $operID = $row2['OperatorID']; $result = mysql_query("SELECT * FROM tblUserPayments WHERE OperatorID = '$operID' AND PaymentStatus='OK' AND PaymentDate LIKE '$currentDate%'"); while($row = mysql_fetch_array($result)) { if($row['PaymentReason'] == 'ACTIVATION'){ ++$ActvCount; //if($row['PaymentMethod'] == 'CREDITCARD'){ $ActvUpgrade += $row['ChargeAmount']; //} } elseif($row['PaymentReason'] == 'UPGRADE'){ $userid = $row['UserID']; $paymentdate = $row['PaymentDate']; $result1 = mysql_query("SELECT * FROM tblRenewalInvoices WHERE UserID='$userid' AND ('$paymentdate' >= DATE_SUB(DueDate, INTERVAL 90 DAY) AND '$paymentdate' < DATE_ADD(DueDate, INTERVAL 15 DAY)) AND ParentInvoiceID IS NULL ORDER BY InvoiceNum DESC LIMIT 1"); if( $row1 = mysql_fetch_array($result1)) { $packageid = $row['PackageID']; $pack = mysql_query("SELECT * FROM tblUserPackages WHERE PackageID='$packageid';"); if($pack1 = mysql_fetch_array($pack)){ $expDate = $pack1['ExpirationDate']; $dueDate = $row1['DueDate']; $days = mysql_fetch_row(mysql_query("SELECT TO_DAYS('$expDate')-TO_DAYS('$dueDate');")); $months = (int)( ((int)$days + 14) / 30.4); $years = (int) ( ((int)$days + 182) / 365); $Intervals = 0; if($years > 0){ $Intervals = $years; } if(($pack1['Package'] or 'GPS-SVL') or ($pack1['Package'] == 'GPS-1') or ($pack1['Package'] == 'GPS-1PLUS')){ if($Intervals > 1){ //if($row['PaymentMethod'] == 'CREDITCARD'){ $Actv += $row['ChargeAmount']; //} } else{ //if($row['PaymentMethod'] == 'CREDITCARD'){ $ActvRenewal += $row['ChargeAmount']; //} } } else{ $Actv += $row['ChargeAmount']; } } else{ } } else{ //if($row['PaymentMethod'] == 'CREDITCARD') $ActvUpgrade += $row['ChargeAmount']; } } elseif($row['PaymentReason'] == 'ADDVEHICLE'){ //if($row['PaymentMethod'] == 'CREDITCARD') $ActvVehicleAdds += $row['ChargeAmount']; } } $result = mysql_query("SELECT * FROM tblRenewalCalls WHERE OperatorID = '$operID' AND PayStatus='OK' AND DateSubmitted LIKE '$currentDate%'"); while( $row = mysql_fetch_array($result) ) { if($row['Charged']){ if ((int)$row['RenewYears'] > 1) { $Actv += $row['RenewTotal']; } else{ $ActvRenewal += $row['RenewTotal']; } } } } $total = $Actv+$ActvRenewal+$ActvUpgrade+$ActvVehicleAdds; $ActvRenewal = $total - ($ActvVehicleAdds + $ActvUpgrade); $upgradeEarned = $ActvUpgrade; $renewalEarned = $ActvRenewal; how can i join the two queries so that they function as one. for example, if $keywords or $username is empty then the result will be null.
$query1 = "SELECT * FROM forums WHERE MATCH (topics) AGAINST ('$keywords' IN BOOLEAN MODE)"; $query2 = "SELECT * FROM users WHERE username='$username"; 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 whats the differance between mysql_query("UPDATE banned SET time and doing $safe4 = "UPDATE banned SET time mysql_query($safe4); is there a reason as to why do it the 2nd way i mentioned? if someone could please explain it to me so i wont be in confusion on this anymore This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=331128.0 Here is the original query: Code: [Select] $query_extract = mysql_query("SELECT downloads,date,title,username,views,id FROM skins ORDER BY id DESC LIMIT 100"); Is it possible to also grab the row username from the table users, without making multiple queries? |