PHP - Fine Tuning Like Statements
Im a newbie trying to get my head around php and sql, please can anyone help me with a statement,
or point me to a place where I can find out? - have tried w3schools. How can I get my like statement to only compare the first two charracters of a value? Let's say $code = EN7 6PX (user has typed this into a html form) for eg . SELECT email FROM treesurgeons WHERE postcode LIKE '%$code%' How can I tell my like statement to only take notice of the first two charracters of the post code (in this case 'EN')? So that I get returned EN4 1PP, EN5 6RT, EN7 3OL etc. Similar TutorialsThis script was working fine yesterday i havn't changed anything?? not it don't register the user upon completing the script no error, just when you hit submit it refreshes and does nothing? <?php //check for submit $submit =$_POST['submit']; //gather POST variable $fullname =strip_tags($_POST['fullname']); $email =strip_tags($_POST['email']); $username =strip_tags($_POST['username']); $password =strip_tags($_POST['password']); $password2 =strip_tags($_POST['password2']); if ($submit) { //check that fields were filled in if ($fullname&&$email&&$username&&$password&&$password2) { //check to see if our two password fields match if ($password==$password2) { $password = md5($password); // register the user //open database $connect = mysql_connect("localhost", "root", ""); mysql_select_db("users"); //begine insert $queryreg = mysql_query("INSERT INTO members VALUES ('','inet_aton('127.0.0.1')','$fullname','$email','$username','$password')"); if ($queryreg) { echo "Thanks, For Registering! Click <a href=\"index.php\">HERE</a>To Login!"; } } //otherwise if passwords don't match else { echo "<font color='red'>The passwords you entered do not match</font>"; //end of checking password } } else { echo "<font color='red'>Please enter all fields!</font>"; } } //end check for submit ?> <form action='testreg.php' method="post"> <table align="center"> <tr> <td> Your Full Name: </td> <td> <input type="text" name="fullname" value="<?php echo $fullname; ?>"> </td> </tr> <tr> <td> Email Address: </td> <td> <input type="text" name="email" value="<?php echo $email; ?>"> </td> <tr> <td> Choose Username: </td> <td> <input type="text" name="username" value="<?php echo $username; ?>"> </td> </tr> <tr> <td> Password: </td> <td> <input type="password" name="password"> </td> </tr> <tr> <td> Retype Password: </td> <td> <input type="password" name="password2"> </td> </tr> </table> <p> <center><input type="submit" name="submit" value="Register"></center> </form> The below is constantly loading the password page no matter what is enter in the password input on the form (on another page). I have checked the $login variable by echoing it and it is carrying the value from the field. <?php $off="yes"; $login=$_POST['login']; if($off=="yes" && (!isset($_SESSION['login']) || $_SESSION['login']!="pass")){ if($login=="" || $_SESSION['login']!="pass"){ header('Location: ./index2.html'); exit(); } elseif(!isset($_SESSION['login'])){ session_start(); $_SESSION['login']=$login; header('Location: ./index.php'); exit(); } } elseif($off=="no" || $_SESSION['login']=="pass"){ content goes here. } ?> Hi Guys, Newbie trying to understand PHP conditionals. In the below Code: [Select] [[*id]] is a global variable which equates to my current page id so it could have the value of 1 for example. I tested it using echo and the correct values pass to it in the cms I'm using. What I cant achieve is for the conditionals below to work correctly so perhaps you can see a syntax error or show me away of doing the same using an array or something perhaps? THANKS Code: [Select] <?php $id='[[*id]]' if ($id=="1" || $id=="2") echo "we are in 1 or 2"; elseif ($id=="3" || $id=="4") echo "we are in 3 or 4"; else echo "not in 1 to 4"; ?> How to write 2 "if" statements together? if($userResult==$myResult) and ($userResult<0) { Hey Guys, I am creating an array and I have a need to put a if statement inside it. Is this even possible? Here is where I am at so far, its just not working. function load_permissions($gid) { $data = array(); $this->db->select('`groups`.`name` AS `permission_name`, `permissions`.``'); $query = $this->db->get('`groups`,`permissions`'); if ($query->num_rows() > 0){ foreach ($query->result_array() as $row){ $data[] = array( "name" => $row['permission_name'], "read" => if($row['level'] >= 1) { img("img/true.gif") } else { img("img/false.gif") }, ); } } $query->free_result(); return $data; Thanks, Peter Hey guys, is there any way to have a LIKE condition on an IF statement? Something like: Code: [Select] if $GET_['WTV'] LIKE %LOVE% { $category=romance Any clues? Thanks in advance. Anything wrong with this because I got a parse error ONLY after adding to create this. <?php $visible = array('Yes', 'No'); foreach($visible as $visible): $visible2 = array('yes', 'no'); foreach($visible2 as $visible2): ?> I am trying to write an if statement that checks to make sure the information put in the text box is an imbedded file. Does anyone know how to do that? Hello, I am learning PDO SQL statements, I have mananged to connect using PDO: Code: [Select] try { $this->link = $dbh = new PDO('mysql:host='.$this->dbhost.';dbname='.$this->dbname.'', $this->dbuser, $this->dbpass); } catch (PDOException $e) { echo 'Connection failed: ' . $e->getMessage(); } I am not getting any error, so I guess that is a good start. I then tried the PDO SQL statement out. My old mySQL query is commented out in the Code: [Select] if (isset($_SESSION['id']) && isset($_SESSION['password'])) { $_SESSION['id'] = ( isset( $_SESSION['id'] ) ) ? $_SESSION['id'] : FALSE; $_SESSION['password'] = ( isset( $_SESSION['password'] ) ) ? $_SESSION['password'] : FALSE; //$logged = mysql_query("SELECT * FROM `db_members` WHERE `id`='".$_SESSION['id']."' AND `password` = '".$_SESSION['password']."'"); //$logged = mysql_fetch_array( $logged ); // the new pdo statement $ff = $dbh->prepare('SELECT * FROM db_members WHERE id = '.$_SESSION['id'].' AND password = '.$_SESSION['password'].''); $ff->execute(); $logged = $ff->fetchAll(); echo $logged['username']; } I am trying to assign the session to logged variable. So all I am asking is go into db_members and check the id and password that is the same as session id and password and collect the rows data such as username. My login script and everything works perfectly, even session id and password is valid when echo'd but I cannot assign it to the logged variable like my old sql statements. Code: [Select] $logged = mysql_query("SELECT * FROM `db_members` WHERE `id`='".$_SESSION['id']."' AND `password` = '".$_SESSION['password']."'"); $logged = mysql_fetch_array( $logged ); I used other PDO statements and it works perfectly but I just don't understand why this is not working.... can I please get some help if you have any solution to this? I need to insert a large variable number of records into a mysql table. I can do this using a while loop and insert queries in the loop but its slow and ive been given to understand its a bad idea. I have heard that I can insert multiple rows with one query, but how to construct the query? This code can perfectly and reliably display a statement with echo: Code: [Select] <?php $querytestquery='"INSERT INTO test(qval1, qval2) VALUES'; echo $querytestquery; $querymax=10; $querystart=0; while ($querystart<$querymax) { $qval1=1*$querystart; $qval2=2*$querystart; $queryadd="($qval1, $qval2)"; echo $queryadd; if ($querystart<$querymax-1) { echo ','; } $querystart++; } echo '"'; ?> "INSERT INTO test(qval1, qval2) VALUES(0, 0),(1, 2),(2, 4),(3, 6),(4, ,(5, 10),(6, 12),(7, 14),(8, 16),(9, 18)" But I don't understand how to set a variable equal to the displayed query so that I can have php construct the statement based on the values and the number of records I want to update or insert. Hello: I am writing this code: Code: [Select] <?php include('include/myConn.php'); include('include/myCodeLib.php'); $zip_id = $_REQUEST['zip_id']; $query=mysql_query("SELECT zip_id,city,full_state,zip FROM zip_codes WHERE zip_id = $zip_id") or die("Could not get data from db: ".mysql_error()); while($result=mysql_fetch_array($query)) { $zip_id=$result['zip_id']; $city=$result['city']; $full_state=$result['full_state']; $zip=$result['zip']; } ?> <!DOCTYPE HTML> <head> <title></title> </head> <body> <?php echo $city; ?>, <?php echo $full_state; ?> <?php echo $zip; ?> </body> </html> It works fine as far as writing out the "City, State Zipcode", but I wanted to see if there is a way to "join" the 3 statements together so it can be written as just 1 statement. Like: Code: [Select] <?php echo $city, $full_state $zip; ?> What is the trick to doing this? Thanks in advance. Okay i'm trying to compare these sets of variables. code looks like this.. Code: [Select] if( $row->cash > $finalcash && $row->core1 > $finalcore1 && $row->core2 > $finalcore2 && $row->core3 > $finalcore3 && $row->core4 > $finalcore4 ) { return true; } else { return false; } First question is this the appropriate way of doing this? Or would a nested if statement work better? example: Code: [Select] if ($row->cash > $finalcash) { if ($row->core1 > $finalcore1) { if ($row->core2 > $finalcore2) { if ($row->core3 > $finalcore3) { if ($row->core4 > $finalcore4) { } else { return false; } } else { return false; } } else { return false; } } else { return false; } } else { return false; } I know it looks pretty messy, so i'm wondering if anybody is aware of an alternative to achieving this? this is working fine : Code: [Select] while($tags=mysql_fetch_array($d_b->sql_answer,MYSQL_ASSOC)){ echo $tags['tag_name'] . "<br/>"; } display : Code: [Select] html css javascript c++ php but when i try to do some sql statements inside like this : Code: [Select] while($tags=mysql_fetch_array($d_b->sql_answer,MYSQL_ASSOC)){ $sql="SELECT * FROM user WHERE user_languages LIKE '% {$tags[tag_name]} %'"; //to apply the $sql $d_b->apply($sql); //number of results $num=$d_b->num_rows(); $sql="UPDATE tags SET tag_folowers={$num}"; $d_b->apply($sql); } it return an error : Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given If my SQL statement returns a result I want to change the background color of a cell. If the user is logged in I want to then show one of two buttons. either book, or cancel, depending on whether the cell is available or not. So far I have this: $sql = "SELECT * FROM diary WHERE day = '$mon' AND studio_id ='mon11'"; $query = mysql_query($sql) or die (mysql_error()); if (mysql_num_rows($query) < 1) { $bgcolour= '#5DFC0A'; if(isSet($_SESSION['logged'])) { $book = '<form action="../book.php" method="POST"><input type="hidden" name="day" value='.$mon.' type="text"/><input type="hidden" name="month" value='.$month.' type="text"/><input type="hidden" name="year" value='.$year.' type="text"/><input type="hidden" name="book_id" value="mon11" type="text"/><input type="submit" name="submit" value="Book!"></form>'; }} else { $bgcolour= '#FF0000'; } if(isSet($_SESSION['logged'])) { $book = '<form action="../cancel.php" method="POST"><input type="hidden" name="day" value='.$mon.' type="text"/><input type="hidden" name="month" value='.$month.' type="text"/><input type="hidden" name="year" value='.$year.' type="text"/><input type="hidden" name="book_id" value="mon11" type="text"/><input type="submit" name="submit" value="Cancel!"></form>'; } echo "<td rowspan='3' bgcolor=".$bgcolour.">"; if (isset($book)) { echo $book; } I want to use the $session(logged) variable to show the appropriate button, but I can't get it to work in the other if statement, Any ideas? Todays date is between the criteria in if else, but it is not catching it. Code: [Select] <?PHP $today = date('Y-m-d'); $sunday = date('Y-m-d', strtotime('last Sunday', strtotime('last Saturday'))); $saturday = date('Y-m-d', strtotime('last Saturday')); $firstday = date('Y-m-d', strtotime('next Sunday', strtotime('last Friday', strtotime('first day of last month')))); $lastday = date('Y-m-d', strtotime('next Saturday', strtotime('last Friday', strtotime('first day of this month')))); $thisfirstday = date('Y-m-d', strtotime('next Sunday', strtotime('last Friday', strtotime('first day of this month')))); $thislastday = date('Y-m-d', strtotime('next Saturday', strtotime('last Friday', strtotime('first day of next month')))); echo"$today<hr />$firstday<br />$lastday<hr />$thisfirstday<br />$thislastday"; if($firstday>="$today" && $lastday<="$today") { $month = date('m', strtotime('-10 days', strtotime('next Saturday', strtotime('last Friday', strtotime('first day of this month'))))); $year = date('Y', strtotime('-10 days', strtotime('next Saturday', strtotime('last Friday', strtotime('first day of this month'))))); echo"1<br />$month|$year"; } elseif($thisfirstday>="$today" && $thislastday<="$today") { $month = date('m', strtotime('-10 days', strtotime('next Saturday', strtotime('last Friday', strtotime('first day of next month'))))); $year = date('Y', strtotime('-10 days', strtotime('next Saturday', strtotime('last Friday', strtotime('first day of next month'))))); echo"3<br />$month|$year"; } ?> output: Code: [Select] 2011-10-10<hr />2011-08-28<br />2011-10-01<hr />2011-10-02<br />2011-10-29 i have been trying to make this work for days, this needs to also include a discount for staying over >=5 days in Tokyo, no matter what i do i always gets syntax error this class is making me crazy how do i go about getting the discount in this????? please help <?php $destination = $_POST['destination']; $numTravelers = $_POST['numTravelers']; $numNights = $_POST['numNights']; $airFare = $_POST['airFare']; $hotel = $_POST['hotel']; if ($destination == Barcelona) {$airFare = 875.00; $perNight = 85.00;} elseif ($destination == Cairo) {$airFare= 950.00; $perNight = 98.00;} elseif ($destination == Rome) {$airFare = 875.00; $perNight = 110.00;} elseif ($destination == Santiago) {$airFare = 820.00; $perNight = 85.00;} elseif ($destination == Tokyo) {$airFare = 1575.00; $perNight = 240.00;} this is where i can not figure out how to put in the discount off the airfare for staying over five days elseif ($destination == Tokyo && $numNights >=5) $tickets = $numTravelers * $airFare; $hotel = $numTravelers * $numNights * $perNight; $totalCost = $tickets + $hotel; print("<p>Destination: $destination<br />"); print("Number of people: $numTravelers<br />"); print("Number of nights: $numNights<br />"); print("Airline Tickets: $".number_format($tickets, 2)."<br />"); print("Hotel Charges: $".number_format($hotel, 2)."</p>"); print("<p><strong>TOTAL COST: $".number_format($totalCost, 2)."</strong></p>"); ?> Hello, I'm currently working on just a quick little frontend for VirtualBox and I'm just running into a little bit of a problem that I can't find my way around. Now this is my first project in php. I'm familiar with programming concepts (well except this one apparently ) and by familiar were talking I like to tinker with small languages.. no formal training. Anyway, here we go. So heres the main page. Pretty simple, you type the argument that goes with the following command and check the box next to the command you'd like to execute. Code: [Select] <HTML> <HEAD> <TITLE>LCCP ver1</TITLE> </HEAD> <BODY> <?php include "header.php"; ?> <form method="post" action="lccp_ver1.php"> <p>cmd="createvm"<br> Enter the name of the Virtual Guest you'd like to create: <input type="text" name="id"> <input type="checkbox" name="createvm"> </p> <p>cmd="showvrtinfo"<br> Enter the name of the Virtual Machine you'd like to view: <input type="text" name="id2"> <input type="checkbox" name="showvminfo"> </p> <p>cmd="unregistervm"<br> Enter the name of the Virtual Guest you'd like to delete: <input type="text" name="id3"> <input type="checkbox" name="unregistervm"> </p> <p>cmd="startvm"<br> Enter the name of the Virtual Machine you'd like to start: <input type="text" name="id4"> <input type="checkbox" name="startvm"> </p> <p>cmd="controlvm"<br> Enter the name of the Virtual Machine you'd like to control: <input type="text" name="id5"> <input type="checkbox" name="controlvm"> </p> <p>Then.. would you like to...</p> <p>arg="pause" <input type="checkbox" name="controlvm_pause"></p> <p>arg="resume" <input type="checkbox" name="controlvm_resume"></p> <p>arg="reset" <input type="checkbox" name="controlvm_reset"></p> <p>arg="poweroff" <input type="checkbox" name="controlvm_poweroff"></p> <p>arg="savestate" <input type="checkbox" name="controlvm_savestate"></p> <input type="submit" name="Submit" value="Submit"> </form> </BODY> </HTML> And then here is the execution page Code: [Select] <HTML> <HEAD> <TITLE>LCCP command <?php function ServerLoad() { $stats = exec('uptime'); preg_match('/averages?: ([0-9\.]+),[\s]+([0-9\.]+),[\s]+([0-9\.]+)/', $stats, $regs); return ($regs[1].', '.$regs[2].', '.$regs[3]); } echo ServerLoad(); ?> </TITLE> </HEAD> <BODY> <?php include "header.php"; ?> <?php function createvm($id) { $output = shell_exec("VBoxManage createvm --name " . $id . " --register"); return $output; } function showvminfo($id) { $output = shell_exec("VBoxManage showvminfo " . $id); return $output; } function unregistervm($id) { $output = shell_exec("VBoxManage unregistervm ". $id ." --delete"); return $output; } function startvm($id) { $output = shell_exec("VBoxManage startvm ". $id ." --type headless"); return $output; } function controlvm($id,$arg) { $output = shell_exec("VBoxManage controlvm ". $id ." ". $arg); return $output; } function print_output($output) { echo' <pre>'. $output . ' </pre>'; } //******************exec main********************** if (isset($_POST['createvm'])) { // createvm($_POST['id2']); print_output(createvm($_POST['id'])); } if (isset($_POST['showvminfo'])) { // showvminfo($_POST['id']); print_output(showvminfo($_POST['id2'])); } if (isset($_POST['unregistervm'])) { // unregistervm($_POST['id3'); print_output(unregistervm($_POST['id3'])); } if (isset($_POST['startvm'])) { // startvm($_POST['id4']); print_output(startvm($_POST['id4'])); } if ((isset($_POST['controlvm'])) AND (isset($_POST['controlvm_pause'))) { //controlvm($_POST['id5']," pause"); print_output(controlvm($_POST['id5']," pause")); } if ((isset($_POST['controlvm'])) AND (isset($_POST['controlvm_resume'))) { //controlvm($_POST['id5']," resume"); print_output(controlvm($_POST['id5']," resume")); } if ((isset($_POST['controlvm'])) AND (isset($_POST['controlvm_reset'))) { //controlvm($_POST['id5']," reset"); print_output(controlvm($_POST['id5']," reset")); } if ((isset($_POST['controlvm'])) AND (isset($_POST['controlvm_poweroff'))) { //controlvm($_POST['id5']," poweroff"); print_output(controlvm($_POST['id5']," poweroff")); } if ((isset($_POST['controlvm'])) AND (isset($_POST['controlvm_savestate'))) { //controlvm($_POST['id5']," savestate"); print_output(controlvm($_POST['id5']," savestate")); } //**********working on*************** //teleport? ?> </BODY> </HTML> Now my question is with the if statements. Well, number one I guess is there a more efficient way of doing this that I'm overlooking? I looked into switches but I don't know how I'd pull that off with checkboxes without some complicated loop and somehow converting the checkboxes "yes" or "nos" into numbers or something. If statements just seemed like less of a headache but I may be finding otherwise haha. Number two here is how do I get the "controlvm" command to work? When I comment out that last indented lines of if statements the program runs perfect (and thats with the controlvm function as well. so.. the problem isn't there). Basically whats the appropriate way to do this. I'm stuck and my limited program knowledge and Google searching is starting to run thin. Thanks in advance for the help! I am trying to dynamically create a form where I pass a table name and it presents me with a table of all the columns (varying number and names of columns) into an HTML table. Both of my queries are working, but for some reason, my nested while statements are not working. Any ideas? function getLuTableBody($lu_tableName) { $tableBodyHtml =""; $tableColumns=getTableColumns($lu_tableName); $tableData=getTableData($lu_tableName); if ($tableData->num_rows > 0) { while($row = $tableData->fetch_assoc()) { if ($tableColumns->num_rows > 0) { $tableBodyHtml .= "<tr>"; while($column = $tableColumns->fetch_assoc()) { $columnName=$column['COLUMN_NAME']; $tableBodyHtml .= "<td>$row[$columnName]<td>"; } $tableBodyHtml .= "</tr>"; } else { echo "problem with column data"; } } } else { echo "problem with record data"; } return $tableBodyHtml; }
Here's the contents of the db id bundleRole recordStatus 1 Database A 2 Web A 3 Base A 4 Application A 5 Print A
<table id="advanced_table" class="table dataTable"> <thead> <tr> <th>Record ID</th> <th>Bundle Role</th> <th>Record Status</th></tr> </thead> <tbody> <tr> <td>1</td> <td></td> <td>Database</td> <td></td> <td>A</td> <td></td> </tr> </tbody> </table> Edited June 13, 2020 by pizote added detail I can't get these two if, elseif and else statements too work, here is the code: if(empty($this->password)){ $this->errors[] = 'You must enter a password!'; } elseif(!strlen($this->password) >= 6){ $this->errors[] = 'Your password must be longer than 6 characters!'; } if(empty($this->email)){ $this->errors[] = 'You must enter an email address!'; } elseif(!preg_match('/^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]{2,4}$/',$this->email)){ $this->errors[] = 'Your password can only contain these characters: a-z, A-Z and 0-9!'; } if(empty($this->confemail)){ $this->errors[] = 'Please confirm your email address!'; } elseif(!$this->confemail == $this->email){ $this->errors[] = 'The email addresses you entered did not match!'; } The if and elseif statements for "email" work just fine but the other 2 doesn't. With the "password" i first want to check if the field is empty, and when it is, it works as it should. But when i for example type "test" too check if the password is longer than 6 characters i don't get any message at all? With the "confemail" i want to first check if the field is empty, and when it is, it works as it should. But when i type in "test@test.com" in both fields to try to compare "confemail" to "email" i still get the "Please confirm your email address!" message? How could I make it so that if the $date variable is past than $memberdate then something shows else something else does. <?php $date = date('Y-m-d H:i:s', time()-3600); $memberdate = '2011-01-29 01:03:28'; ?> Thanks in advance, I realised I could convert it into a unix timestamp but there must be a better way. Ty. |