MySQL Conditional Statement
What I am trying to do is kind of like an advanced search. Basically, I have three dropdowns, for this I am going to use the example books: Three dropdowns, which are
1) Author 2) Language 3) Type (Hardback or Paperback)
Typical search: I want to get a list of all books written by STEPHEN KING, that are written in ENGLISH and that are HARDBACK ok fine, but what if I just want to search for ALL books by STEPHEN KING regardless of the language or the type of book?? Heres the SQL i would use for all 3 "search parameters": PHP Code:
View Complete Forum Thread with Replies
See Related Forum Messages: Follow the Links Below to View Complete Thread
Writing Conditional Statement
I'm trying write a conditional statement that updates the database in 1 of 2 ways depending on the values given. I'm only 2 weeks into learning PHP/MySQL so I realize the way I've written it out is probably sloppy and more inefficient than what it could be. I've just been winging it from examples and trial and error and have gotten everything working except for this. I'm not sure if I have my logic or syntax wrong. Application-specific details: This is a simple invoicing application. Every invoice is in either 1 of 3 states: - pending (default state when a new invoice is entered) - paid (state when invoice is paid in full) - partial (state when only partial payments have been made on the invoice) What I'm trying to do is this: 1. If a partial payment is made on an invoice, the status is set to 'partial' (this is working) 2. If the payment posted was the full amount of the invoice or the final amount needed to pay it in full, the status is set to 'paid' (this is not working) My processing logic works like this: 1. There is a total invoice amount stored in the invoice table represented by $total variable (working) 2. When payments have been made to that invoice (stored in the payments table), I show the remaining balance on their invoice by calculating the sum of those payments and subtracting them from the total (this is represented by the $diff variable and is working) 3. The part not working: When the remaining balance ($diff) minus the payment amount posted ($_POST['amount']) is equal to 0, the status is set to paid. PHP Code:
Help With Posting Conditional If Statement
I've tried scaling down a script to the bare minimum and it still is not working correctly. What I think should happen is that when the field app_fname is blank, that $hold_chk will get set to 1 and the 1st if statement will be executed. What actually happens is that when I hit submit, the form stays where it is, for example if the form where the submit button is located is on the form other.php, then when I hit submit this is where it stays. If I then hit the submit button a 2nd time, it post to the some.php form. I've tried this script without the conditional if(isset() and it works. I need to have the isset() otherwise the form displays all empty fields as soon as it loads, before the submit button is hit. <?php $holdchk = 0; if (isset($_POST['B1'])) { echo "<br><br><br>"; if (empty($_POST['app_fname'])) { $holdchk = 1; } if ($holdchk == 1 ){ echo "<form method="POST" action="some.php">"; } if ($holdchk == 0 ){ echo "<form method="POST" action="other.php">"; } } ?> <html> <head> </head> <form method="POST" action=""> When hit the submit button</font></b<input type="submit" value="Submit" name="B1"></p> </form> </body> </html>
Syntax Issue With Form And Conditional Statement
Is it possible for a <form ... action="program.php"> to contain a conditional statement for the action? For example, I want to call one PHP program if variable $a="screen" and another program if variable $a="download". I have been struggling with this for some time and cannot seem to get it to work.
Conditional Select From Mysql
I have a mysql database which stores race data that I want to open up to users for viewing. I want the user to be able to select various subsets of the data according to the parameters: race, gender, age, and type (and maybe sometime, by name as well). This is BOTH a mysql question and a php one, as I ask for a more efficient solution (see bottom this post). Here is a snippet of how I am implementing the mysql statements to select only the exact subset of data. PHP Code:
PHP -> MySQL Insert Statement
heres what i am using : Code: if (($p1 == $p2) && ($p1 != " ")) {print "accepted"; print "<br>entering you into the database...."; $enter = 'INSERT INTO member(name, psw) VALUES("$name", "$p1")' $goenter = mysql_query($enter) or die("Entery Failed due to " . mysql_error());} else {print "<br><font size=+1>Password did not match, try again!</font>";}} ?> now heres the problem : when it writes to the table (all the db selection etc is fine) all that gets written is : "$name" and "$p1" literally $name and $p1 *** not their values. I have tried combinations of quotes ( as " " will interpolate but ' ' will not) but still no dice. and w/o the quotes around the values ("$name" , "p1") --- it will return an error stating the colum ($name value) does not exsist.
Mysql Query Statement
What I'm trying to do is search a field in mysql, and if it has an _ in the file name, change it to a - instead. And alos change any capital letters to lower case. From: This_is_my_example To : this-is-my-example I figure it would be something like: UPDATE 'file' SET '-' WHERE `filename` LIKE '_' I"m not really sure how to put a regular expression in there to only replace the underscore put leave the data.
Quote Escaping For MySQL Statement
I'm doing a data migration and used gnumeric to change some big spreadsheets into .csv files for upload into a MySQL database through php. It seems to have done fine on my local machine, but it is dying on the production dB when it encounters a single quote, e.g. "The Manufacturer's specification ..." Right there------------------^ magicquotes is On Is there a handy extra function that can improves a string's chances of getting into MySQL cleanly? The setting for the csv export was "Always" (escape-quote everything)
MySQL - Using Expressions In ORDER BY Statement
I am currently teaching myself PHP/MySQL to add functionality to a website showing event listings for an entertainment venue. The events in any day can run from 11am until 3am. I have a search script that will return all events by title, time, date and other criteria and users can click on any column heading in the results to sort by that column. My problem is the event start time column. Sorting the data using "ORDER BY time" puts the post-midnight shows at the beginning of the list not the end. Does anyone have any ideas as to how I could adapt the ORDER BY part of the SELECT statement to return the post-midnight shows at the end of the list. I could presumably sort after deducting 4 hours off every time. Would something like ORDER BY (time-4) work (using simplistic shorthand for the "time-4")? I assume I would have to use the DATE_SUB() command but I am not sure about the format. The time is currently recorded simply as hh:mm:ss in the MySQL database.
PHP, MySQL, $_GET And If Statement Problem
I am having a issue that I have been working on for the last few days. I am using PHP 5, MySQL 4.1 and PEAR. The following code works by itself between <?php and ?tags: $isbn = $_GET['isbn']; $sql = "DELETE FROM lounge WHERE isbn = $isbn"; $db->query($sql); print $sql; Now, if I put it inside of an If statement, it does not work and I get a "DB Error: syntax error": if ($_POST['yes_no'] == 'yes') { $isbn = $_GET['isbn']; $sql = "DELETE FROM lounge WHERE isbn = $isbn"; $db->query($sql); print $sql; } else { print "Unable to delete record"; } This isbn is stored as an INT in MySQL. Does anyone have any ideas?
Switch Statement + Reading From MySQL DB
I have created a templated site, with the use of switch statements [shown below] Anyway, this works fine, accept the person I am doing this for knows little html so what I want to do is be able for him to add new sections easily without doing any HTML, thus the MySQL DB. But I am stumped what is the best way to do this?? I would be very grateful if someone can help.. PHP Code:
PEAR DB/MySQL Prepared Statement With LIKE
how to create a select statement using PEAR DB or MySQL with the LIKE function. That is I am looking of how I can get statement like this work. SELECT * FROM customer WHERE name LIKE '%?'
Question Regarding A MySQL SELECT Statement
I tried hunting for a MySQL specific NG and didn't find one but I did see that MySQL questions get asked here. If this isn't appropriate and you know of an appropriate NG then that would be great. In one table I have inventory... table name is "inventory" columns are.. ----------------------------- item_number item_name ----------------------------- 1 radishes 2 carrots 3 potatoes 4 oranges etc..etc Table two is "sold" ------------------------------ date item_number 13Mar 1 14Mar 4 15Mar 2 16Mar 1 What I am querying is the table "sold" for the Unique items (1,4,2) and then retrieving their names from table 1. My query below isn't working.. SELECT item_name FROM inventory WHERE inventory.item_number = sold.item_number; I am just now starting to get into complicated MySQL queries and actually the more I learn about it the more I love it.
Trouble MySQL AES_ENCRYPT() Using PHP For SQL Statement
I want to add a binary element (AES_ENCRYPT()) to a $_POST array. I need to make it binary because it is going into a BLOB field. $results = $dbr->Execute('select * from table1 where id='.$_GET['id']); .... // validation take place and now is processed $_POST["field1"] = $dbr->GetOne('select AES_ENCRYPT('.trim($_POST['field1']).', 'salt*&)#')'); // there are other $_POST fields that are in cluded in the next line // GetInsertSQL is a function that eventually calls $dbr->Execute() $dbr ->GetInsertSQL($results, $_POST, true); It decrypts most records (field1) but not all. After researching it, I think the problem lies in how I am adding the encrypted field. I think I need to make the $_POST["field1"] binary, somehow. If so, how do I do that?
Using Several Variables In A Mysql Statement In A Php Script
1. asking the user to select a teacher and adding to the hyperlink a variable ($id) to be used in the next page 2. showing a list of classes that teacher gave and ordering them by date or title. problems: 1. when i try and use variables for the "order by" function (one for $orderby and another for $direction), from some reason the query fails. I think that problem is about the other variable ($id) which is used in the same statement.... when i take that variable off and just enter a static number there is no problem. However trying to use these two or even three variables in the same mysql statement fails. any ideas? Code:
PHP/mySQL Insert Into Statement With Auto Increment
When i use mysql from the linux command line it is just plain simple to add an row into a table, even with php this isn't a problem. But when the table has aan field with auto_increment php won't allow to insert a new row in the table. I'll get an invalid query back.. In don't understand how to insert a new row into a table with the auto increment. Btw this is also the primary key: Code:
Getting Form Info Into A Mysql Select Statement
I'd like to get user input from an html form into a mysql select statement. Here's where I'm stumped: $result = mysql_query("SELECT * FROM dept WHERE notes LIKE '%search-string%'",$db); I need to get the user's input into the '%search-string%' section, but I do not understand how to do this. I can hard-code a specific search string and it will work, but I want the users to be able to dynamically define the search-string. So, I created a basic html form and used the post method to grab their input, but now I can't insert that input into the mysql select statement. Any ideas? I think it should be easy, I just don't know how to do it. I've tried this: $result = mysql_query("SELECT * FROM dept WHERE notes LIKE '%$_POST["search"]%'",$db); But it doesn't work. Below is the form in html and the php file: <html> <title>Search Test</title> <head> </head> <body> <form action="search-db.php" method="POST"> <p>Enter Your Search: <input type=text name=search></p> <input type="submit"> </form> </body> </html> ----------------------------------------------------------- <html> <body> <?php $db = mysql_connect("localhost", "Anonymous"); mysql_select_db("computers",$db); $result = mysql_query("SELECT * FROM dept WHERE notes LIKE '%surplus%'",$db); echo "<table border=1> "; while ($myrow = mysql_fetch_array($result)) { printf("<tr><td><b>%s</b></td></tr> ", $myrow[notes]); } echo "</table> "; ?> </body> </html>
MySQL Prepare Statement Performance Bottom-neck
When doing mysql query (SELECT statements) in php, we often use prepare statement to prevent SQL injection. However, I just noticed that the prepare statements can SLOW the number of queries per second by a factor of 2 times (max). So are there any faster method that can prevent SQL injection, but has a better performance?
MySQL UNION: Only The First Select Statement Returns A Result.
I am attempting to join multiple select statements into a single query. However, I am not able to extract the result of any of the UNIONED selects. $query1 = mysql_query (" ( SELECT SUM(deposits) AS total_deposits FROM table1 ) UNION ALL ( SELECT SUM(withdrawals) AS total_withdrawals FROM table1 ) ") or die (mysql_error()); $result1 = mysql_fetch_array($query1); extract($result1); When I echo the results of the second select statement I get nothing. echo $total_withdrawals;
MYSQL CASE Statement Within PHP Syntax Or Correct Quoting ?
I'm trying to use a MySQL "CASE" statement within PHP to develop a conditional query. The query runs fine within from the MySQL command prompt with the "case" statements. And the PHP code works fine when I remove the lines that begin with "case". However when I run the query as listed below within my PHP code i get the following: [Fri Apr 20 22:15:24 2007] [error] [client 10.188.50.74] PHP Parse error: parse error, unexpected T_CONSTANT_ENCAPSED_STRING in /srv/www/htdocs/mysql-learn/acetrack-post.php on line 68, referer: http://webserver1/mysql-learn/acetrack-post.html < code snip > $query =" SELECT acetitle, tracking_no, aceamt, case when (To_days(curdate()) - To_days(create_date)) >= 90 Then pototalamt else "" end as "90past" , case when (To_days(curdate()) - To_days(create_date)) < 90 and (To_days(curdate()) - To_days(create_date)) > 30 Then pototalamt else "" end as "30-90past" FROM Purtable t LEFT JOIN acelog a ON ace=acenum WHERE ace='0220' GROUP by po ASC "; $result = mysql_query($query); < /code snip > Thanks in advance for any help.
Update Statement Causes Mysql Varchar Field To Be Set To Empty String
I have come across a problem that has me baffled. I am using PHP with MySQL 4.1.14. Whenever I execute an update statement against a specific table, some of the varchar fields do not get set to the new values, but get set to empty strings instead. I have simplified the code down to updating a single column in the table, but the same results happen when updating just the single column. Here is the stripped down code which causes the problem: $queryString = "UPDATE REGISTRATION SET passwd = '$pass'' WHERE id = 388"; $db = mysql_connect("hostname", "user", "pass"); mysql_select_db("CUSTOMER", $db) or die(mysql_error()); mysql_query($queryString, $db) or die(mysql_error()); Printing the query string after executing mysql_query shows the following query: UPDATE REGISTRATION SET passwd = 'test' WHERE id = 388 This query updates the column successfully when run directly through phpMyAdmin. When run through PHP using the code above then column is set to an empty string value. There is no error returned if I call mysql_error() nor is there any unusual info returned from mysql_info() (other than it telling me that 1 row was affected). Does anyone have any ideas what the underlying problem is on this one? Could be an attribute of the database table or columns that would cause this behavior? I have racked my brain for a while over this problem.
Conditional Loop
I have one table, "players" that has player info including start season (year). I then have a table for each season with player stats, i.e. games played etc called stats200X where X is the year obviously. I have no problem with extracting data from the current year, but what I would like to do is get data from previous years too. I was thinking about doing something like: (year) - (startyear), which for example could be 3. I don't know where to begin, but I want to be able to loop though previous years so that, if tables exist of course, I could do select * from stats{Y -1} display select * from stats{Y -2} etc Would I need to hard code this or is there a way of doing this though a conditional loop?
Conditional Login..
I have a form with a username & password field along with 3 radio buttons. What I basically want to achieve is if radio button A is checked it will post the username & pass to a.php, If button B is checked it will post the username & pass to b.php and so on for button C.
Checkboxes,conditional
Basically I have what seems to be a very small problem but I am driving ny self mad trying to figure out what the problem is. Here is what I have: I have a form with two checkboxes: <input type="checkbox" name="medicalcheck" > <input type="checkbox" name="dentalcheck" > the form is posting the a php file, decision.php, that simple checks to see if the boxes have been checked and performs an operation in either case. Here is the code:
Once Conditional Causes Error, The Other Doesn't...why?
There are 2 if statements at the beginning of this code snippet. The one that is currently commented out works while the one that is not commented out yields this error Parse error: syntax error, unexpected '{' in C:xampphtdocsench2index4.php on line 106 I am just not seeing why. Code:
Conditional Structures
I am wondering about conditional structures and the depth of nesting allowed, if at all. For example I know I can do this: Code:
Conditional Form
I want to condtionally display an HTML form. I havnt got a clue how it can be done, I suppose its the same way as putting html tables in php, but I cant get it to work. Here is the condtion: <?php if (!empty($pk)) { And here is the form: <form action="google.php" method="GET" name="deleteForm" > <input type="hidden" name="pk" value="<? echo $pk;?>"> <input type="submit" value="Delete"> </form>
Conditional Third Expression In For Loop
Is it possible to make expr3 $i++ under one condition and $i-- under another? Instead of having the condition outside the loop and having two loops. Or I could just use a while loop, I guess.
Sessions + Conditional Include
I am having a little problem in trying to figure out why my session state is not expiring after I close the browser window. Having been used to the ASP way of doing things I am trying to get my head around this slightly different method of handling sessions in PHP.... What happens is that I log on to the site, do various things and then close it when I am finished. I return the next day to find that the 'logged in' menu is displayed first which shouldnt happen until you have logged in again. I assumed that the session was been stored as a cookie but wasnt been released after the session terminates by default, but found I was wrong when I deleted all my internet files and went back to the site. My code for the first page is as follows..
Conditional PHP Cookies; If Cookie = 1 Do This...
I've figured out cookies ... now I'm trying to combine them with if conditions. For cookie 'bandwidth1' I want to echo that it is set to 1 by the cookie to confirm this in the brower through regular html. My if/else statements don't seem to be working though...heres the code I have now. <?php setcookie("bandwidth1","0",time()+2592000,"/"); setcookie("bandwidth2","1",time()+2592000,"/"); setcookie("bandwidth3","2",time()+2592000,"/"); ?> <?php if (isset($_COOKIE["bandwidth1"])=="1") echo "Bandwidth is 1!"; else echo "Bandwidth is unknown"; elsif echo "Cookie was not set?"; ?>
Conditional Statements And Loops
Not long ago I was asked to give PHP lections to some private IT school. I'm on second lection now, and will be teaching my :) students conditional statements (if..else and switch) and loops (while and for). That was my story, now the question. Can you give me an advise on some geeky use of those statements to stir up some enthusiasm in students.
Mutlipart And/or Conditional Form
I have a form that needs to have conditional statements, and I am not sure how to "fix" this. The existing form is split in two parts - the form, and the processor. I would think that I will need to combine them, but.. Anyways - what I need is somewhat simple - if a certain option (from a <select>) is chosen, force another field to be completed. I also have 2 other fields that if the radio button is set to YES, require new fields. Ideally, the optional fields would only be shown to the user IF they are required.
Conditional Preg Match
The following bit of code does a preg match and does something if true (sets $browser to ppcie) Without using if then and else's how do I code it so it does not equal what it is testing for? So if it does not find ppc in the $agent then it does something else/sets it to something else? $agent = getenv("HTTP_USER_AGENT"); if (preg_match("/PPC/i", "$agent")) { $browser = 'PPCIE' }
Question On Conditional Statements
I'm a perl programmer and am trying to learn PHP. So far I have figured out most of the differences, but have not been able to find out how to do the following: When running through a loop, how can you test two separate conditions against the same $element of an array. For example, this is how I thought it would be done (similar to Perl), but it did not work: if (eregi("apple", $line) and (eregi("orange", $line) { do whatever; } Basically testing each line of an array to see if both the words "apple" and "orange" are present. Also, is there any equivalent to the following from Perl while running through a loop: next if (whatever conditions); last if (whatever conditions);
Conditional List Boxes
I am attempting to create a list box that is dynamically populated based on the selection of another list box. I am in way over my head..only way to learn I guess. The code below has a year listbox and then based on the year selection, the page should either show another listbox (show industry selection when year <> 2005) or it should render the main form (when year=2005). I cannot get the main form to appear. Code:
If Statement Construction Within An Echo Statement
I have a form that is being used to "update" user info and I need the information to be pulled from the users table. In order to get the variables into the form, I am echoing it in and using an mysql array to place them into the form. at the t-shirt size part of the form the code is as follows ....
Conditional Email Text To Hyperlink
I am trying to write a content management section for a web site. I have managed so far to use htmlarea to give users a basic, but user friendly interface by which to edit the page content. The user can add emails by symply typing john@example.com - IE automatically converts this to a hyperlink. The trouble is sometimes the users use plain text. I have been using the following line to convert plain text to a hyperlink: $pagetext=ereg_replace('[A-Za-z0-9_]([-._]?[A-Za-z0-9])*@[A-Za-z0-9]([-.]?[A-Za-z0-9])*.[A-Za-z]+', '<a href="mailto: ?subject=Email%20from%20web%20site"> |