Total Without And With A Condition
How do I get the total without a condition and the total with the
condition at the same time?
This is my mysql table:
id datetimeconfirmed customerid amount
1 2007-08-14 06:19:03 1 12.25
2 2007-08-06 06:19:19 1 15
3 2007-08-02 06:19:41 2 5
4 2007-08-07 06:19:58 2 7.25
5 2007-08-09 06:36:41 3 25
If I run this query:
select customerid, sum(amount) from test
group by customerid
I get this result:
customerid sum( amount )
1 27.25
2 12.25
3 25
If I run this query:
select customerid, sum(amount) from test
where datetimeconfirmed < ��-08-08'
group by customerid
I get this result:
customerid sum( amount )
1 15
2 12.25
Which query do I have to run to get this result?
customerid sum( amount ) total
1 15 27.25
2 12.25 12.25
3 NULL 25
View Complete Forum Thread with Replies
Related Forum Messages:
Code Doesn't Work When The The First Condition Is True And The Second Condition Is False?
I can't see the forest for the trees today! Can someone expain to me why the following code doesn't work when the the first condition is true and the second condition is false? In this example, health_safety (in the db) is set to 'No'....but investigator is set to 'Yes'? To my way of thinking the statement is saying "if health_safety is not equal to 'Yes' OR investigator is not is not equal to 'Yes' echo "Go Away". So the example should read (according to the db) "health_safety = 'No' but investigator = 'Yes'" (therefore) 'Hello' Code:
View Replies !
While -> If Condition
Let say i have 10 record. For every 3 record it used the same value starting from number 1. The output would be like this 1 1 1 2 2 2 3 3 3 4 I don't know how to put the if condition of 3 in the while statement like this Quote<? $var1 = 0; while ($var1 < 10) { $var1++; echo $var1; } ?>
View Replies !
If Not Condition
I want PHP to check if the variable section is not home or services, and if it isn't, to set it to about. if (!$section== home, services){$section = about;} But it doesn't work.
View Replies !
If NOT(condition)
Is there any support for a negative condition in If statements in PHP. Some tutorials ive found say that you can use the if!(condition)cmd; syntax. however i always get an error when i use that. "Parse error: parse error, unexpected '!', expecting '(' in TMP5rsqwh3ag.php on line 13" I am runing PHP 4.3.2.
View Replies !
Need Value Of Variable In If Condition
Hello, I have a code displayed below ... $tot_ext = count($ext); for($i=1;$i<$tot_ext;$i++) { if($i < ($tot_ext-1)) { $ext_if_loop .= "'$file_ext' == '".$ext[$i] ."' || " ; } else { $ext_if_loop .= "'$file_ext' == '".$ext[$i] ."' " ; } } Here $ext is an array with specidied allowed file extrensions. When this for loop is executed it returns me a string like ... ''gif' == 'gif' || 'gif' == 'GIF' || 'gif' == 'jpg' || 'gif' == 'JPG' || 'gif' == 'jpeg' || 'gif' == 'JPEG' || 'gif' == 'mp3' " now i want to make one if condition below this for loop like if(''gif' == 'gif' || 'gif' == 'GIF' || 'gif' == 'jpg' || 'gif' == 'JPG' || 'gif' == 'jpeg' || 'gif' == 'JPEG' || 'gif' == 'mp3' " ) { // Do something } else { // Do something } but my problem here is how can i put value of $ext_if_loop variable in if conditon. i tried to use eval but i am not getting proper result. May be i dont know proper use of it...
View Replies !
Redirection If A Condition Is Met
I know this topic has been discussed a few times here and also on php.net, but I cannot find an answer to my specific problem. I check to see if a user is logged in before serving admin.php like so: <?php session_start(); if (!isset($_SERVER['username']) or !isset($_SERVER['password'])) { header("location:http://linux-place.com"); exit; } ?> These are the very first lines in the file. It works perfectly. The problem is that I would like to output a message like "Please login first before accessing the administration panel". How can I do that without getting the headers already sent error?
View Replies !
IF Condition For A Variable
I want to have a condition that is essentially: Code: IF $phonenumber (includes '%911%') { print "this is an emergancy!"}; Any suggestions on how I would form that based on that criteria? I know what I want to do but just no clue how.
View Replies !
Looping Within An IF Condition.
I have a counter on my site to log visits. It works well but I've noticed that a lot of visits come from web crawlers so I'm getting counts higher then what it should be. So I put an if statement around my counter code like so..PHP Code:
View Replies !
A Simple IF Condition.
I have a simple IF condition to check whether an entered town name for a search actually exists in the database. The form search produces $townsearch The check should return "Cannot Find The Town" if $townsearch does not correspond to a recognised townname in the database. The database is correct, and the SQL query OK. So why can I type anything in and it accepts it? (Day 4 of learning PHP) <?php $townsearch = $_GET['town']; ?> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="get"> <input type="text" name="town" size="20" value="<?php echo $townsearch; ?>" /> <input type="submit" value="GO" /> <?php $check = @mysql_query ("SELECT townname FROM site01_towns WHERE townname='$townsearch'"); if (!$check) { echo '<p>Cannot Find The Town</p>' exit(); } ?>
View Replies !
If/else To Meet A Condition
i'm not sure how to go about the if/else code i'm trying to write, basically when a profile is made i get the "Join Date" (which is basically a timestamp) then add 1 hour to it like: $time = date('Y-m-d H:i:s', strtotime("$added +1 hour")); what i was wanting to happen is , when the new timestamp is met ($time) which is 1 hour ahead some text saying "new profle" disappears (so basically new profile only stays there untill the 1 hour is up) then disappears.
View Replies !
Building An 'if' Condition On The Fly.
I would like to create the condition of the 'if' function on the fly, meaning : $condition="$a > $b"; // this variable is a string that contain the 'if' condition .... $a=1; $b=1; if ($condition) { ... } I hope you see what I mean here... In fact, I try to build the condition of the 'if' function so at the end it 'virtually' looks like this: if ($a > $b){ ... } Of course, here that does not work because $a=$b. Code:
View Replies !
Mod_rewrite Condition
<IfModule mod_rewrite.c> RewriteEngine on RewriteBase /testTypo/ RewriteCond %{REQUEST_URI} !index.php$ [NC] #RewriteCond %{REQUEST_URI} !$ [NC] RewriteCond %{QUERY_STRING} !.+$ [NC] RewriteRule ^(.*)$ index.php?id=29&sA=detail&pool=$1 [R] </IfModule> this works fine, there's only one problem. if the REQUEST_URI is empty the rewrite SHOULDN'T be executed. i've been trying to do that with the 2. condition.
View Replies !
Condition Checking
I have a PHP script that loads in a library of PHP auth functions. One of the auth functions I created tells the main script if authorization of a user failed or not. What is the best way to test this condition? By passing a global variable whose prescense can be tested for to see if the function passed or not? Unfortunately I am unable to test the function with an if statement (eg. if (!authUser($user)) ) because it involves mySQL calls and PHP won't allow any calls after HTML markup has started.
View Replies !
Condition Failes
I'v been going nuts for about 2hrs. I have the following code; Code: $stat2 = `grep -c -m1 "^$user" "$myfile"`; The above returns either a 0 or 1 Now here is the good part. The if condition fails completely if i use Code: if ($stat2 == Ɔ') or if ($stat2 == "0") HUH? Why is that? Is there a reason? Intead to get this working i had to place the following condition in my code Code: if ($stat2 == 0) Can sombody explain why?
View Replies !
Include If Condition
How to include an if condition to see wether $areacode is null or not, under the select query before executing: areacode like '%".$areacode."%' $strSQL = "Select distinct id, login, SUBSTRING(comment,1, 165) as comment, gender, date_birthday,icon_path, default_icon as icon_path_default, from ".USERS_TABLE." where date_birthday like '%-".date("m")."-".date("d")."%' and status=Ƈ' and root_user = Ɔ' and guest_user=Ɔ' and id != '".$user[0]."' order by id".$limit_str;
View Replies !
If (condition) {blah}
if (condition) {blah} if (condition) {blah} if (condition) {blah} else {blah} and if (condition) {blah} else if (condition) {blah} else if (condition) {blah} else {blah} are exactly the same right?
View Replies !
Condition Inside A While
I have this code: print "<td width="59">" . $row1['Name']; print "<td width="37">" . $row1['age']; the $rows diplay a value in the database. what I need is in the row['age'] have a condition. for example if row age is biger than 60 the prints older, if it's less the prints younger.
View Replies !
While Loop Condition
so it's not possible to have more than one condition in a while loop?! like: while($row = mysql_fetch_array($result) && $moo = true) or while($row = mysql_fetch_array($result) && $moo < 10) $moo++;
View Replies !
Retrieving An Image If Condition Not Met
I'm sure the answer is simple, but the solution is eluding me-I'm not too good at the particulars of scripting. Maybe someone can point me on the right path... Here is the problem: I have a string of php code that retrieves an image, in this case, an image of a book cover from Amazon.com. This works perfectly well, unless, there isn't an image of the book on Amazon's server. When there's no image, a blank hole appears on the final page. What I would like to happen is, if the variable for the image isn't met (i.e. no book cover image), a "No Image" image, from my server, will load in its place. Here is the code that retrieves the image: <img border="0" src=<? echo $i['ImageUrlSmall'];?>> Is there a way to include a command that will retrieve an image from http://www.mysite.com/images/noimage.gif if the first condition is not met?
View Replies !
Php Condition In A Table With Html And Php
I would like to show a line in a tabel in html if there is quantity of article choosed. My code is: <? if ($quantite1 0) { echo(' <tr> <td align="left" nowrap="nowrap">Article 1</td> <td align="center"><? echo $quantite1 ?</td> <td align="center">20 €</td> <td align="center"<? echo $montant1 ?€</td> </tr>'); } else{ echo(""); } ?> If there is no article >no line If there is article >show the line Problem: I can have the variable $quantite1 and $montant1 en php
View Replies !
Pcntl_fork() Race Condition?
I am using php 5.0.3 and I have a class that I fork, the class works fine independently and is very memory efficent, but when I fork more than one process php races and I get a process that takes up 99% of the CPU, is there a way to determine why these processes are racing? If I do 4 processes all 3 processes will complete and the last will spike to 99% 5/4 etc.. etc..
View Replies !
Mysql Count(condition)?
i have a table that has the following fields: id, name, dept, pay 1, John, Sales, 4000 2, Peter, HR, 5000 etc. How do i count how many people there are in each dept with an sql query? I find this surprisingly difficult, given the fact that i can sum the total pay for each dept by using: $query=" Select sum(if (dept='HR', pay, 0)) as hrpay, ...... ";
View Replies !
Condition Based Redirection
Hi everyone, I have just created my first php form and everything is working great. Now that the form is functional, I was thinking a little error checking would be good. My form POST to a new php page which then processes the answers submited and emails them to me. What i want to do is have a conditional redirect that will read the the submitted feild, then if the feild was left blank, kill the script and send the visitor to the first page with a new error message asking them to fill out all form feilds. All redirect info in php I have been able to find says it must be in the head, before anything else. I was thinking it would be better in my situation to do something like (if possible) if ($x="" ){ redirect http:www.example.com;} Now i'm sure its not as simple as that, but is there something like that I can use?
View Replies !
Mkdir Condition Statement
I am trying to come up with a statement that will create a directory using an ID# that is passed to this page, but if the directory with the ID# has already been made then just upload to that directory. Does anyone know how to do this? Code: //Creates ID folder in the upload directory $resourcefolder = "photos/"; $filestocopy = "array"; $filestocopy[0] = "file1.php"; $filestocopy[1] = "file2.php"; $foldername = "(". $_REQUEST['ID'] .")"; mkdir ("photos/$foldername", 0777); chmod ("photos/$foldername", 0777); $link = mysql_connect("localhost", "db_name", "db_password") or die("Could not connect to server!"); $sql=mysql_query("INSERT INTO folders ('" . $foldername . "') VALUES ('" . $foldername . "')"); { $frompath = $resourcefolder.$filestocopy; .
View Replies !
Condition Display Variables
In a flat file database I have 7 fields saved and separated by pipe. The last one [6] is a "Yes" or "No". I was wondering how to make it so that the site could display all the records that has "Yes" in that record and the ones with "No" in a separated place. Here is my code so far. It doesn't appear to distinguish. Code:
View Replies !
Session If Else Condition Problem
i have one php page but it has different pagaes based on if else condition Now when the session is started first time everything is ok But when the other condition comes true or other page gets loaded The error comes that session has already started beacuse i am using same php page and there is session_start at the top of page.
View Replies !
Why Doesn't This If Condition Work? && || Problem ?
I need to know if the following condition is correctly defined or not: if( ($x == 'string 1' && $y == 'string 2') || ($x == 'string 1' && $y == 'string 2' && object && object == object_type ) ) I figure that it says if match xy or (xy and object^2), it seems that it doesn't. The first condition will always match (xy) while the second won't. If I remove the first xy condition the if statement will match the second condition and the first condition when the first condition also match the object^2 condition.
View Replies !
Condition Window Open
Trying to verify a condition based on a form post. No easyway to tell if field has been posted. Can't echo or echo alert as the php in question is layers below display. Is it possible to open a new window in php something like the following? PHP Code: $email_ba = $_POST['email_ba']; if($email_ba=Ƈ'){ window.open('about:blank', 'about_blank', 'height=400,width=600'); }
View Replies !
Assignment In Condition Error Msg
While this is perfectly exceptable: Code: while ($row = mysql_fetch_row($result)) { $num_rows = mysql_num_rows($result); for ($i = 0; $i < $num_rows; $i++) { $tab = mysql_tablename($result, $i); if(strtolower(trim($tab)) === 'table_name') { $run_job = true; } } } Send Studio IDE keeps returning the analysis: BUG: Assignment in condition.
View Replies !
Page Based Upon Condition
I'm sure this question is really showing my "neophyte" status in php, but here goes: I've got a form that has a number of buttons. On submit, certain functions are called and, depending on which button was pressed, certain things are processed. So far, that part works fine. However, in two instances (add record and edit record) I want to display two different pages. This is where I'm having the problem. As you can see below in the code sample, if $buttonHit == Edit - I want to display edit_row.php; ELSE I want to display Add_row.php. if ($buttonHit == 'Delete'){ deleteEntry($rowId); } else if ($buttonHit == 'Edit') { // LOAD EDIT_ROW.PHP; } else { // LOAD ADD_ROW.PHP; } Seemed straight forward enough to me at the outset, but I can't find the right .php function or syntax to get the job done.
View Replies !
If Condition Not Work In Internet Explorer
I'm having an error with internet explorer. In netscape this redirect page works fine. Basically there is a page before this that has a drop down menu listing options. The select list is named 'selectoption' and selectoption is registered as a session variable at the top. In netscape when someone selects blue it goes to blue_stats.php as I want it to. However in ie, when someone selects blue they are still redirected to red_stats.php. Any reason why its reading the same php page differently? Code: <?php session_start(); if (@$selectoption == "blue" ){ header("Location: blue_stats.php");} else{ header("Location: red_stats.php");}?>
View Replies !
Testing The Condition Of A Pair Of Fields
why the following code will NOT work The error message should be displayed when there is something in both fields if ((isset($_POST['Link']) && $_POST['Link'] !=='') && (isset($_POST['uploadedfile']) && $_POST['uploadedfile'] !=='')) { $error_msg.="<br>You can't select to upload a link and a file at the same time."; curiously the following works if(empty($_POST['Link']) || $_POST['Link'] ='' && empty($_FILES['uploadedfile']) || $_FILES['uploadedfile'] ='') { $error_msg.="<br>You didn't select whether to upload a link or a file."; } to display a message when there is nothing in both fields
View Replies !
Add A Clause Where Records Are Only Returned If Condition
There are two tables, let's call them tblA and tblB. Each of these tables has a field that is delimited with different ids (tied to another table). What I'm looking for is a way to add a clause where records are only returned if one of the members in tblA.field matches a member in the tblB.field. There will be other WHERE clauses, so ideally I need something that can stack. I'm using MySQL, and I think it's a version that pre-dates subqueries if that makes a difference.
View Replies !
Multiple Results Using Ternary Condition
I've just started using the ternary operator to shorten my code and make it more readable. I'm curious to know if you can have more than one result returned and how (if you can). I've currently got this: $password == $passwordConfirm ? $valid[3] = 1 : $valid[3] = 0; I'd like to add $vError++ as well in the "else" part if it's possible.
View Replies !
Session Varilble To Test Condition
I am trying to test the session varilble to test condition. Here is my code. <? if (isset($_SESSION['s_admin'])) == 1 { echo "You are currently logged in as ".$_SESSION['s_admin'].", <a href=logout.php>Log-Out</a><br><br>"; }else{ echo "You are not logged in you log in <a href='login.php'>here</a> or register <a href='register.php'>here</a>."; echo $_SESSION['s_username']; print "<META HTTP-EQUIV='Refresh' content=ƆURL=login.php'>"; } if $_SESSION['s_admin'] == 1 { echo "ok"; } ?>
View Replies !
Displaying Form Based On A Condition
I would like to display a form on a page, but only if a person choses a particular option. I would like to avoid sending my user to a new page to enter his/her information in this form. How could PHP be used to do this(if possible) and what elements could be used to provide the user with the options, example, could i just put an image button that causes the form to be diplayed when clicked, could i use options from a flyout menu. I would like the element used to provide the option to display the form be very accessible.
View Replies !
Changing Variables Values Based On Condition
I am submitting a form field that has several dropdown menu that pass information that is dynamiclly changed in javascript through a menu function so the values for each dropdown menu equal numbers ranging from 0-12 when i submit the form and tried to read what was in the form fields for processor I get a reply such as 0 or 1 or 2 Instead of AMD ATHLON XP 1900+ which is what I want into read and store into my session. PHP Code:
View Replies !
PHP File Writing And Avoiding A Race Condition
So, PHP has this issue where you cannot lock a file until you open it, which leaves the door open for a race condition when writing files. I wrote the following code a while back and think it should work (and in fact use it and it works), I just thought I'd post it here for an audit and in case it might be useful for someone to use or I missed something! /** * Write a file to the server. * * First open a temp file for writing and acquire a lock. * Proceed to write, unlock and copy the file from a temp file. If the * file size is the same, the write worked, clean up and go home. if * not, clean up and hope it works the next time. */ function cms_writeFile($filename, $tempfile, $data) { $ft = fopen($tempfile, 'w'); if(flock($ft, LOCK_EX)) { fwrite($ft, $data); flock($ft, LOCK_UN); fclose($ft); if(copy($tempfile, $filename) && filesize($tempfile) == filesize($filename)) { unlink($tempfile); return true; } else { // The whole process failed. unlink($tempfile); unlink($filename); return false; } } else return false; } I pass it a random tempfile name, so at that point I think we avoid any race condition issues, but to be paranoid I check the file size after the copy. If the files are of a different size, I drop them both and hope this works the next time. An example to use the function: if(cms_writeFile('test.php', 'randomg-temp.php', 'some data')) { echo 'written' } else { echo 'notwritten' } Seems right, and it works, am I missing anything?
View Replies !
Display All Or Selected Data Based On An IF Condition
I am trying to display all and selected data based on an IF condition. It will either execute all the data from the table or selected data based on category. well at least it is supposed too. I can take out the select * query and it will work but I need to use both. And I want the page to load all the data from the table on reload or load and when someone selects the list box and hits submit it will only display the selected ones on a web page. Its probably something simple but I cant see why I dont get any results to display. Code:
View Replies !
How To Redirect People To Different Pages Depending On A Condition
Right now i have a login page in wich after you enter an existing user and ID then you are redirected to another php page wich is called infouser.php what i want is to do is before sending people to infouser.php check wich company they belong to, (on table employees_selex there`s a field called company with that info) if they are on Cemex Mexico or Cemex Central its ok if they are sent to infouser.php but if they are working with any othe companies at all then i want to send them to infouser2.php any clues on what to add to this code? Code:
View Replies !
Race Condition When Inserting Data / MySQL 4.0+, MyISAM Tables
I use a table to cache some informations which need lots of resources to be composed. The first time the info is needed, it will be composed and written to the cache table ($db in the example is a PEAR DB object; the question is the same for other ways of accessing the database): // Retrieve info if present $details = $db->getOne("SELECT contents FROM cache WHERE id=".$id." AND info='details'"); // If not present, compose info and write it to the database if (!is_string($details) || trim($details) == '') { $details = $this->compose_details(); $data = array('id' =$id, 'info' ='details', 'contents' =$details); $db->query("INSERT INTO cache (id, info, contents) VALUES (".$id.", 'details', '".$details."')"); } Now I encountered that if several users call a page at the same time after the cache was flushed, it is possible that between the first line and the INSERT query the info was entered by another user. This results in a duplicate key error. Now I wonder which is the best way to handle this. I see various approaches: - Use ON DUPLICATE KEY UPDATE (which might fail if MySQL 4.0 is used) - Try to write some kind of locking mechanism - Suppress the error message for this special case - Remove the primary key from the cache table (as it is flushed whenever items are administrated, duplicate entries might not be a big problem) Which is the recommended way to handle this? I guess, as MySQL 4.0 and MyISAM tables are a quite common configuration, there must be some common practice about this, but I did not find anything by googling...
View Replies !
Total
I have a database table with many entrys, is there a quick way of adding how many entrys there is?
View Replies !
Total ?
I have a table (sales) with 3 columns(id,name,price) the price column is integer, id = 1 name = Car price = 10000 id = 2 name = Car 2 price = 15000 I want to calculate the (price) columns in which the total = 25000?
View Replies !
|