PHP - Return Value If Isset (form)
Hey Guys,
Im working with a form and need some help. So at the moment i have got it working so that if the user doesn't select the values from the drop down list, an error will occur saying 'Please select all fields'. What i want to do now is make it so that if this error occurs, the value of the drop down list will stay as it is an NOT reset. Could someone help me out? * Note that the code below is currently ok, basically it checks if there is a value, if not it will say "Select Player". Code: [Select] <td>Prop</td> <td><select name="prop1" style="width: 150px"> <option value="<? echo $row['prop1']; ?>"><? if (empty($row['prop1'])) { echo "Select Player"; } else { echo $row['prop1']; } ?></option> <?php echo $option_str; ?> </select></td> <td>16.</td> <td><select name="r16" style="width: 150px"> <option value="<? echo $row['r16']; ?>"><? if (empty($row['r16'])) { echo "Select Player"; } else { echo $row['r16']; } ?></option> <?php echo $option_str; ?> </select></td> Similar TutorialsI have a form that is supposed to use PHP to display errors next to incomplete form fields when the form is submitted. But I am never getting into my PHP loop. I tried using the print_r(true) function to debug, but no luck. When I click submit I see this i the URL... http://localhost/00_MyWebSite/zzEmptyPHP.php?firstName=&lastName=&submit=Process+Order&submitted=true which is what I would expect on a blank form being submitted. Here is my code... Code: [Select] <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link type="text/css" rel="stylesheet" href=".css"> <style type="text/css" > form{ width: 400px; margin: 0 auto; } </style> </head> <body> <?php // Initialize. $errors = array(); $errors['firstName'] = ''; $errors['lastName'] = ''; $firstName = $lastName = ''; echo "print_r = " . print_r(true); if (isset($_POST['submit'])){ // Handle Form. // Trim all incoming data. $trimmed = array_map('trim', $_POST); // Check First Name. if (preg_match('/^[A-Z\'.-]{2,20}$/i', $_POST['firstName'])){ $firstName = $_POST['firstNamae']; }else{ $errors['firstName'] = 'Please enter your First Name.'; } // Check Last Name. if (preg_match('/^[A-Z\'.-]{2,20}$/i', $_POST['lastName'])){ $lastName = $_POST['lastName']; }else{ $errors['lastName'] = 'Please enter your Last Name.'; } // if there are errors then go back to the form and display them }else{ } ?> <form action=""> <fieldset> <legend>Billing Details</legend> <ol> <li> <label for="firstName">First Name:</label> <input id="firstName" name="firstName" class="text" type="text" /> <?php echo $errors['firstName']; ?> </li> <li> <label for="lastName">Last Name:</label> <input id="lastName" name="lastName" class="text" type="text" /> <?php echo $errors['lastName']; ?> </li> </ol> <input type="submit" name="submit" value="Process Order" /> <input type="hidden" name="submitted" value="true" /> </fieldset> </form> </body> </html> Any ideas what I am doing wrong? Thanks, Debbie Hi all, Hoping someone can help with what i would guess is a very simple problem. I have the following code which is suppose to display a form. the form posts to itself and uses isset and if the form has been posted it doesnt display the form. if (isset($_POST['submit'])) { echo "question submitted successfully"; } else { echo '<form method="post" name="qanda" id="qanda" action="http://' . $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"] . '">'; echo '<p><label for="name">Name</label> <input type="text" id="name" /></p>'; echo '<p><label for="e-mail">E-mail</label> <input type="text" id="e-mail" /></p>'; echo '<p><label for="Question">Question</label> <textarea rows="6" id="question"></textarea></p>'; echo '<p class="submit"><input type="submit" value="Submit" /></p></form>'; } this currently doesnt work. Extra things you might need to know is that this script/form is an included file in a dynamic site which also uses the rewrite module which is why I am using http://' . $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"] just incase that makes a difference. I've tried both of these methods, but neither are working. The if statement fails every time. Code: [Select] if(isset($_POST['submit'])){ Code: [Select] if(isset($submit)){ This is the form: Code: [Select] <form id="form1" name="form1" method="post" action="join.php"> <label><span> <input name="email" type="text" class="keywords" id="textfield" maxlength="50" value="Join my mailing list..." onclick="make_blank();" /> </span> <input name="submit" type="image" src="images/search.gif" class="button" onclick="return checkmail(this.form.email);"/> </label> </form> I'm having a few issues with a serach function in Internet Explorer, it works fine in firefox which is very annoying. What basically is happening, is the a form is sumbitting and posting info across, but on itself and then this is transfered into a php variable which is used on the query. Default values have been assigned if the isset of the form is not true. So I believe the issue is occuring on the " if(isset($_POST['submit'])) " but as stated it works perfectly fine in firefox. Any suggestions? Code: [Select] <?php print " <form target='_self' method='POST'> <table class=''> <tr> <td> <input name='vehicle' type='text' id='search_name' size='16'> <input type='image' src='images/search.gif' alt='Search' name='submit' id='search' value='Search'/> </td> </tr> <tr> <td> <select name='filter' id='filter'> <option value='make' selected='selected'>Filter By</option> <option value='make'>Vehicle Manufacture</option> <option value='model'>Vehicle Model</option> <option value='our_price'>Price</option> <option value='delivery_time'>Delivery Time</option> </select> </td> </tr> <tr> <td> <input type='radio' name='direction' value='ASC' checked/>Ascending <input type='radio' name='direction' value='DESC' />Descending </td> </tr> </form> "; include "connections/dbconnect.php"; if(isset($_POST['submit'])) { $vehicle = $_POST['vehicle']; $filter = $_POST['filter']; $direction = $_POST['direction']; //$rowsPerPage = $_POST['limit']; } else { $filter = "make"; $direction = "ASC"; } //$manfactures = "Ford"; if(isset($_GET['limit'])) { $rowsPerPage = $_GET['limit'];; } else { // how many rows to show per page $rowsPerPage = 10; } // by default we show first page $pageNum = 1; // if $_GET['page'] defined, use it as page number if(isset($_GET['page'])) { $pageNum = $_GET['page']; } // counting the offset $offset = ($pageNum - 1) * $rowsPerPage; $car_query = " SELECT * FROM cars WHERE model LIKE '%$vehicle%' OR make LIKE '%$vehicle%' OR model_details LIKE '%$vehicle%' OR search LIKE '%$vehicle%' ORDER BY $filter $direction LIMIT $offset, $rowsPerPage"; $car_result = mysql_query($car_query) or die ("Error in query: $car_query. ".mysql_error()); setlocale(LC_MONETARY, 'en_GB'); $fmt = '%i'; // how many rows we have in database $query = "SELECT COUNT(model) AS numrows FROM cars"; $result = mysql_query($query) or die('Error, query failed'); $row = mysql_fetch_array($result, MYSQL_ASSOC); $numrows = $row['numrows']; // how many pages we have when using paging? $maxPage = ceil($numrows/$rowsPerPage); // print the link to access each page $self = $_SERVER['PHP_SELF']; $nav = ''; for($page = 1; $page <= $maxPage; $page++) { if ($page == $pageNum) { $nav .= " $page "; // no need to create a link to current page } else { $nav .= " <a href=\"$self?page=$page&limit=$rowsPerPage\">$page</a> "; } } if ($pageNum > 1) { $page = $pageNum - 1; $prev = " <a href=\"$self?page=$page&limit=$rowsPerPage\">[Prev]</a> "; $first = " <a href=\"$self?page=1&limit=$rowsPerPage\">[First Page]</a> "; } else { $prev = ' '; // we're on page one, don't print previous link $first = ' '; // nor the first page link } if ($pageNum < $maxPage) { $page = $pageNum + 1; $next = " <a href=\"$self?page=$page&limit=$rowsPerPage\">[Next]</a> "; $last = " <a href=\"$self?page=$maxPage&limit=$rowsPerPage\">[Last Page]</a> "; } else { $next = ' '; // we're on the last page, don't print next link $last = ' '; // nor the last page link } if (mysql_num_rows($car_result) > 0) { ...... bringing back all the information from the database Hi, I have a form on my page. <form id="advanced_search" name="advanced_search" method="POST" action="<?php echo $PHP_SELF;?>"> </form> Form submits with a regular button <input type="submit" name="advSearch" id="advSearch" value="Search" /> And i have a detector to see where submit button has been clicked on my next page: if(isset($_POST['advSearch'])) { echo "Button was clicked"; } However, I wanted a custom button for better styling and control. So i replaced my regular button with this now which uses javascript to submit the form. <a class="button" href="javascript:document.advanced_search.submit()" name="advSearch" id="advSearch"><span>Search</span></a> Now the isset($_POST) is not working anymore. Can anyone help please?? Thanks! Hi. Link to project: www.smarttreff.moo.no Login user: admin login pw: 123 When i login the login form wont disapear. If i return to the index(Hjem) page without logging out, the loginform disapear. I am ussing session for the login So the basicly, i want the loginform do disapear at once when the user has pushed login button(Logg in) (dont laught at my "cut and past" for the include meny.. i just made the design and chopped it to bits and put it into includes) Index.php Code: [Select] <?php session_start(); include("css.php"); include("header.php"); include("meny.php"); ?> <td width="596" valign="top"><table width="100%" border="0" cellpadding="15"> <tr> <td class="tabell" valign="top" align="left"> Main </td> </tr> </table></td> </tr> </table> <?php include("footer.php"); ?> meny.php Code: [Select] <table width="800" border="0"> <tr> <td width="198" valign="top"><table width="100%" border="0" cellpadding="15"> <tr> <td align="left" valign="top" class="tabell"> <a href="index.php">Hjem</a> <br /> Når og hvor <br /> For hvem <br /> Spørsmål og svar<br /> Forum <br /> <br /> <br /> Samarbeidspartnere </td> </tr> </table> <br /> <table width="100%" border="0" cellpadding="15"> <tr> <td class="tabell" valign="top" align="left"> <?php if(isset($_SESSION['username'])) echo "Velkommen, " .$_SESSION['username']. "!<a href='innlogget.php'>Medlemsnyheter</a><br><a href='logout.php'>Log ut</a>"; else { include("loginform.php"); } ?> </td> </tr> </table></td> <td width="15"> </td> If I wanted to make multiple fields required before letting a User move past the field is this the proper way to do it? Code: [Select] if(isSet($_POST['playerFirst']['playerLast']['feet']['inches']['year']['status'])) { ## Something } else { ## Something else } I read ages ago (and checked to see if it's true, it was and given how it works, it must still be) the end user can alter the value of any form field, using Firebug or similar, before submitting it. Two things I've figured out today: 1) a form input doesn't need a value - doesn't even need the attribute - if you're only checking whether the POST var isset and the actual value isn't important 2) Although it appears not to matter in the example I'm working on now, if the script doesn't check what the value is, and potentially sanitise it, the user could submit the form with any value, true, false, malicious, idk... So my question is: is this one of the ways malicious bad things can happen and do I *have to* specify a value, not because the script won't work without it, it does, but because in the real world it opens a security door if I don't check for malicious script by saying "if value not as expected, script has to die". Having formulated the question properly and thought about it I can't imagine simply making a form, without obvious connections to anything important, could be a problem in the way I'm asking about but I asked it now so Edited by appobs, 03 July 2014 - 12:08 PM. I have a form that worked fine on my personal server, but then when I tried it on another server, it is giving me a Return Error: 4. I don't even know what that code means or why I am getting it. Can someone help me get rid of this stupid error code?!? Please? :-) Here is the link to the page with the error: http://midwestcreativeconsulting.com/jhrevell/add/ Click submit to see the error. Can anyone help me get rid of it? Hey all. I'm a noob so bare with me. Just started studying php and have an assignment due. At this phase of the project I have to create a form where a user can register data and I should retrieve that data and store it in my database. Now I have already created the form (student_reg.php) and a separate file with php code (demo.php) My database is name "registration" and I am trying to put this info in the "student" table. It has about 15 fields but for now I am only trying trying to insert the 1 field of data to test if it works. Dont know if that may cause problems? So far my demo.php connects to the database successfully. The problem I am having is the information I submit does not showing in the database field. However, I have an id field in my case a student number field which is set to auto increment so it automatically updates (1,2,3,4) with each new sumbitted info. When I submit the info the id field gets updated each time with a new row ( so i assume some information is somehow going through ) however the info I entered will remain blank in its field. :banghead: Heres my form (student_reg.php) Code: [Select] <div id="apdiv3"> <FORM action = "demo.php" method ="post "> <p>Course name:</p> <INPUT TYPE = "text" name="input"/> <INPUT TYPE = "Submit" VALUE = "Submit"/> </div> </FORM> and heres my php code to retrieve the form info Code: [Select] <?PHP include 'includes/config.php'; //connect to database $link=mysql_connect(DB_HOST, DB_USER, DB_PASSWORD); //error check if (!$link) { die('could not connect: ' . mysql_error()); } $db_selected=mysql_select_db(DB_NAME, $link); // error check if (!$db_selected) { die('can\t use ' . DB_NAME . ': ' . mysql_error()); } // Connected to database // retrieve form data $value=(isset($_POST['input'])); $sql = "INSERT INTO student (sname) VALUES ('$value')"; if (!mysql_query($sql)) { die ('Error: ' . mysql_error()); } mysql_close(); ?> I also recieved a notice "undefined index" or something like that from this part of the code "$value=(isset($_POST['input']));" before I inserted "isset" to the code. I'm not sure if what I did fixed the problem or only hid it, or whether that notice was related to the problem I'm having of not retrieving the info. Haha sorry guys know this is probably childs play for you but I just started out and really need to fix this so I can catch up with this project. Feel free to add tips and comments on other areas. Thanks :mrgreen: Hello, Curious to know if someone could point me in the right direction, been struggling with this for a bit now. I have a HTML page with a search field, I can enter a search term and hit the submit button and I am directed to my search.php page with the appropriate results. What I am looking to accomplish is having the search results from the search.php page displayed in a text area below my search field in my HTML page. I have included an image to better describe what I am looking to accomplish: Additionally below is the source from my HTML page and search.php page: page.html <form name="search" action='search.php' method="post"> <input type="text" class="myinputstyle" name="search" value="search" onClick="this.value=''"/><br> <input type="submit" value="submit" class="myinputstyle"> </form> search.php <?php $search = "%" . $_POST["search"] . "%"; mysql_connect ("localhost", "game_over", "Ge7Ooc9uPiedee3oos9xoh4th"); mysql_select_db ("game_over"); $query = "SELECT * FROM game_over WHERE first_name LIKE '$search'"; $result = mysql_query ($query); if ($result) { while ($row = mysql_fetch_array ($result)) { echo "Name: {$row['name']} " . "{$row['lname']} <br>" . "Email: {$row['email]} <br>" . } } ?> Any insight would be most appreciated. Thank you. guys this thing called isset() is bugging me.What is the difference in when you say Code: [Select] if(isset($_POST['name'])) and Code: [Select] if($_POST['name']) and Code: [Select] if(!$_POST['name']) and why would someone require a code such as Code: [Select] if($_POST['submit']=='Submit') And what is that code which tells you the user has entered something into the form Thanks People This is blowing my mind. I have this function and all I want it to do is check to make sure that the var $race is set and = '0'. The default value from the form is '0'. I also want it to check the value of race and if it is anything but the two listed , submit error. Yes I've tried to replace the || with &&.. Nothing works(Meaning that it will error when its not suppose to or it wont error when its suppose to).. Any ideas? Code: [Select] function check_Race ($race,$display_name,$member_id,$description,$ip) { //echo "This is the race". $race; //exit; if (isset($race) && $race ='0' && $race !== 'White' && $race !== 'Black'){ echo "This is an errror.!"; $t_error="19"; $member_id = $member_id; notify_Admin($t_error,$member_id,$ip); // logOut ($t_error); exit; } Hi all I need to do a multiple if isset to get three variables from the URL. Here is my code for just one: if(isset($_GET['category'])) { $fetchproducts = mysql_query(" SELECT * FROM `products` WHERE category = '".$_GET['category']."'"); while($returnedProduct = mysql_fetch_array($fetchproducts)) { include('product-cell.php'); } How do I combine this to check what is the 'type' and 'colour' from the URL and fetch from the SQL accordingly? Many thanks for you help Pete Isn't this code redundant... if (isset($_SESSION['loggedIn']) && $_SESSION['loggedIn'] == TRUE){ After all, if $SESSION['logged_in'] == TRUE then it is *obviously* set... Debbie Hi there, I'm inserting data into a mysql database. My submissions works fine, however when a part of the form is not filled out the php scripit crashes. How can I submit all data that is set and skip pieces that aren't filled out? For example I have a plant database which has an option to insert different types of common names for the plant. It's ok if they aren't all filled out. My code is as follows: Code: [Select] <?php //insert general plant data into db $queryplant="INSERT INTO actualplanttable (id, scientific, common1, common2, common3, family, genus, description, planting, growing, care, duration, reference) VALUES ('NULL', '$_POST[scientific]', '$_POST[common1]', '$_POST[common2]', '$_POST[common3]', '$_POST[family]', '$_POST[genus]', '$_POST[description]', '$_POST[planting]', '$_POST[growing]', '$_POST[care]','$_POST[duration]','$_POST[reference]')"; mysql_query($queryplant) or die ('Error updating actualplanttable'); //insert maintenance data into db $querymaintenance="INSERT INTO plantmaintenancelinktable (plant_id, maintenance_id) VALUES ('$inserted_id', '$_POST[maintenance]')"; mysql_query($querymaintenance) or die ('Error updating plantdurationtable'); ?> Should I be trying to work an isset function into this code? Any help would be greatly appreciated. Thanks! Bill... why dose this not work <?php if(isset($_SESSION['SESS_ADMIN'])) $loc = ../admin/admin.php; else $loc= ../head/head.php"; ?> <form><INPUT TYPE="button" value="Main Menu" onClick="parent.location='<?php echo $loc; ?>'"></form> </body> </HTML> Hello all, i am hoping someone can help me. i have some code i have been working on and i am trying to add a 404 page if it cant find the page, i know it will be some sort of if statment, but with me been pretty much a noob at php i am stuck. heres the code that the page calls. Code: [Select] function get_content() { //Get page name from browser if none call it home $page = (isset($_GET['page'])) ? $_GET['page'] : 'home'; //Get The Page Content $sql = "SELECT * FROM content WHERE page = '$page'"; $res = mysql_query($sql) or die (mysql_error()); while($row = mysql_fetch_assoc($res)){ //Show The Page Content echo '<h1>' . $row['title'] . '</h1>'; echo $row['body']; } } thanks all. I believe that my problem is with the isset on line 7 and 39, but I do not know of anyway around it. Can someone enlighten me. <?php session_start(); if (isset($_GET['logout'])){ unset($_SESSION['logged_in']); } ?> <html> <head> <title>Add a New Car!</title> <?php if (isset($_POST['submit'])) { //print_r($_POST); $password = md5($_POST['password']); //echo'<p>'.$password.'</p>'; $username = ($_POST['username']); //echo'<p>'.$username.'</p>'; } $db = new PDO('sqlite:login.sqlite'); $login = 'SELECT * FROM login WHERE userid="'.$username.'" AND password="'.$password.'";'; //echo'<p>'.$login.'</p>'; $attempt = $db->query($login); foreach ($attempt as $row) { //print_r($row); $_SESSION['logged_in'] = $username; } ?> </head> <body> <?php if (!isset($_SESSION['logged_in'])){ ?> <form method="post" action="Db_login.php"> <p>Username:<br /><input type="text" name="username" /> </p> <p>Password:<br /><input type="password" name="password" /></p> <p><input type="submit" name="submit" value="Log In!" /></p> </form> <?php } else { ?> <?php if(isset($_POST['submit'])) { print_r($_POST); $make = ($_POST['make']); $model = ($_POST['model']); $year = ($_POST['year']); $fuel = ($_POST['fuel_type']); $vin = ($_POST['vin_number']); $reg = ($_POST['reg_number']); } $db = new PDO('sqlite:cars.sqlite'); $sqlCars = 'INSERT INTO cars ( ) VALUES("'.$make.'","'.$model.'","'.$year.'","'.$fuel.'","'.$vin.'","'.$reg.'");'; echo'<p>'.$sqlCars.'</p.>'; ?> <form method="post" action="Db_new_Cars.php" enctype="multipart/form-data"> <p>Make:<br /><input type="text" name="make" /> </p> <p>Model:<br /><input type="text" name="model" /></p> <p>Year:<br /><input type="text" name="year" /></p> <p>Fuel Type:<br /><input type="text" name="fuel_type" /></p> <p>Vin Number:<br /><input type="text" name="vin_number" /></p> <p>Reg Number:<br /><input type="text" name="reg_number" /></p> <p>Choose a image to upload:<br /> <input type="file" name="myfile"></input></p> <p><input type="submit" name="submit" value="Submit!" /></p> </form> <h1> Protected Content!</h1> <p>You are logged in as <em><?php echo $_SESSION['logged_in']; ?> </em></p> <p><a href="Db_login.php?logout=true">Log out!</a></p> <p><a href="New_Cars.php">Add a new car</a></p> <p><a href="Book_Out_Cars.php">Book out a car</a></p> <?php } ?> </body> </html> i Have two page login.php and verify.php In login.php user is entering Username and Password and in the action of the form i am writing verify.php. If verification is a success then i will start a session() Code: [Select] session_start(); $_SESSION['ls']="loggedin"; // ls stands for login status $_SESSION['id']=$row['id']; $_SESSION['user_name']=$row['user_name']; $_SESSION['email']=$row['email']; header('location : members.php'); die (" "); and will redirect them to members.php .... Everything is working fine... But in login.php i have written a code on the top... Code: [Select] <?php if(isset($_SESSION['ls']) && isset($_SESSION['id']) && isset($_SESSION['user_name']) && isset($_SESSION['email']) ) { header('location:members.php'); die(" "); } ?> I want if a session is started and if user will access login.php they will automatically go to members.php But this script is not working... Iam not getting whats the problem... also i m not getting any error login.php or anything CODE WRITTEN ON THE TOP OF members.php IS : Code: [Select] <?php session_start(); if(@$_SESSION['ls']!=="loggedin" ) // Checks if the person has done stage one (Registration.php) { header('Location: login.php'); //If they haven't done it, it sends them back. die (" "); } ?> |