PHP - Restricting Or Defining Search
I have a search code for my site and I want to narrow the scope of the search with a drop down that will allow users to pick a state, ( the sql table includes a state field ) or set the script so that i will only search for results for a particular state.
In the sql select I have tried every way of using WHERE venue_state='NY' but it will not work. I would really rather allow the users to select a state from a dropdown and then enter the search term - city, zip or venue name. Thank you for looking Code: [Select] <?php include('config.db.php'); $find = trim($_GET['find']); $field = $_GET['field']; if($find && $field) { // we have search form submitted // check for values to prevent sql injection $valid_fields = array("venue_zip", "venue_city" , "show_name"); if(!in_array($field, $valid_fields)) die("Error: Invalid field!"); $rpp = 10; // results per page $adjacents = 4; $page = intval($_GET["page"]); if(!$page) $page = 1; $reload = $_SERVER['PHP_SELF'] . "?find=" . urlencode($find) . "&field=" . urlencode($field); echo "<h4>Search Results for $find</h4>\n"; $find = addslashes($find); $result = mysql_query("SELECT *, DATE_FORMAT(`start_date`, '%b %e, %Y') AS s_date FROM craft_shows WHERE $field LIKE '%$find%'"); if(mysql_num_rows($result) == 0) { echo "<p>0 matches found.</p>"; } else { echo "<table class='table7' cellpadding='2'>"; echo "<tr><td> </td><td><strong>Date</strong></td><td><strong>Show Name</strong></td><td><strong>City</strong></td><td><strong>Attendance</strong></td></tr>"; echo "<tr><td colspan='5'><hr class=\"hr2\"></td></tr>"; // count total number of appropriate listings: $tcount = mysql_num_rows($result); // count number of pages: $tpages = ($tcount) ? ceil($tcount/$rpp) : 1; // total pages, last page number $count = 0; $i = ($page-1)*$rpp; while(($count<$rpp) && ($i<$tcount)) { mysql_data_seek($result,$i); $row = mysql_fetch_array($result); $id = $row['id']; echo "<tr><td>"; echo "<a href=\"/show_submits/show_detail.php?id=$id\">Details</a>"; echo "</td><td>"; echo $row['s_date']; echo "</td><td>"; echo $row['show_name']; echo "</td><td>"; echo $row['venue_city']; echo "</td><td>"; echo $row['venue_state']; echo "</td></tr>"; echo "<tr><td colspan='5'><hr class=\"hr3\"></td></tr>"; $i++; $count++; } echo "</table><br>"; function paginate_one($reload, $page, $tpages) { $firstlabel = "First"; $prevlabel = "Prev"; $nextlabel = "Next"; $lastlabel = "Last"; $out = "<div class=\"pagin\">\n"; // first if($page>1) { $out.= "<a href=\"" . $reload . "\">" . $firstlabel . "</a>\n"; } else { $out.= "<span>" . $firstlabel . "</span>\n"; } // previous if($page==1) { $out.= "<span>" . $prevlabel . "</span>\n"; } elseif($page==2) { $out.= "<a href=\"" . $reload . "\">" . $prevlabel . "</a>\n"; } else { $out.= "<a href=\"" . $reload . "&page=" . ($page-1) . "\">" . $prevlabel . "</a>\n"; } // current $out.= "<span class=\"current\">Page " . $page . " of " . $tpages . "</span>\n"; // next if($page<$tpages) { $out.= "<a href=\"" . $reload . "&page=" .($page+1) . "\">" . $nextlabel . "</a>\n"; } else { $out.= "<span>" . $nextlabel . "</span>\n"; } // last if($page<$tpages) { $out.= "<a href=\"" . $reload . "&page=" . $tpages . "\">" . $lastlabel . "</a>\n"; } else { $out.= "<span>" . $lastlabel . "</span>\n"; } $out.= "</div>"; return $out; } echo paginate_one($reload, $page, $tpages, $adjacents); } } ?> Similar TutorialsI am using the following to check that the user is logged on before he/she views pages on my site can I adapt what is here so that only some pages can be viewed by admin only? <?php include("../php/dbconnect.php"); //connects to the database //session code session_start(); //Check if user is authenticated if(!isset($_SESSION['username'])){ //User not logged in, redirect to login page header( "Location: http://webdev/schools/hhs/psy_bookings/" ); } else { //User is logged in, contiue (use session vars to diplay username/email) //echo "'Welcome, {$_SESSION['username']}. You are still logged in. <br />'"; // echo "'Your email address is: {$_SESSION['email']}.'"; }//end of session code ?> I assume this can be done somehow w/ PHP. How would I create a page which only displays based on detection of certain IP addresses and if the certain IP address is not detected, then redirects to a not allowed page. I have a list of the IP addresses to allow. Thanks in advance! So I have a very simple for loop that I am populating a list with levels and exp required to achieve the next level. I have been using a sandbox to test my output and have also created an excel sheet to replicate the data to verify the content. This code was not mine from the beginning and in creating the spreadsheet I discovered the flaw. Below is the code I am trying to fix: function experience($L, $pres = 0) { $a = 0; $end = 0; for ($x = 1; $x < $L; ++$x) { $a += $x * round($x + 5 * pow(4, ($x / 300))); } if ($x > 199) { $a += $x * round($x + 7 * pow(4, ($x / 290))); } if ($x > 399) { $a += $x * round($x + 11 * pow(4, ($x / 280))); } if ($x > 599) { $a += $x * round($x + 19 * pow(4, ($x / 270))); } if ($x > 799) { $a += $x * round($x + 35 * pow(4, ($x / 260))); } if ($x > 999) { $a += $x * round($x + 67 * pow(4, ($x / 250))); } return round($a / 1.25); } Below is the troubleshooting I am attempting to do (Modified and simplified for and while loop): //for loop $no = 200; $a = 0; for ($x = 1; $x < $no; ++$x) { $a += $x + 1; } if ($no > 199) { $a += $x + 2; } echo $a; //while loop $no = 200; $a = 0; $x = 1; while (($x - 1) < $no) { $a += $x * round($x + 5 * pow(4, ($x / 300))); $x++; if ($x > 199) { $a += $x * round($x + 7 * pow(4, ($x / 290))); } } echo $a; Upon request I can also provide snipets of the excel sheet. So the gist of what the issue I am having is this. Between level 199 and 200 the iteration of the loop is running one extra time through the initial formula. As you can tell at level 200, 400, 600, 800 and 1000 I want this formula to change so that it simplifies the amount of exp required to achieve the next level. I can not for the life of me figure out how to restrict the loop while still allowing the values 200 up to run through it for the first 199 iterations. The output I should get from the primary code for levels 199 through 201 are as follows: 199 = 200 = 201 = At level 199 I am good but for whatever reason it runs one additional iteration at the level 1-199 formula and then moves on to the 200 level formula messing up the values. Any and all help is much appreciated. I am a novice hobbyist at best and have been doing this for many, many years now but sometimes I get stumped. I chalk it up to lack of proper training and time to really be serious with it. Thanks in advance....NICON just wandering if this can be done and if so do you know were i can read about this or have any suggestion? i have a database with all are clients data that we store in it. I can now let them log into a php search screen that they can pull data from and see what we have stored. I would like to restrict what info they can pull by the user name they log in with, so they are not pulling other client info when they do the search. the user database and company database are two different ones. they search by box number and i would like to restrict what it pulls up by company name depending on if the user logged in has rites to that company info. so if jane doe logged in and she was a member of soso company when she did a box search she would only see what was from soso company instead of how it is now it pulls from soso, DD, and all the company's. Thanks in advance Hi, I have a web site that sells both video and images. The full versions are located securely behind a paywall, however in a bid to get visitors to purchase them and to promote the members offering I have trailer videos of 30 seconds to one minute and four free images per imageset. I want to be able to restrict the number of images a visitor can view for free to 12 and the number of videos a visitor can play to 5. With a little graphic/overlay notifying the user when they have exceeded their free play/preview limit. I have been advised that a tracking cookie and php if statement would be the way to go to achieve this. I have got a cookie that is successfully logging views that is written to on a free preview link as an onclick function. I have tried writing some php if code that will have the normal thumbnail or video divs display as usual if the views recorded in the cookie are below 12 or five, respectively, and have a not allowed, please subscribe div that would show over the thumbnails or video divs should the number of views exceed the threshold. My PHP code does not seem to be working at all, I have ran it through an online syntax checker - corrected the mistakes and now it's supposed to be working but opts to display nothing instead of either if argument. Videos then become a whole other problem because at the moment I have no other way to track the view/visit other than to count the loading of the video summary page with the free player as the preview, whether or not the clip is played - ideally I would like the view to be counted when the video begins to play. But I have no idea how to write to the cookie from Flash (is that even possible?) Any help would be greatly appreciated. Here is my situation. I have an exam application built in Flash, where after the taker is finished and submits their scores a record is created in MySQL in a log table. Basically there is a column called attempt which is populated with a 1 after they have successfully finished the exam. When this column has a 1, the user is locked out and cannot access the exam when they try and login. The Flash part was built a while back in AS3 and is very cumbersome to try and figure out and make changes, so I have been trying to improve some things on the PHP/MySQL end. What I have now is a php based login which uses if else statements to determine if a user has passed and if they have not uses a DELETE statement to delete their log record and thus they regain access to taking the exam. Code below. <?php if(($pcnt[$i]*100) > 89) { echo "<span class='green'>you did great!</span>"; } else { $query_delete = "DELETE FROM log_March2011 USING log_March2011 INNER JOIN roster_March2011 WHERE log_March2011.user_id =roster_March2011.user_id AND roster_March2011.user_id = '{$_SESSION['user_id']}'"; //echo $query_delete; //for debugging test $result_delete = mysql_query($query_delete) or trigger_error('Query failed: ' .mysql_error()); //$num = mysql_affected_rows($db); if ($result_delete) { echo "<span class='red'>Please review missed questions/sections below</span><br />You can now retake the exam"; }// end if else { echo "No record of taking exam"; } //end else } ?> what I would like to do to improve the application is to be able to implement a set number of attempts allowed before the user is disallowed to take the exam again, but not sure how to implement this or is even possible? Hi all I wonder if someone can help me, basically I have a HTML form with a free text area, which looks like Code: [Select] <textarea name="details"></textarea> when I submit the form, I can print what was outputted using $details = $_POST['details']; print $details; The user is able to either enter plain text, like Code: [Select] this is my website profile or they can enter some text and a URL, like Code: [Select] this is my website [http://www.google.com,2] profile My question is, when I do my print statement using print $details; how can I get it to convert what has been posted, so that it outputs the following HTML Code: [Select] this is <a href="http://www.google.com">my website</a> profile so basically it would create a link using what was entered between Code: [Select] [] and then use Code: [Select] ,2 to determine how many words before the URL should be linked, so in my example, just the words Code: [Select] my website would be linked, as I defined Code: [Select] ,2 following the URL in the code. But then further to this, if I entered 0, using Code: [Select] ,0 how can I then get it to link all the text, like Code: [Select] <a href="http://www.google.com">this is my website profile</a> i'm very new to PHP, so some guidance would be a great help Thanks very very much, been racking my brain on how to do this and have tried so many things, all with massive failure Hello Guys
I need help.
I found one PHP script for simple auto update of "system" (automatic updating of website for example)
http://maxmorgandesign.com/simple_php_auto_update_system/I want to adjust this script for my project, and In this code there is a line (on line 10): echo '<p>CURRENT VERSION: '.get_siteInfo('CMS-Version').'</p>';which variable should write in my page to define curent version of CMS? I try to googleit but unsuccessful :-/ Many thanks I need to define a query in a PHP script that will check a MySQL db - based on six variables (the six variables are statically defined within the script based on another snippet of code reading the new file that's being prepared for insertion into the db.) Objective: if the six variables, from the new records, does not produce an exact match already within the db based on ($rcheck) then insert the new record into the db. Note: I have the INSERT statement working correctly but having issues with the query ($rcheck). As for the records being checked by ($rcheck) in the MySQL db: they are all UNIQUE records based on the six fields I'm trying to build the query around to ensure no DUPLICATE entries are made with new insertions. ------------------- Issue: I can't get the query ($rcheck) to fire correctly to check the queued (new records' data) against the db - based on six fields of data. Error: Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource. FYI: if I just do a standard "SELECT * FROM information"; the quey works as it should but I need to check the db based on the six fields as shown in below code: $rcheck = "SELECT docno,fdate,ftime,vegregno,direction,grossmass FROM information where docno = $docnoNew AND fdate = $fdateNew AND ftime = $ftimeNew AND vegregno = $vegregnoNew AND direction = $directionNew AND grossmass = $grossmassNew;"; $duplicate = mysql_query(rcheck); // Execute query to check for duplicate transaction in table while ($row = mysql_fetch_array($duplicate)) { echo $row['docno']."<br/>"; echo $row['fdate']."<br/>"; echo $row['ftime']."<br/>"; echo $row['vegregno']."<br/>"; echo $row['direction']."<br/>"; echo $row['grossmass']."<br/>"; } I know the problem rests with trying to use multiple "AND" clauses but I'm not sure how to get around this issue. Any advice on how to define this query to check based on all six fields surely appreciated to get ($rcheck) working! thanks Can someone help me out, I had a guy make some great changes to a script. works perfectly - however I want to modify it further and he's unavailable till tomorrow to discuss. Hopefully someone will be able to guide me: define('TBL_PROFILE_COUNTRY_FILTER', '`country_id` = \'IE\''); This line is based on users in a database from Ireland (IE) but what I need to do is make it so that this TBL_PROFILE_COUNTRY_FILTER doesnt just filter Ireland members but also those from Northern Ireland (Ni) as well. So my question is this - can I (and if so how) - can I add Ni to this define statement. Grateful for any guidance (php isn't my thing at all but I'm trying to pick up what I need when I need it). Thanks again. What the hell am i missing here?? Trying to set the $output so if there are any errors it will display a message. If no email or password is entered the $output is echoed fine But if the wrong email or password is entered the $ouptut is not echoed at all??? if (loggedin()){ header ("Location: index.php"); exit(); } if (isset ($_POST['login'])) { $email= $_POST['email']; $password= $_POST['password']; if (isset ($_POST['rememberme'])) {$rememberme= $_POST['rememberme'];} if (isset($rememberme)) {$rememberme= "on";} else {$rememberme= "off";} if (empty($email)) {$output= "<span class='error'>Please enter a username or password</span>";} if (empty($password)) {$output= "<span class='error'>Please enter a username or password</span>";} if ($email&&$password) { $login= mysql_query ("SELECT * FROM user WHERE email='$email'"); while ($row= mysql_fetch_assoc($login)) { $passwordcheck = $row['password']; if (md5($password)==$passwordcheck) $loginok = true; else $loginok = false; if ($loginok==true) { $uniquelogon = "{$row['uniqlogon1']}"; if ($rememberme=="on"){ setcookie("uniquelogon", $uniquelogon, time()+2628000);} else if ($rememberme=="off"){ session_start(); $_SESSION['uniquelogon'] = "$uniquelogon";} header ("Location: index.php"); exit(); } else echo "<span class='error'>Your Email or Password do not match our records</span>"; } } } <?php if (!empty($output)) {echo $output;} ?> <form action"login.php" method="POST"> <p>Email:<br> <input type="text" name="email"> </p> <p>Password:<br> <input id="pwd" type="password" class="required lock pad" watermark="{html:'Password',cls:'pad empty'}" name="password"> </p> <p> <input type="checkbox" name="rememberme"> Remember Me!<br> </p> <input type="submit" name="login" value="Log In"> </form> Ive used all my special powers trying to get this to work, but i am missing something... I know that I have posted a similar question to this but I am still having some confusion that I hoped I could clear up. Thank you all for being patient with and helping me clean up this mess.
Below is the code that is spitting out the bottom error messages. So, I understand that the way to define a variable which uses += and not send it into a loop, generating a notice is this..
Using the top example
$meter_multiplier=0;
while ($row5 = sqlsrv_fetch_array($query5)){ meter_multiplier += $row5['meter_multiplier']; } versus... $meter_multiplier += $row5['meter_multiplier']; how can I implement this type of statment below. Should the php be called another name and reference sql that way, so the names are different? example $meter_multiplier=0; while ($row5 = sqlsrv_fetch_array($query5)){ meter_multiplier += $row5['meter_mult']; <?php $sql5 = "select meter_id, subaccount_number, service_name, service_address, service_address2, service_city, service_st, service_zip, service_contact, basic_charge, energy_charge, base_rate, intermediate_rate, peak_rate, meter_multiplier, raw_material_price FROM [radiogates].[dbo].[ops_invoice] where meter_id ='$comm_id' and subaccount_number='$session_id'";$query5 = sqlsrv_query($conn, $sql5);if ($query5 === false){ exit("<pre>".print_r(sqlsrv_errors(), true));}while ($row5 = sqlsrv_fetch_array($query5)){ $meter_multiplier += $row5['meter_multiplier']; $raw_material_price += $row5['raw_material_price']; $basic_charge += $row5['basic_charge']; $peak_rate += $row5['peak_rate']; $intermediate_rate += $row5['intermediate_rate']; $energy_charge += $row5['energy_charge']; $base_rate += $row5['base_rate']; $account_number = $row5['meter_id']; $service_name = $row5['service_name']; $service_address = $row5['service_address']; $service_address2 = $row5['service_address2']; $service_city = $row5['service_city']; $service_st = $row5['service_st']; $service_zip = $row5['service_zip'];} sqlsrv_free_stmt($query5); ?>Notice: Undefined variable: meter_multiplier in C:\xampp1\htdocs\Utrack\invoice.php on line 335 Notice: Undefined variable: raw_material_price in C:\xampp1\htdocs\Utrack\invoice.php on line 335 Notice: Undefined variable: basic_charge in C:\xampp1\htdocs\Utrack\invoice.php on line 335 Notice: Undefined variable: peak_rate in C:\xampp1\htdocs\Utrack\invoice.php on line 335 Notice: Undefined variable: intermediate_rate in C:\xampp1\htdocs\Utrack\invoice.php on line 335 Notice: Undefined variable: energy_charge in C:\xampp1\htdocs\Utrack\invoice.php on line 335 Notice: Undefined variable: base_rate in C:\xampp1\htdocs\Utrack\invoice.php on line 335 Edited by Butterbean, 10 January 2015 - 06:34 PM. Is it possible to define a variable's type at the start of your code? I believe you can "cast" a variable, but can I do something like this... Code: [Select] name string; age integer; gender string; children array; single: boolean; I know some people say PHP is better suited for the web because it is loosely-typed, but I'm anal-retentive and like my structure!! TomTees Hi, I my first problem is hashing passwords to md5. My second problem is defining session on value from db. There is my code but not working. Code: [Select] mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); $username=$_POST['username']; $password=$_POST['password']; $hash = md5($password); $username = stripslashes($username); $password = stripslashes($password); $username = mysql_real_escape_string($username); $password = mysql_real_escape_string($password); $sql="SELECT * FROM $tbl_name WHERE where username = '$username' and password = '$hash'"; $result=mysql_query($sql); $count=mysql_num_rows($result); if($count==1){ $sql2="SELECT access FROM $tbl_name WHERE username='$username' and password='$password'"; $access=mysql_query("$sql2"); session_register("username"); session_register("password"); session_register("access"); $_SESSION["access"]=$access; header("location:success.php"); } else { echo "Invalid Username or Password";Thanks for any answers. I am trying to define a session variable where I can save it and use it as the user surfs the site. I need the variable saved as $amano so I can use it in my select from/where statement and to echo within a table. This is a test trying to capture and define the variable and works, but I can't get the variable $amano into the session. If I am then I don't know how to display it. <?php> session_start(); $id = $_POST['amano']; $_SESSION['amano'] = '$amano'; echo "Pageviews = ". $_SESSION['amano']; // My effort to see what is happening. echo "<br />"; echo "AMA # = ". $_POST['amano']; // I have it just like I want it here. echo "<br />"; echo "Sessions AMA # = ".$_SESSION['amano']; ?> // does the product exist ? $sql = "SELECT pd_id, pd_qty FROM tbl_product WHERE pd_id = $productId"; $result = dbQuery($sql); if (dbNumRows($result) != 1) { // the product doesn't exist header('Location: cart.php'); } else { // how many of this product we // have in stock $row = dbFetchAssoc($result); $currentStock = $row['pd_qty']; if ($currentStock == 0) { // we no longer have this product in stock // show the error message setError('The product you requested is no longer in stock'); header('Location: cart.php'); exit; } } // current session id $sid = session_id(); session_register("size"); $size = $_SESSION['size']; // check if the product is already // in cart table for this session $sql = "SELECT pd_id FROM tbl_cart WHERE pd_id = $productId AND ct_session_id = '$sid'"; $result = dbQuery($sql); if (dbNumRows($result) == 0) { // put the product in cart table $sql = "INSERT INTO tbl_cart (pd_id, ct_qty, size, ct_session_id, ct_date) " . "VALUES ($productId, 1, '$size', '$sid', NOW())"; $result = dbQuery($sql); } else { // update product quantity in cart table $sql = "UPDATE tbl_cart SET ct_qty = ct_qty + 1 WHERE ct_session_id = '$sid' AND pd_id = $productId"; $result = dbQuery($sql); } This is just a piece of my cartfunctions.php (which is an include() once you add an item to the cart). I've been trouble shooting this all day and finally got it to stop giving me error messages. Im trying to allow the user to pick a size between 4 options, after that it is added to the cart and I can easily find out what size shirt the customer wants before I ship it. but now it wont update the $size variable to the DB. Am I defining this wrong or maybe my whole approach is messed up? If you would like to see the setup you can go to rbcrime.com/newshop/newshop/ . Hello, I'm using the below code to determine whether fields have been left blank, however, it only a standard sentence, i'd like to customise it, like: "Email has been left blank" or The email and message has been left blank. My best preference would be to bullet point each line. IE: Email has been left blank. Message has been left blank. $name = $_POST['name']; $visitor_email = $_POST['email']; $user_message = $_POST['message']; if(empty($name)|| empty($visitor_email)|| empty($user_message)) { $errors .= "\n Some of the above fields have not been filled in.<br><br> "; } Many thanks. Hey Guys. I came across this code example below assigns array values to a private property. However the private property is not defined as an array. It was a bit confusing to me because I always thought you need to define the property as an array first. If someone can please help me understand this concept I would really appreciate it.
Below is the code.
<?php class Product { public $name; public $price; function __construct($name, $price){ $this->name = $name; $this->price = $price; } } class ProcessSale { private $callbacks; // This holds an array but is not defined as an array? function registerCallback($callback) { if(!is_callable($callback)) { throw new Exception("Callback Is Not Callable"); } $this->callbacks[] = $callback; } function sale($product) { print "{$product->name}: processing \n"; foreach ($this->callbacks as $callback) { call_user_func($callback, $product); } } } $logger = function($product) { print "logging ({$product->name})\n"; }; $processor = new ProcessSale(); $processor->registerCallback($logger); $processor->sale(new Product("shoes", 6)); echo "\n"; $processor->sale(new Product("coffee", 6)); i am building a reservation system i have special date blocks which have different price tags for example reservation for 01/12/2011-07/12/2011 where 03/12/2011-06/12/2011 prices +15% how would i define the range for special dates? Have a ton of pop-up javascript links in my page. To tidy up the code, I have decided to declare all links at top of the page to keep them together and simply use the variable within the "a" brackets. Let me show you: Code: [Select] <? $brand_edit = 'javascript:void(0)"onclick="window.open('/admin/form.php?db=outlet&tbl=brands&auto_increment=<? echo $auto_increment; ?>&action=edtamp;step=1','none','width=750,height=250,menubar=no,status=no,resizable=no,location=no,toolbar=no,scrollbars=yes,left=50,top=50,titlebar=no')'; ?> <span class="float" style="width: 100px;"><a href="<? echo $brand_edit; ?>"><? echo $auto_increment; ?></a></span> However, something things to go wrong as I'm getting an "Parse error: syntax error, unexpected '=' in ... on line 12" Where am I going wrong with my syntax? |