PHP - Got One Item To Validate, But Not Two
I am working on a script for a simple form with only 2 options that are dropdowns. I need to validate these two options that there is a selection made.
I have gotten the first one to validate, but I cannot get the second one to validate. Can anyone steer me in the right direciton why only one is working? I get no errors in the script, so I assume I am just missing something. Code: [Select] <?php // options for drop-down menu $choices = array('-- Choose Your Item','Anniversary Jacket', 'Anniversary T-Shirt'); $sizes = array('-- Choose Your Size','L', 'XL'); if($_SERVER['REQUEST_METHOD'] == 'GET'){ // display form when GET showForm(array()); } else{ // process form if POST $errors = validateForm(); if(count($errors)) showForm($errors); // if errors show again else print 'Form submitted succesfully!'; // no errors } // function generating form function showForm($errors){ global $choices,$sizes; // set defaults $defaults = array(); foreach($choices as $key => $choice){ if(isset($_POST['item']) && ($_POST['item'] == $key)) $defaults['item'][$key] = 'selected'; else $defaults['item'][$choice] = ''; } foreach($sizes as $key => $size){ if(isset($_POST['size']) && ($_POST['size'] == $key)) $defaults['size'][$key] = 'selected'; else $defaults['size'][$size] = ''; } // print form print "<form action='{$_SERVER['SCRIPT_NAME']}' method='post'>"; print "<div>"; print "<select name='item'>"; foreach($choices as $key => $choice){ print "<option value='{$key}' {$defaults['item'][$key]}>{$choice}</option>"; } print "</select>"; showError('item', $errors); print "</div>"; print "<div>"; print "<select name='size'>"; foreach($sizes as $key => $size){ print "<option value='{$key}' {$defaults['size'][$key]}>{$size}</option>"; } print "</select>"; showError('size', $errors); print "</div>"; print "<input type='submit'/>"; print "</form>"; } // display error function showError($type, $errors){ if(isset($errors[$type])) print "<b>{$errors[$type]}</b>"; } // validate data function validateForm(){ global $choices,$sizes; // start validation and store errors $error = array(); // validate drop-down if(!(isset($_POST['item']) && (array_key_exists($_POST['item'], $choices)) && $_POST['item'] != 0)) $errors['item'] = 'Select Item'; return $errors; // validate drop-down if(!(isset($_POST['size']) && (array_key_exists($_POST['size'], $choices)) && $_POST['size'] != 0)) $errors['size'] = 'Select Size'; return $errors; } ?> Similar TutorialsI have a script that seems to work well to insert a bookmark into a users database when he/she is logged into the system but I am having a hard time figuring out how I would go about making a work-a-round for having an item selected before being logged in, and inserted after they have logged in or registered. For example, I would like a user to be able to select an Item to add to bookmark whether that user is logged in/registered or not and if they are not, they would be greeted with a login/registration form and after successful login the add bookmark script would be initiated on the item previously selected. What I've got this far: Simple form to add bookmark: <form name="bm_table" action="add_bms.php" method="post"> <input type="text" name="new_url" value="http://" /> <input type="submit" value="Add Bookmark"/> </form> Then I have the add bookmark script: BEGIN php $new_url = $_POST['new_url']; try { check_valid_user(); //cannot get past this part since it ends the script....code below if (!filled_out($_POST)) { throw new Exception('Form not completely filled out.'); } // check URL format if (strstr($new_url, 'http://') === false) { $new_url = 'http://'.$new_url; } // check URL is valid if (!(@fopen($new_url, 'r'))) { throw new Exception('Not a valid URL.'); } // try to add bm add_bm($new_url); echo 'Bookmark added.'; // get the bookmarks this user has saved if ($url_array = get_user_urls($_SESSION['valid_user'])) { display_user_urls($url_array); } } catch (Exception $e) { echo $e->getMessage(); } END php Checking valid user - the portion I cannot get past in the above script: function check_valid_user() { // see if somebody is logged in and notify them if not if (isset($_SESSION['valid_user'])) { echo "Logged in as ".$_SESSION['valid_user'].".<br />"; } else { // they are not logged in do_html_heading('Problem:'); echo 'You are not logged in.<br />'; do_html_url('login.php', 'Login'); do_html_footer(); exit; } } How would I go about modifying the script so that a user could fill in the form (later it would be a link...obviously they probably wouldn't be filling in a form that is log-in specific - but same concept I think) Thanks in advance for the help! tec4 Hi there, I think this is a big question but I'd appretiate any help you can provide!! I have a list of items and subitems in a table that looks like this: id parent_id title 1 0 House Chores 2 1 Take Out Trash 3 1 Clean Room 4 0 Grocery List 5 4 Eggs 6 4 Produce 7 6 Lettuce 8 6 Tomato 9 4 Milk I want to display it like this: (+) House Chores: > Take Out Trash > Clean Room (+) Grocery List: > Eggs (+) Produce > Letutce > Tomato > Milk So basically each entry in the table has an unique id and also a parent id if it's nested inside another item. I "sort of" got it figured out in one way, but it doesnt really allow for nested subgroups. I'd like to know how would y'all PHP freaks to this Also taking suggestions for the javascript code to expand/collapse the tree !! Thank you! Well I am looking to change this url Code: [Select] http://website.com/product.php?Item=2369 to Code: [Select] http://website.com/product.php?Item=Item-Name Heres a snip of the code that handles that. <?php include_once('mysql_connect.php');$id = (int)$_GET['Item'];?>() any help would be appreciated. How do I make email, name and phone required fields? thanks in advance <?php $email = $_POST['email']; $name = trim($_POST['name']); $phone = trim($_POST['phone']); $time = trim($_POST['time']); $zipcode = trim($_POST['zipcode']); $date = trim($_POST['date']); $EmailTo = "myemail@somedomain.com"; $Subject = "form"; /// Add a subject $Body = ""; $Body .= "Full name:\n$name\n\n"; $Body .= "Primary phone:\n$phone\n\n"; $Body .= "time:\n$time\n\n"; $Body .= "Zip code:\n$zipcode\n\n"; $Body .= "date:\n$date\n\n"; if($Subject == NULL) {$Subject = "From $EmailFrom";} $success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom>"); if ($success){ header ('Location: confirm.html');} else{ echo "Error! Your e-mail was not sent!";} ?> Hi, I am fairly new to php and I wanted to know whether you could validate a "input type = text ". I have made a class where i've made functions to validate test fields but i dont know how to call them with the html form. Any suggestions or tips .... Thanks in advance. Hey everyone, im building my first newsletter sign up and wanted to add the validation of checking if the email is already in the database. This is the top part of the code that works. <?php switch ($_REQUEST['action']) { default: foreach($_POST as $key=>$value){ $$key = $value; } if ($email == ''){ $error_msg = 'email required'; } elseif (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)) { $error_msg = 'Invalid email address'; } echo ""; if ($error_msg == ''){ foreach($_POST as $key=>$value){ $$key = htmlentities(stripslashes($value)); } $Q = mysql_query("INSERT INTO newsletter (`email`) VALUES ('$email')"); But when i add my attempted validation it doesn't work. $check = mysql_query("SELECT FROM newsletter WHERE email = '$email'") or die(mysql_error()); $check2 = mysql_num_rows($check); if ($check2 != 1) { $error_msg = 'email exists'; Could someone be so kind to add this code where it should go, iv tried everything. I do not know whats going on. I have tried two different methods of validating and email and it keeps saying invalid email I have even tried to debug it by putting errors and nothing i have tried preg_match("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$^", $e) and fliter_var($e, FLITER_VALIDATE_EMAIL); the email i am trying to debug is a valid one. its one I use daily. I have tried different emails and still no luck.... someone help me please! Hi, I want to control a variable (decide whether to track click if coming from a specific site oppose to hitting the final site (destination) directly. For example: www.portal.com - this will be a management site that will redirect viewers to the the final destination based on variable info - for exmample $a=123 or $a= 567 - which would come in as www.portal.com?a=123 or www.portal.com?a=567 Note: 123 would redirect to www.abc.com?a=123 and/or 567 would redirect to www.xyz.com?a=567 with said variable(s). ------ My question is this: What is the best method to authenticate (both on) www.abc.com and/or www.xyz.com that the referred viewer came from www.portal.com? I know about the super globals (HTTP_REFERER) but want to know if there are other (more) secure method to manage this interaction between external domains /websites? Any insight on this appreciated - thanks! This is probably a simple one, but I'm not experienced with arrays. I have a form with looped dropdowns for items from a database. On submit it goes to a second page. Before I run any script I want to make sure the array created from the dropdowns contains anything greater than 0... I thought this would do it: if (isset($_POST['participantqty']) && ($_POST['participantqty']) > 0){ But it does nothing. I also tried: if (isset($_POST['participantqty[]']) && ($_POST['participantqty[]']) > 0){ Where should I validate the return value?
In the function should I validate the value before returning it.
Or once the value has been returned, should I check it?
Is it really necessary to validate the return value?
Thank you.
Hi Everyone..
I am not sure if I should post this question here. I would like to fix this problem using PHP rather than HTML. I am new to PHP. This code is part of an old PHP gallery file. I am trying to validate my site but the site's links have some characters that makes the link throw errors in W3C Validator. So I tried to replace the characters with HTML characters for example ? are now replaced by ?
so my original link before using valid HTML characters looked like
www.awebsite.com/viewgallery.php?cname=Colorado-Fall&pcaption=Lost-In-The-artAnd now it looks like this ... www.awebsite.com/viewgallery.php?cname=Colorado-Fall&pcaption=Lost-In-The-artBut now W3C Validator shows an error like this Line 32, Column 240: an attribute value must be a literal unless it contains only name characters …n class='next'><a href=viewgallery.php?cname=Colorado-Journeys&pca…✉ You have used a character that is not considered a "name character" in an attribute value. Which characters are considered "name characters" varies between the different document types, but a good rule of thumb is that unless the value contains only lower or upper case letters in the range a-z you must put quotation marks around the value. In fact, unless you have extreme file size requirements it is a very very good idea to always put quote marks around your attribute values. It is never wrong to do so, and very often it is absolutely necessary. Hello
I have a PHP page that sends text entered by a user to our database which we use to display news. This system supports various languages but occasionally we get issues with odd characters being entered...
For example, the premade glyph for ellipsis which is normally represented by 3 .'s broke our system today
How can I check that each character is valid and within range?
These are our character ranges
ExtendedLatin_c_iLowerAlphaChar = 0x00C0;
ExtendedLatin_c_iUpperAlphaChar = 0x01FF;
Arabic_c_iLowerChar = 0x600;
Arabic_c_iUpperChar = 0x6FF;
Arabic_c_iLowerAlphaChar = 0x621;
Arabic_c_iUpperAlphaChar = 0x64A;
Arabic_c_iLowerNumericChar = 0x660;
Arabic_c_iUpperNumericChar = 0x669;
So each character must fall within one of these ranges... but I have no idea how to get the hex value of a character in PHP
Thanks
i have this while loop making my category links at the top of my page, but i still have the bullet after the last item. ive looked at other examples and CANNOT get mine to follow suit...help please? Code: [Select] $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); $query1 = "SELECT * FROM ob_category"; $data1 = mysqli_query($dbc, $query1); while($row=mysqli_fetch_array($data1)){ echo '<a href="viewlistings.php">' . $row['name'] . '</a> • '; } Hi, I'm hoping someone can lead me in the right direction here. I'm creating a simple shopping cart that I will later pass on to Paypal for payment but my problem is, it won't add the items to my shopping cart when I click add to cart. My products are on different pages and I'm not sure if that is going to matter. When I click "add to cart" nothing gets added and it says my cart is empty. I have two tables with the following columns: 1. products: productId productName productDesc productPrice link (for dynamically creating the page links on the main product page) 2. productscents scentId scentName scentDesc Here is the add code that is in my first products page (Elite Hand Cream): Code: [Select] <?php if(isset($_GET['action']) && $_GET['action'] == "add") { $id = intval($_GET['id']); $desc=intval($_GET['desc']); if (isset($_SESSION['cart'][$id])) { $_SESSION['cart'][$id]['quantity']++; } else { $sql3 = "SELECT * FROM products WHERE productId=[$id]"; $sql4= "SELECT * FROM productscents WHERE scentId=[$desc]"; $query3 = mysql_query($sql3); $query4 = mysql_query($sql4); if(mysql_num_rows($query3) != 0) { $row3 = mysql_fetch_array($query3); $row4 = mysql_fetch_array($query4); $_SESSION['cart'][$row3['productId']] = array("quantity" => 1, "price" => $row3['productPrice'], "desc" => $row4['scentId']); } } } ?> Here is code I have for the $_SESSION: Code: [Select] <?php if(isset($_SESSION['cart'])) { $sql5= "SELECT * FROM products,productscents WHERE productId IN ("; foreach($_SESSION['cart'] as $id => $value) { $sql5 .= $id . ","; } $sql5 = substr($sql,0,-1) . ") ORDER BY productId, scentId ASC"; $query = mysql_query($sql5); if(!empty($query)) { while($row = mysql_fetch_assoc($query)) { ?> <?php echo $row['productName'];?><?php $_SESSION['cart'][$row['productId']]['quantity'];?> <?php } } else { echo "You need to add an item to your cart";} } Here is the code that I have for the "add to cart" and "view cart": Code: [Select] <a href=#&action=add&id=<?php echo $prodId;?>&desc=<?php echo $scent_id[$y];?>>Add to Cart</a><br><a href="cart.php">View Cart</a> This grabs the correct product Id and scent Id which I want and no errors are being displayed on the page. I'm not sure where to begin with this. LOL. I'm new to PHP and I used a tutorial to help with the code. Any help would be greatly appreciated. Hi How to get value of all $_Request variable so that we can validate for cross scripting. see below http://srijanlinux.com/consentRequestNew.php?requestId=24753 print count($_GET); // return ---------- 1 print_r($_GET); // return ----------- Array ( [requestId] => 24753 ) Now I want to validate value of requestId. I know I can validate by getting using $_GET['requestId']. But there are changes that I don't know variable name then How validate unknown variable which might be put by hacker. Thanks akash how can i validate if email is being entered correctly in a form? i have the following code Code: [Select] <?php if(isset($_POST['Submit'])){ //NEED TO CHECK IF FIELDS ARE FILLED IN if( empty($_POST['email'])){ header("Location:Messages.php?msg=12"); exit(); } if( empty($_POST['name'])){ header("Location:Messages.php?msg=3"); exit(); } if( empty($_POST['pw1']) && (empty($_POST['pw2']))){ header( "Location:Messages.php?msg=4" ); exit(); } $name=$_POST['name']; $email=$_POST['email']; $pw1=$_POST['pw1']; $pw2=$_POST['pw2']; if("$pw1" !== "$pw2" ){ header( "Location:Messages.php?msg=5" ); exit(); } $ip = $_SERVER['REMOTE_ADDR']; //connect to the db server , check if uname exist include('config.php'); $query1=("Select * from user where email='$email'"); $result1= mysql_query($query1); $num1=mysql_num_rows($result1); if ($num1 > 0) {//Email already been used header( "Location:Messages.php?msg=11" ); exit(); }else{ $query=("Select * from user where uname='$name'"); $result= mysql_query($query); $num=mysql_num_rows($result); if ($num > 0) {//Username already exist header( "Location:Messages.php?msg=6" ); exit(); }else{ //if username does not exist insert user details $query=( "INSERT INTO user (uname, pw,email,date_joined,ip,level) VALUES ('$name','$pw1','$email',NOW(),'$ip','Normal')"); if (@mysql_query ($query)) { header("location:login.php?reg=1"); exit; } } } mysql_close(); } ?> This topic has been moved to HTML Help. http://www.phpfreaks.com/forums/index.php?topic=358157.0 Hello, I had this code that checks for a form validity using AJAX: ereg("^[a-zA-Z0-9]+$ This will check only for a-z,0-9 and A-Z, how can I allow white spaces to be inserted? Thanks Hello. So I already know an extremely elementary way to check to see if a form field is blank using PHP. For example: Code: [Select] if ($subject == "") The question I have is, is there a way to have php check every field in a form to make sure it has some sort of value? I want to create an 'if' statement which basically says, "If all form fields have something filled in, then do this" For example Code: [Select] if ($subject == "any value") & ($name == "any value") & ($comment == "any value") Not sure if that makes sense. Any help would be greatly appreciated!!! |