PHP - (mysql) Multiple Conditions In While Statement
Hello everyone! I'm new here on phpfreaks - Here's my problem. I get "1 <br/> 2" echoed, but not the query results. the connect() function connects and selects a table in a mysql database.
Here's the code: Code: [Select] <?php connect(); $query = "SELECT `title`, `body`, `date` FROM `tutorials` ORDER BY `date` DESC" or die ("Query Error"); $counter = 0; if ($query_run = mysql_query($query)) { while ($query_row = mysql_fetch_assoc($query_run)) && ($counter <= 2) { $title = $query_row['title']; $body = $query_row['body']; $date = $query_row['date']; $counter ++; echo $counter; echo "<br/>"; echo $title; echo $body; echo $date; } } ?> If anyone has any idea, please help! - I'm been battling this for a few hours now Similar TutorialsHello everyone, I'm a newbie with PHP and mySQL and need some assistance with writing a php script that searches a mySQL database using a form. The form has five fields that I want to search from and one is a required field (State). I need to filter or narrow down the search by either two or more fields. The problem I am having is if I used multiple WHERE clauses using the AND condition I have to enter valid information in all five fields and if I use the OR condition then my search does not produce the desired outcome (too many results). I "think" I need to use the AND condition but I need to be able to leave some of the fields blank (except for the State field) and narrow my search with using anywhere from 2-5 search fields. Also, another requirement is to be able to enter partial information in the search field "without" having to enter a wildcard in the search field. Any assistance is very much appreciated and thanks in advance for your help. Form Fields: State SELECT FIELD Lease TEXT FIELD Operator Name TEXT FIELD County or Parish TEXT FIELD Well No TEXT FIELD I have a table called well_permits and it is structure is as follows: date DATE state TEXT county VARCHAR api VARCHAR permit_no VARCHAR operator VARCHAR phone VARCHAR contact VARCHAR lease VARCHAR well_no VARCHAR permit_for VARCHAR welltype VARCHAR wellspot VARCHAR lat FLOAT lon FLOAT depth VARCHAR This is what I have for the connecting to my database and selecting the fields: <?php require_once('../../../Connections/Wldatabase.php'); ?> <?php if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } $currentPage = $_SERVER["PHP_SELF"]; //Variable to store Unique_ID aka API which will be passed to the well-search-results.php page $var_api_rs_search = $_Get['api']; $maxRows_rs_search = 20; $pageNum_rs_search = 0; if (isset($_GET['pageNum_rs_search'])) { $pageNum_rs_search = $_GET['pageNum_rs_search']; } $startRow_rs_search = $pageNum_rs_search * $maxRows_rs_search; $var_state_rs_search = "%"; if (isset($_GET['state'])) { $var_state_rs_search = $_GET['state']; } $var_lease_rs_search = "%"; if (isset($_GET['lease'])) { $var_lease_rs_search = $_GET['lease']; } $var_well_no_rs_search = "%"; if (isset($_GET['well_no'])) { $var_well_no_rs_search = $_GET['well_no']; } $var_operator_rs_search = "%"; if (isset($_GET['operator'])) { $var_operator_rs_search = $_GET['operator']; } $var_county_rs_search = "%"; if (isset($_GET['County'])) { $var_county_rs_search = $_GET['County']; } mysql_select_db($database_Wldatabase, $Wldatabase); $query_rs_search = sprintf("SELECT DISTINCT * FROM well_permits WHERE (well_permits.`state` LIKE %s AND well_permits.county LIKE %s) OR (well_permits.lease LIKE %s) OR (well_permits.operator LIKE %s) OR (well_permits.well_no LIKE %s) ORDER BY well_permits.county", GetSQLValueString($var_state_rs_search, "text"),GetSQLValueString($var_county_rs_search, "text"),GetSQLValueString($var_lease_rs_search, "text"),GetSQLValueString($var_operator_rs_search, "text"),GetSQLValueString($var_well_no_rs_search, "text")); $query_limit_rs_search = sprintf("%s LIMIT %d, %d", $query_rs_search, $startRow_rs_search, $maxRows_rs_search); $rs_search = mysql_query($query_limit_rs_search, $Wldatabase) or die(mysql_error()); $row_rs_search = mysql_fetch_assoc($rs_search); ?> This is my form: <form action="search.php" method="GET" name="frmsearch" target="_self"> <input name="api" type="hidden" value="" /> <div> <table width="900" border="0" align="center" cellpadding="2" cellspacing="2"> <tr> <td colspan="6"> <p style="text-align:left">Select a State then enter at least one search criteria. State is a required field.</p> * Denotes a required field.<br> </td> </tr> <tr> <td align="right">* State: </td> <td> <select name="state" size="1" dir="ltr" lang="en"> <option value="AL">AL</option> <option value="AR">AR</option> <option value="CA">CA</option> <option value="CO">CO</option> <option value="IL">IL</option> <option value="IN">IN</option> <option value="KS">KS</option> <option value="KY">KY</option> <option value="LA">LA</option> <option value="MI">MI</option> <option value="MS">MS</option> <option value="MT">MT</option> <option value="ND">ND</option> <option value="NE">NE</option> <option value="NM">NM</option> <option value="NY">NY</option> <option value="OH">OH</option> <option value="OK">OK</option> <option value="OS">OS</option> <option value="PA">PA</option> <option value="SD">SD</option> <option value="TX">TX</option> <option value="UT">UT</option> <option value="WV">WV</option> <option value="WY">WY</option> </select> </td> <td align="right">County or Parish: </td> <td align="left"><input name="County" type="text" value="" size="35" maxlength="40" /></td> </tr> <tr> <td width="63" align="right">Lease: </td> <td width="239"><input name="lease" type="text" value="" /></td> <td align="right">Well No: </td> <td><input name="well_no" type="text" value="" /></td> </tr> <tr> <td width="111" align="right">Operator Name: </td> <td width="261"><input name="operator" type="text" value="" /></td> </tr> <tr> <td> </td> <td> </td> <td> </td> <td align="left"><input name="search" type="submit" value="Search" /></td> </tr> </table> </form> My Repeat Region starts here <table width="100%" border="1" align="center" cellpadding="2" cellspacing="2"> <tr> <td align="right"> </td> <th align="center">Operator</th> <th align="center">Lease</th> <th align="center">Well Number</th> <th align="center">County</th> <th align="center">State</th> </tr> <tr> <?php do { ?> <td align="center"><a href="results.php?recordID=<?php echo $row_rs_search['api']; ?>">Select</a></td> <td align="left"><?php echo $row_rs_search['operator']; ?></td> <td align="left"><?php echo $row_rs_search['lease']; ?></td> <td align="center"><?php echo $row_rs_search['well_no']; ?></td> <td align="center"><?php echo $row_rs_search['county']; ?></td> <td align="center"><?php echo $row_rs_search['state']; ?></td> </tr> <?php } while ($row_rs_search = mysql_fetch_assoc($rs_search)); ?> </table> <p align="center">Number of Wells Located: <?php echo ($startRow_rs_search + 1) ?> to <?php echo min($startRow_rs_search + $maxRows_rs_search, $totalRows_rs_search) ?> of <?php echo $totalRows_rs_search ?></p> <table border="0" align="center"> <tr> <td align="center"><?php if ($pageNum_rs_search > 0) { // Show if not first page ?> <a href="<?php printf("%s?pageNum_rs_search=%d%s", $currentPage, 0, $queryString_rs_search); ?>">First</a> <?php } // Show if not first page ?></td> <td align="center"><?php if ($pageNum_rs_search > 0) { // Show if not first page ?> <a href="<?php printf("%s?pageNum_rs_search=%d%s", $currentPage, max(0, $pageNum_rs_search - 1), $queryString_rs_search); ?>">Previous</a> <?php } // Show if not first page ?></td> <td align="center"><?php if ($pageNum_rs_search < $totalPages_rs_search) { // Show if not last page ?> <a href="<?php printf("%s?pageNum_rs_search=%d%s", $currentPage, min($totalPages_rs_search, $pageNum_rs_search + 1), $queryString_rs_search); ?>">Next</a> <?php } // Show if not last page ?></td> <td align="center"><?php if ($pageNum_rs_search < $totalPages_rs_search) { // Show if not last page ?> <a href="<?php printf("%s?pageNum_rs_search=%d%s", $currentPage, $totalPages_rs_search, $queryString_rs_search); ?>">Last</a> <?php } // Show if not last page ?></td> </tr> </table> Hey all, I would like to some how clean up an if statement to be a little cleaner. Code: [Select] if(condition && condition && (condition && condition) || (condition && condition) || (condition && condition)) How can I do that? I forgot how to write multiple conditions with if(). if (A == B || C == D) {foobar;} I know the above is if any of the conditions is true, then do foobar, but what is it again so they both have to be true? I have forgotten, but I'm guessing either if (A == B && C == D) {foobar;} if (A == B ++ C == D) {foobar;} ? This works: Code: [Select] if($ABC == 'Yes' and $X != $Y){ echo "Error"; exit(); } I need to evaluate one more set of variables in this statement like so; This does not work: Code: [Select] if($ABC == 'Yes' and $X != $Y or $Z != $Y){ echo "Error"; exit(); } So basically I need to echo an error if $ABC == Yes and both $X and $Z do not equal $Y If gives an error because it is obviously not correct. I do not know how to make it correct. Any suggestions? Hi Guys I am having problems with the below, I am assuming I have formated the if statement incorrectly but I cant see my mistake as nothing shows? Code: [Select] <?php $query = mysql_query("SELECT * FROM user_profile WHERE username = '$username'"); $results = mysql_fetch_array($query); if($results['followers'] < 150 && $results['posts'] < 300 && $results['days'] > 0 && $results['status'] = 0) { echo 'ok' } The database for the said user looks like: followers days posts status 1 182 1 0 All fields are INT Many Thanks Ok I'm trying to insert multiple rows by using a while loop but having problems. At the same time, need to open a new mysql connection while running the insert query, close it then open the previous mysql connection. I managed to insert multiple queries before using a loop, but for this time, the loop does not work? I think it is because I am opening another connection... yh that would make sense actually? Here is the code: $users = safe_query("SELECT * FROM ".PREFIX."user"); while($dp=mysql_fetch_array($users)) { $username = $dp['username']; $nickname = $dp['nickname']; $pwd1 = $dp['password']; $mail = $dp['email']; $ip_add = $dp['ip']; $wsID = $dp['userID']; $registerdate = $dp['registerdate']; $birthday = $dp['birthday']; $avatar = $dp['avatar']; $icq = $dp['icq']; $hp = $dp['homepage']; echo $username." = 1 username only? :("; // ----- Forum Bridge user insert ----- $result = safe_query("SELECT * FROM `".PREFIX."forum`"); $ds=mysql_fetch_array($result); $forum_prefix = $ds['prefix']; define(PREFIX_FORUM, $forum_prefix); define(FORUMREG_DEBUG, 0); $con = mysql_connect($ds['host'], $ds['user'], $ds['password']) or system_error('ERROR: Can not connect to MySQL-Server'); $condb = mysql_select_db($ds['db'], $con) or system_error('ERROR: Can not connect to database "'.$ds['db'].'"'); include('../_phpbb_func.php'); $phpbbpass = phpbb_hash($pwd1); $phpbbmailhash = phpbb_email_hash($mail); $phpbbsalt = unique_id(); safe_query("INSERT INTO `".PREFIX_FORUM."users` (`username`, `username_clean`, `user_password`, `user_pass_convert`, `user_email`, `user_email_hash`, `group_id`, `user_type`, `user_regdate`, `user_passchg`, `user_lastvisit`, `user_lastmark`, `user_new`, `user_options`, `user_form_salt`, `user_ip`, `wsID`, `user_birthday`, `user_avatar`, `user_icq`, `user_website`) VALUES ('$username', '$username', '$phpbbpass', '0', '$mail', '$phpbbmailhash', '2', '0', '$registerdate', '$registerdate', '$registerdate', '$registerdate', '1', '230271', '$phpbbsalt', '$ip_add', '$wsID', '$birthday', '$avatar', '$icq', '$hp')"); if (FORUMREG_DEBUG == '1') { echo "<p><b>-- DEBUG -- : User added: ".mysql_affected_rows($con)."<br />"; echo "<br />-- DEBUG -- : Query used: ".end($_mysql_querys)."</b></p><br />"; $result = safe_query("SELECT user_id from ".PREFIX_FORUM."users WHERE username = '$username'"); $phpbbid = mysql_fetch_row($result); safe_query("INSERT INTO `".PREFIX_FORUM."user_group` (`group_id`, `user_id`, `group_leader`, `user_pending`) VALUES ('2', '$phpbbid[0]', '0', '0')"); safe_query("INSERT INTO `".PREFIX_FORUM."user_group` (`group_id`, `user_id`, `group_leader`, `user_pending`) VALUES ('7', '$phpbbid[0]', '0', '0')"); mysql_close($con); } include('../_mysql.php'); mysql_connect($host, $user, $pwd) or system_error('ERROR: Can not connect to MySQL-Server'); mysql_select_db($db) or system_error('ERROR: Can not connect to database "'.$db.'"'); } So I need to be able to insert these rows using the while loop.. how can I do this? I really appreciate any help. Hi, can't get my head around this one! I have this code :- if (isset($_SESSION['cartid']) && !isset($_SESSION['lockedcard']) && isset($_POST['cartitem']) && isset($_POST['quantity']) && is_numeric($_POST['quantity'])) { if ($_POST['quantity'] > 0) {
Which I need to add an OR statement to : - (!isset($_SESSION['lockedpaypal']). if (isset($_SESSION['cartid']) && ($_SESSION['lockedpaypal'] != '1' || ['lockedcard'] != '1') && isset($_POST['cartitem']) && isset($_POST['quantity']) && is_numeric($_POST['quantity'])) { if ($_POST['quantity'] > 0) { Thanks! Hello all,
Am trying to use multiple if statement to check for data in the DB. everything seems fine till the last statement which is to insert the data in the DB if all the conditions are false. please, what am i doing wrong?
$tool = mysql_query("SELECT * FROM leave_member WHERE firstname = '$firstname' AND lastname = '$lastname' "); $fest = mysql_fetch_array($tool); if ($type == 'Annual Leave'){ $annual = $fest['annual']; if ($annual == '0') { echo "Sorry, you don't have any $type leave days available."; exit; } else if ($workingDays > $annual){ echo "Sorry, the number of days you are requesting is more than the number of days you have left. "; exit; } exit; } else if ($type == 'Sick Leave'){ $sick = $fest['sick']; if ($sick == '0') { echo "Sorry, you don't have any $type leave days available."; exit; } else if ($workingDays > $sick){ echo "Sorry, the number of days you are requesting is more than the number of days you have left. "; exit; } exit; } else if ($type == 'Compassionate Leave'){ $com = $fest['compassionate']; if ($com == '0') { echo "Sorry, you don't have any leave days available."; exit; } else if ($workingDays > $com){ echo "Sorry, the number of days you are requesting is more than the number of days you have left. "; exit; } exit; } else if ($type == 'Study Leave'){ $study = $fest['study']; //$result = $study - $days; //$com = $fest['study']; if ($study == '0') { echo "Sorry, you don't have any leave days available."; exit; } else if ($workingDays > $study){ echo "Sorry, the number of days you are requesting is more than the number of days you have left. "; exit; } exit; } else if ($type == 'Mertanity Leave'){ $maternity = $fest['maternity']; if ($maternity == '0') { echo "Sorry, you don't have any leave days available."; exit; } else if ($workingDays > $maternity){ echo "Sorry, the number of days you are requesting is more than the number of days you have left. "; exit; } exit; } $sql = mysql_query("INSERT INTO leave_request ( id, firstname, lastname, department, type, days, startdate, enddate, details, status) VALUES ( NULL, '$firstname', '$lastname', '$department', '$type','$workingDays', '$startDate', '$enddate','$details', '$status' )") or die(mysql_error());thanks in advance Folks, I am trying to learn PHP and I have spent the morning trying to sort out something seemingly simple but it is not working for me. I want to write a statement which says: if session variable "one" is empty or if session variable "two" is not equal to "svValue" then do this: if ((empty ($_SESSION["One"])) || if ($_SESSION["Two"] != "svValue ) { do this; } Could you point out the mistake(s) in my syntax? Thanks! John This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=312377.0 Hi there, I am working on a PHP web form. There is simple textbox where users can enter countries. If the user enters any of the European countries for example Spain, Germany or Italy then the web page must echo ' You entered a European country. The code I am using is: switch ($txtCountry) { case 'Germany' || 'Spain' || 'Belgium' || 'Cyprus' || 'Estonia': echo "You entered a European Country"; break; case 'Japan': echo "You entered a Far Eastern Country"; break; default: echo "Unknown Country"; break; } Now the problem is even if I enter a different country like Japan, it goes to the first Case: i.e. 'You entered a European Country' Whats the best way to use Switch case to check multiple values. Is my Syntax correct or do I need to use single quote of double quote here. Please reply. Thank you! I'm using the following code. I have tried placing parenthesis around $date1 and $date2 to separate them. No matter where I place the parenthesis Dreamweaver keeps giving me a syntax error. If I remove the second operator $date2 with the && the error goes. checked all my books but I can't see what is probably a stupid error ! Code: [Select] if ($row_sales_shipping_tax['cdate'] >= $date1 && <=$date2 ) Thanks for the help ! Hey, I was wondering if there is a way to pull multiple rows at once using a list of unique identifiers. For example, I want to pull the rows with the IDs of 4,13,91 and 252 I know the WHERE part of this query is incorrect, but I'm putting it to hopefully help you guys understand what I'm looking for. $result = mysql_query("SELECT * FROM $table WHERE id='4' OR '13' OR '91' OR '252'"); while($row = mysql_fetch_array($result)) { echo($row['name']); } Or is the best way simply to do it one query at a time without a while statement? There could be as many as a few dozen records being pulled per page. Hi, I'm modifying the following PHP code from a Wordpress plugin: /* Byline. */ if ( $instance['byline'] ) echo do_shortcode( "<p class='byline'>{$instance['byline']}</p>" ); /* Entry title. */ if ( 'widget' !== $instance['entry_container'] && $instance['entry_title'] && $show_entry_title ) { the_title( "<{$instance['entry_title']} class='entry-title'><a href='" . get_permalink() . "' title='" . the_title_attribute( 'echo=0' ) . "' rel='bookmark'>", "</a></{$instance['entry_title']}>" ); } elseif ( 'widget' !== $instance['entry_container'] && $show_entry_title ) { the_title( "<a href='" . get_permalink() . "' title='" . the_title_attribute( 'echo=0' ) . "' rel='bookmark'>", "</a>" ); } The output currently is: Code: [Select] [ December 13, 2010 ] Post Title I'm trying to combine the two so that the output appears on one line. What is the operator to execute multiple command in one statement? Thanks. Hello, Please excuse me if this sounds like a bit of a newb question. If I have a link to a users profile and use GET to pull information about that user from various tables using something like this: Code: [Select] <?php { $id = $_GET['id']; $user = mysql_query("SELECT * FROM users,tbl1,tbl2,tbl3,tbl4,tbl5 WHERE $id=tbl1.user_id AND tbl1.user_id=tbl2.user_id AND tbl2.user_id=tbl3.user_id ANDtbl3.user_id=tbl4.user_id AND tbl4.user_id=tbl5.user_id"); $user=mysql_fetch_assoc($user); } ?> <h3>Table 1</H3> <?php echo "<b>".$user['tbl1_title']."<br>"; ?><br /> <h3>Table 2</H3> <?php echo "<b>".$user['tbl2_title']."<br>"; ?><br /> <h3>Table 3</H3> <?php echo "<b>".$user['tbl3_title']."<br>"; ?><br /> <h3>Table 4</H3> <?php echo "<b>".$user['tbl4_title']."<br>"; ?><br /> <h3>Table 5</H3> <?php echo "<b>".$user['tbl5_title']."<br>"; ?><br /> Why does it only show the 1st record for that user from each table? And mostly, how do I change it to show all or a certain number of records from each table? Any help would be greatly appreciated. Thanks in advance I have a problem:
I have some PHP code as show below and every time I add the code at the while loop which starts while($select_stmt->fetch()), I immediately get an error and my page did not display. I downloaded the Zend Studio IDE and at the same line it highlights an error which states "Multiple annotations found at this line. Syntax error unexpected ->, unexpected ')'.
I have no clue how to resolve the error as I am new to PHP programming and the "Fix" option from the compiler offers no suggestions.
See the attached code file
Attached Files
code.txt 357bytes
2 downloads This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=312323.0 I have a table with 5 records with the following "id_number" for each record in ASC order: 2, 6, 74, 86,87 There is one other field called "tag_number" and for each record in ASC order here is the data: 50670, 50077, 1234, 1235, 1236 I have a text field and if I search for a spastic "tag_number" I want to return the record but count and display what record like this: Record 3 of 5 The above 3 of 5 means I searched for "1234". I'm not sure what loop I need and how to count the records, any help would be great! Here is what I'm thinking: $id_number = 74; $result = db_query("select * from table order by id_number ASC"); $num_rows = mysql_num_rows($result); //this will provide how many records are in the table $result = db_query("select * from table where id_number = '$id_number' order by id_number ASC"); for ($i = 1; $i == $num_rows; $i = $i + 1) { if ($result['id_number'] == $id_number) { Hi, I'm having a slight issue with some coding (see below). It worked a few minutes ago before I add "Packages" & "Safety & Technology" titles to the MySQL database. Hopefully the attached image has worked, but if it hasn't go to www.bikescarsandvans.co.uk/test.php and select the first Audi A3 additional extras drop down menu and you'll see whats going wrong. Code: [Select] $query_title = "SELECT * FROM extras JOIN car_to_extra ON (car_to_extra.extras_id = extras.id) WHERE car_to_extra.car_id = '{$car_row['id']}' ORDER BY extras.price ASC"; $title_results = mysql_query($query_title) or die ("Error in query: $query_title. ".mysql_error()); $current_heading = ''; print "<div class='addtional_extras'>";// ADDED TO TRY TO SORT OUT POSITIONING ISSUE while ($title_row = @ mysql_fetch_array($title_results )) { if ($current_heading != $title_row["title"]) { // The heading has changed from before, so print the new heading here. $current_heading = $title_row["title"]; print " <div class='title_tab2'>" . $title_row["title"] . "</div> "; } ?> <a class='data' href='#' onmouseout='hideTooltip()' onmouseover='showTooltip(event,"<?php print "" . $title_row["info"] . "<br/>(£" . $title_row["price"] . ")"; ?>");return false'> <?php print " <img class='extra_img' src=\"". $title_row["img"] ."\" alt='" . $title_row["img_alt"] . "' /></a> "; }// CLOSES WHILE LOOP ($title_row = @ mysql_fetch_array($title_results )) print "</div>";// CLOSES DIV IMAGE55 This isn't the entire code just enough to see what I'm trying to do. Everything was working until I added the mysql update query in the if statement. Is this possible or am I doing something wrong? When I run the script it just echos "No results found" twice as $num_results = 2. Code: [Select] <?php include("../includes/connect.php"); $query = "SELECT ........ "; $result = $db->query($query); $num_results = $result->num_rows; if ($num_results == 0) { exit; } else { $i=0; while ($i < $num_results) { $row = $result->fetch_assoc(); $id = $row['id']; if ($expiration_date > $today) { ### EMAIL CODE HERE ### $update = "UPDATE model SET reminder_sent = '1' WHERE id = '$id' "; $result_2 = $db->query($update); $i++; } else { echo "No results found."; $i++; } } } ?> |