PHP - Foreach On A Sequence Of $_post Or $_get Variables
I have a php search page that takes form data to create its queries, then reload the original search page. The form is long, so there are numerous $_POST's to convert to variables for use in the query. I've looked at "extract" and a few other code snippets. But it's a form and I don't want any security issues. I'm hoping there's a "foreach" solution, but I'm a beginner. What's a proper way to to simplify this:
$s1 = $_POST["s1"]; $s2 = $_POST["s2"]; $s3 = $_POST["s3"]; $s4 = $_POST["s4"]; $s5 = $_POST["s5"]; $s6 = $_POST["s6"]; $s7 = $_POST["s7"]; $s8 = $_POST["s8"]; $s9 = $_POST["s9"]; $s10 = $_POST["s10"]; $s11 = $_POST["s11"]; $s12 = $_POST["s12"]; Similar TutorialsHello guys. I'm trying to improve my control panel system. I have this page where you input a player's name and when you hit "Search" it will display that user's information. Ok. This is the code: Code: [Select] <form action="ShowStats.php" method="post"> <li><font color="#FF9933"><b>User's Name:</b></font> <input type="text" name="User" /></li> <p> </p> <p> </p> <input type="submit" value="Search" /></form>That's when you input the player's name and the Search button. Once you hit that button, I want the Address bar to display something like this: "www.test.com/ShowStats.php?User=SEARCHED_USER" Here's the $_POST ( and "fetch" user's info ) function inside "ShowStats.php" include("database.php"); if(!$con) { die('Could not connect: ' . mysql_error()); } $user = $_POST["User"]; $escuser = mysql_real_escape_string($user); $result = mysql_query("SELECT * FROM playerinfo WHERE user = '$escuser'"); $username_exist = mysql_num_rows($result); if($username_exist == 0) { echo('<b><font color="#C41F1F">That username does not exist</b></font>'); echo('<p><center><font face="Arial" color="#000080" size="2"><b><a href="http://yu-ki-ko.com/fsns/Stats.php">Go back</a></b></center></font></p>'); die; } $row = mysql_fetch_row($result); All I want is that when a user searches for the player, the address bar will be displayed like: "www.test.com/ShowStats.php?User=SEARCHED_USER" Thanks! If any more info is needed, let me know. Well, i have got this code: Code: [Select] <?php header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); ?> <form action="signature.php?user=" .$user. "&img=". $img" method="post"> <input name="user" type="text" /> <select name="img"> <option value="blue">Blue</option> <option value="red">Red</option> <option value="purple">Purple</option> <option value="pink">Pink</option> </select> <?php $user = $_POST['user']; $img = $_POST['img']; ?> <input type="submit" value="Submit" /> <?php //Skill Grabs $order = array("Overall", "Attack", "Defence", "Strength", "Hitpoints", "Ranged", "Prayer", "Magic", "Cooking", "Woodcutting", "Fletching", "Fishing", "Firemaking", "Crafting", "Smithing", "Mining", "Herblore", "Agility", "Thieving", "Slayer", "Farming", "Runecraft", "Hunter", "Construction", "Summoning", "Dungeoneering"); $user = $_GET['user']; //Change this to the variable (Or a string literal) that contains the username $get = file_get_contents("http://hiscore.runescape.com/index_lite.ws?player=$user"); $get = explode("\n", $get); $i = 0; foreach ($order as $key => $value) { $value = strtolower($value); $temp = explode(",", $get[$i]); $temp = array("rank" => $temp[0], "level" => $temp[1], "exp" => $temp[2]); $stats[$value] = $temp; $eval = "\$$value = array(\$temp[\"rank\"], \$temp[\"level\"], \$temp[\"exp\"]);"; eval($eval); $i++; } //End Skill Grabs // specify the file name - you can use a full path, or "../../" type stuff here // if the image is not in the same directory as this code file $image = imagecreatefrompng("http://slay2day.x10.mx/highscores/signatures/".$_GET['img'].".png"); // specify the font size // in this case, the color is white, but you can replace the numbers with the RGB values // of any color you want $color = imagecolorallocate($image, 255,255,255); // and now we do the overlay - the layers of text start top to bottom, so // the drop shadow comes first // $image - the base image file we specified above // $font_size - Well duh. Its the size of the font // 0 - the angle of the text - we don't want an angle, so we leave it at 0 // 55 - pixels to the right from the leftmost part of the image // 35 - pixels down from the top of the image // $black - the color we defined above // "../fonts/ARIALBD.TTF" - the location on the server that the font can be found // "Test Text" - the text we're overlaying - you can also use a variable here ImageTTFText ($image, "7", 0, 280, 10, $color, "arial.ttf","Slay2day"); ImageTTFText ($image, "12", 0, 240, 55, $color, "biblio.ttf",$user); if($overall[0]==-1){ImageTTFText($image, "11", 0, 230, 105, $color, "biblio.ttf","NOT RANKED");}else{ImageTTFText($image, "11", 0, 240, 105, $color, "biblio.ttf",$overall[0]);} ImageTTFText ($image, "10", 0, 27, 20, $color, "arial.ttf",$attack[1]); ImageTTFText ($image, "10", 0, 27, 42, $color, "arial.ttf",$strength[1]); ImageTTFText ($image, "10", 0, 27, 64, $color, "arial.ttf",$defence[1]); ImageTTFText ($image, "10", 0, 27, 88, $color, "arial.ttf",$hitpoints[1]); ImageTTFText ($image, "10", 0, 27, 114, $color, "arial.ttf",$ranged[1]); ImageTTFText ($image, "10", 0, 70, 20, $color, "arial.ttf",$prayer[1]); ImageTTFText ($image, "10", 0, 70, 42, $color, "arial.ttf",$magic[1]); ImageTTFText ($image, "10", 0, 70, 64, $color, "arial.ttf",$cooking[1]); ImageTTFText ($image, "10", 0, 70, 88, $color, "arial.ttf",$woodcutting[1]); ImageTTFText ($image, "10", 0, 70, 114, $color, "arial.ttf",$fletching[1]); ImageTTFText ($image, "10", 0, 117, 20, $color, "arial.ttf",$fishing[1]); ImageTTFText ($image, "10", 0, 117, 42, $color, "arial.ttf",$firemaking[1]); ImageTTFText ($image, "10", 0, 117, 64, $color, "arial.ttf",$crafting[1]); ImageTTFText ($image, "10", 0, 117, 88, $color, "arial.ttf",$smithing[1]); ImageTTFText ($image, "10", 0, 117, 114, $color, "arial.ttf",$mining[1]); ImageTTFText ($image, "10", 0, 162, 20, $color, "arial.ttf",$herblore[1]); ImageTTFText ($image, "10", 0, 162, 42, $color, "arial.ttf",$agility[1]); ImageTTFText ($image, "10", 0, 162, 64, $color, "arial.ttf",$thieving[1]); ImageTTFText ($image, "10", 0, 162, 88, $color, "arial.ttf",$slayer[1]); ImageTTFText ($image, "10", 0, 162, 114, $color, "arial.ttf",$farming[1]); ImageTTFText ($image, "10", 0, 212, 20, $color, "arial.ttf",$runecraft[1]); ImageTTFText ($image, "10", 0, 212, 42, $color, "arial.ttf",$construction[1]); ImageTTFText ($image, "10", 0, 212, 64, $color, "arial.ttf",$hunter[1]); ImageTTFText ($image, "10", 0, 212, 88, $color, "arial.ttf",$summoning[1]); ImageTTFText ($image, "10", 0, 212, 114, $color, "arial.ttf",$dungeoneering[1]); // Now add the actual white text "on top" header("Content-type: image/png"); imagepng($image); imagedestroy($image); ?> It generates a image and gets data from the name thats in the url. I am wanting to make a form where they fill out their name and what color they use. What is wrong? Hi guys i am a PHP newbie trying to learn from the beginning. I am reading a php book and i can't get past a particular example because $_GET and $_POST just won't work. Below is the code i am working with: HTML File <form action="welcome1.php" method="get"> <div> <label for="firstname">First name: <input type="text" name"firstname" id="firstname"/></label> </div> <div> <label for="lastname"> Last name: <input type="text" name="lastname" id="lastname"/> </label> </div> <div> <input type="submit" value="GO" /> </div> PHP file <?php $firstname = $_GET['firstname']; $lastname = $_GET['lastname']; print 'Welcome to our website, ' . htmlspecialchars($firstname, ENT_QUOTES, 'UTF-8') . ' ' . htmlspecialchars($lastname, ENT_QUOTES, 'UTF-8') . '!'; ?> I am working on a windows pc with Vista home edition installed. I run a localhost server installed via XAMMP. Please this has been a recurring problem for me. Each time i get to this stage in the past i always get stuck. $_GET and $_POST just does not work for me. Please heeeelp! My form values are not posting on my thankyou.php page. I'm sure it's a simple fix. Here's some code from reservation.php . form action="CGI/gdform.php" method="post" enctype="application/x-www-form-urlencoded" name="formres" id="formres"> <input type="hidden" name=" redirect" value="ThankYou.php"> <label><span class="style12">Your Name: <input type="text" name="txtName" id="Name" /> </span></label> ... <p class="style12"><span id="sprytextfield10"> <label>Date of Special Event: <input type="text" name="DateReq" id="DateReq" /> </label> <?php $txtName = $_GET[txtName]; ... $DateReq = $_GET[DateReq]; ?> </form> On my thankyou.php: <body> <?php $txtName = $_POST[txtName]; ... $DateReq = $_POST[DateReq]; ?> and a little lower down... <?php echo $txtName ?> ... <?php echo $DateReq ?> Any reason why the thank you page isn't calling the values? I exhaustively checked it against a working form I have on another site, and the code seems to be, well, identical. Not getting an error, just get empty space where the values should be. Hi, I do not have a problem with specific code but rather code design/technique. I am not able to articulate the problem very well but here goes. I am building a [mostly] object oriented PHP store as a personal project to improve my PHP skills. However I'm running into some problems concerning my sorting, pagination and filtering facilities. I've tried to use $_GET to store the following: Page being viewed by the user Category (e.g. fruit or vegetables) Sort method (e.g price ascending, descending etc.) When the user clicks on a link to another page for example, I must append the page number to the URL, something like "index.php?page=2" but the other $_GET parameters are lost unless I do something like: Code: [Select] <a href=\"index.php?cat=".$_GET['cat']."&sort=".$_GET['sort']."&page=".($this->pageNum+1)."\">Next-> </a> This means whenever there is a link or form submission I must find a way to carry over all those parameters to ensure the page and category are remembered, otherwise the user is returned to page 1 and the main category. It's a mess and has become too confusing with the introduction of other pages. Clearly, I'm doing it all wrong. $_GET parameters alone are not a good solution here, at least how I'm using them. So I ask of you, what's the correct way to store information such as page number, sorting method and category? Must I use $_SESSIONS and if so how? Thanks. hey guys basically i have a form which searches my news <form action="" method="GET"> <label for="search">Search: </label><input name="search" id="search" type="text" /> <input value="Search" type="submit" /> </form> and im not sure the best way around this or if im going around this the right way but when i access http://localhost/news/seach (search form) and press submit after entering a query i want the action to be http://localhost/news/seach/search query value here i hope ive explained well enough and someone could help me with this...thank you
So maybe this is normal, or maybe there is a "better way." The only simple solution appears to be to always save $_POST data to $_SESSION["post"] on the off-chance some visitor some day ever decides to do a $_GET request from a referral link.
3 weeks of my life has been lost to correcting the neverending 'illegal string offset' and 'undefined index' errors etc. by making sure every last variable is declared... Anyway, blah blah blah, that's my rant. Is there a better way? Or is this "how everybody does it?" It seems stupid to have to do all of this.
I recently had a customer say that one of my forms isn't working. For some reason the ID number is getting lost when she submits the form. The form code looks like: ... print "<form method='post' name='form' action='update.php'>"; ... print "<input type='hidden' name='id' value=\"$id\" />"; print "<input type='submit' name='submit' value=\"Save Session\" />"; print "</form>"; ... And the PHP code that gets executed looks like: ... //GET SESSION ID if(isset($_GET['id'])) { //ID from HTML link, before updates have been made $id = $_GET['id']; } elseif(isset($_POST['id'])) { //ID from form, after updates have been made $id = $_POST['id']; } else { $id = ''; } //IF SESSION ID IS VALID if(preg_match("/^\d+$/", $id)) { ... //ELSE, INVALID ID } else { $msg = "<span class='errorText'>Session ID not found or invalid.</span>"; } ... For some reason she usually gets the "Session ID not found..." error when submitting the form. Do you see any problems with the above code? Note that she has been able to sucessfully use the form before (in the same day); we have nearly 1,800 records submitted using these forms; and I am unable to duplicate the issue. So I'm at a loss on what to do next. Also, she talked with her IT person about the form. The IT person was able to submit data on his computer. So he reset her Internet options which seemed to fix the problem on her end temporarily. Note that she is using IE 7. She also said that she doesn't have access to any other browsers. I'm tempted to chalk this up as a personal computer issue, but wanted to get your input first. Hi, I am a curious fellow just beginning to use PHP. I understand the basics of what the $_GET and $_POST superglobals do, and how we can use them to retrieve data after form submission. I also know that since $_GET and $_POST are just associate arrays, we can create our own values in both $_GET and $_POST by writing statements like $_POST['variable'] = "value". I am wondering if it is at all possible to send data beyond form data by adding new key/value pairs into $_GET and $_POST. So for example, if I had a form that transferred username/password through Post, would it be possible for me to include further data by just saying $_POST['formtype'] = "house_insurance_form"? Basically what I'm getting at is trying to physically add your own data to $_POST or $_GET that you could pull from the next page where the form redirects to. In other words, can I send data beyond form data using these superglobals? I know I can do this with $_SESSION, but could I do it through $_POST or $_GET? I haven't been able to accomplish this, and I was just wondering if someone could give me an in-depth explanation of how this might work or how this is not possible. I would really really really appreciate it. Best Regards, -Sky Is this an effective way of accessing the $_GET and $_POST properties? I can see that the native $_GET function has been looped through so that $varName would be for example "username" and $value would be "Jeremy". Then they are both stored into an array called $getVars? Is this the best way of doing it, if not then why? foreach($_GET as $varName=>$value) $getVars[$varName]=trim(clean($value, 100)); foreach($_POST as $varName=>$value) $postVars[$varName]=trim(clean($value, 100));[/php] Kind regards, laanes User clicks on a url, ie: example.com/AEQ438J When I perform this in the code below: Code: [Select] $referrer = $_GET['_url']; // echo $referrer displays the referrer ID contents correctly as "AEQ438J" if ( ! empty($referrer)) { $mysqli->query("UPDATE coming_soon_emails SET clicks = clicks + 1 WHERE code='" . $referrer ."'"); } // this also updates the database correctly as it should if (!empty($_POST['email'])){ // echo $referrer displays the referrer ID contents as BLANK. It should display "AEQ438J"! ..... $referrer displays correctly BEFORE if($_POST['form']), however during the if($_POST['form']) $referrer is empty. How can I fix my code so that $referrer is not empty during the time the user posts their email address in the form? Thank you! Complete PHP and HTML Code: [Select] <?php require "includes/connect.php"; //var_dump($_GET);die; function gen_code($codeLen = 7) { $code = ''; for ($i=0; $i<$codeLen; $i++) { $d=rand(1,30)%2; $code .= $d ? chr(rand(65,90)) : chr(rand(48,57)); } return $code; } function add_code($email_id) { global $mysqli; $code = gen_code(7); $mysqli->query("UPDATE coming_soon_emails SET code='" . $code ."' WHERE email_id='" . $email_id . "'"); if($mysqli->affected_rows != 1) { add_code($email_id); } else return $code; } $msg = ''; $referrer = $_GET['_url']; // echo $referrer displays the referrer ID contents correctly if ( ! empty($referrer)) { $mysqli->query("UPDATE coming_soon_emails SET clicks = clicks + 1 WHERE code='" . $referrer ."'"); } if (!empty($_POST['email'])){ // echo $referrer displays the referrer ID contents as BLANK // Requested with AJAX: $ajax = ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'); try{ if(!filter_input(INPUT_POST,'email',FILTER_VALIDATE_EMAIL)){ throw new Exception('Invalid Email!'); } $mysqli->query("INSERT INTO coming_soon_emails SET email='".$mysqli->real_escape_string($_POST['email'])."'"); if($mysqli->affected_rows != 1){ throw new Exception('This email already exists in the database.'); } else { $email_code = add_code($mysqli->insert_id); } $msg = "http://www.example.com/" . $email_code; //the following doesn't work as referrer is now empty :( if ( ! empty($referrer)) { $mysqli->query("UPDATE coming_soon_emails SET signup = signup + 1 WHERE code='" . $referrer ."'"); } if($ajax){ die(json_encode(array('msg' => $msg))); } } catch (Exception $e){ if($ajax){ die(json_encode(array('error'=>$e->getMessage()))); } $msg = $e->getMessage(); } } ?> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <link rel="stylesheet" type="text/css" href="css/styles.css" /> </head> <body> <div id="launch"> <form id="form" method="post" action=""> <input type="text" id="email" name="email" value="<?php echo $msg;?>" /> <input type="submit" value="Submit" id="submitButton" /> </form> <div id="invite"> <p style="margin-top:20px;">The ID of who referred you: <?php echo $referrer; //this displays correctly?>)</p> <p style="margin-top:20px;"><span id="code" style="font-weight:bold;"> </span></p> </div> </div> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script> <script src="js/script.js"></script> </body> </html> script.js Code: [Select] $(document).ready(function(){ // Binding event listeners for the form on document ready $('#email').defaultText('Your Email Address'); // 'working' prevents multiple submissions var working = false; $('#form').submit(function(){ if(working){ return false; } working = true; $.post("./index.php",{email:$('#email').val()},function(r){ if(r.error){ $('#email').val(r.error); } else { $('#email').val(r.msg); // not needed but gets hidden anyways... $('#launch form').hide(); $("#code").html(r.msg); $("#invite").fadeIn('slow'); } working = false; },'json'); return false; }); }); // A custom jQuery method for placeholder text: $.fn.defaultText = function(value){ var element = this.eq(0); element.data('defaultText',value); element.focus(function(){ if(element.val() == value){ element.val('').removeClass('defaultText'); } }).blur(function(){ if(element.val() == '' || element.val() == value){ element.addClass('defaultText').val(value); } }); return element.blur(); } htaccess Code: [Select] RewriteEngine on RewriteCond %{HTTP_HOST} ^my-url.com RewriteRule (.*) http://www.my-url.com/$1 [R=301,L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^([a-z0-9]+)$ /index.php?_url=$1 [NC,L,QSA] table.sql Code: [Select] CREATE TABLE IF NOT EXISTS `coming_soon_emails` ( `email_id` int(11) NOT NULL auto_increment, `email` varchar(64) collate utf8_unicode_ci NOT NULL, `code` char(7) collate utf8_unicode_ci DEFAULT NULL, `clicks` int(64) collate utf8_unicode_ci DEFAULT 0, `signup` int(64) collate utf8_unicode_ci DEFAULT 0, `ts` timestamp NOT NULL default CURRENT_TIMESTAMP, PRIMARY KEY (`email_id`), UNIQUE KEY `email` (`email`), UNIQUE KEY `code` (`code`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; I'm have a form with at least 3 fields(name, price, and date). I have some jquery that produces another date form input every time a certain link is clicked so there can be several date inputs. The first one(not dynamically created) has the form name "date_1". All the jquery produced inputs have the name "in_123435443453". The number after "in_" is the current timestamp. I'm trying to cycle through only the POSTs that start with "in_" and take their value to insert into database. I can't figure out how to grab the date("in_25346435253") POST in the foreach loop though because they're all unique. I'm using the codeigniter framework. That's why the code to insert into the db make look weird. Code: [Select] <?php foreach($this->input->post() as $key => $value) { $start = substr($key, 0, 3); if($start == "in_") { $cal_id = $this->input->post('cal_id'); $exc_name = $this->input->post('exc_name'); $date = $this->input->post('???'); // <-- part i need help with $price = $this->input->post('price'); $date = date("Y-m-d 00:00:00",strtotime($date)); $data = array( 'cal_id' =>$cal_id, 'name' => $exc_name, 'date' => $date, 'price' => $price ); $this->db->insert('Exceptions', $data); } } ?> I have a form with radio buttons, depending on if a person selects yes, they will be given an answer after they hit submit. I don't want to do a bunch if un-necessary coding, so I'm trying something else, but it's not working. My form is this Code: [Select] <table width="100%" border="0" cellspacing="0" cellpadding="4"> <tr> <td align="center" valign="top">Yes</td> <td align="center" valign="top"><input type="radio" name="phone1" id="phone1" value="1" /></td> <td align="center" valign="top">No</td> <td align="center" valign="top"><input type="radio" name="phone1" id="phone1" value="2" /></td> </tr> </table> My code is this Code: [Select] <?php if(isset($_POST['submit'])) { $key; $key['phone1'] = "testing phone 1"; $key['phone2'] = "testing phone 2."; foreach( $_POST as $key => $value) { if($value == "1"){ echo $key."<br />"; } } } ?> Now, it does not show the wording associated with $key if the value is 1. Can anybody help me out here? This form is going to have over 100 questions. Thanks in advance. new account form has the usual; firstname, last name company, street address etc.
Talents write in ALL uppercase, lowercase everything but proper case.
Don't know where to apply ucwords and strtolower to convert values into proper case.
Code as is:
<form action="https://www.website.com/?page=step3" method="POST" name=myForm id="commentForm" class="cmxform"> Hello Guys, I have a question. I have the following code to grab all of my $_POST vars and run through my filter function Code: [Select] foreach($_POST as $key => $value) { $mydata[$key] = filter($value); } Before using the foreach loop I was just doing the basic $var1 = $_POST['var1']; $var2 = $_POST['var2']; I'm going to have about 40 - 50 $_POST vars so my question is how do i return it as just a $var name instead of having to do this echo "<br><br><br>example1" . $mydata['var1']; echo "<br><br><br>example2" . $mydata['var2']; I guess its hard for me to explain.. Thanks for your help! Hi all, I am trying to write a script that finds the blank $_POST values and add them to a $blank_array. All I get is a blank page - any ideas? Also is there some code I can put at the top of every php page to show exactly what the errors are? - I have tried a few scripts but have not found one to work universally. include("cxn.php"); $reg = "G-".strtoupper($_POST['reg']); $sql = "SELECT * FROM sales WHERE reg='$reg'"; $result = mysqli_query($cxn,$sql) or die ("Couldn't execute query"); $num = mysqli_num_rows($result); if ($num >0) // Listing Already Found { echo "The aircraft '$reg' is already listed!"; echo $_SESSION['logname']; } foreach ($_POST as $value) { if ($value == "") { $blank_array[] = $field; } if (@sizeof($blank_array) > 0) // blank fields are found { $error = "Please fill in all the form.<br>"; include ("../sell-your-reg.php"); } } ?> I have a file called myfile.html and it includes the following line: Code: [Select] <!--#include virtual="/output.php" --> The SSI statement works great, but I want more... I would like to be able to link to myfile.html?var=val and use the var string in the php file. However $_GET[var] equals nothing when I try this Is this not possible? Hello, I just wanna know if any such commands are available in php for making a variable as such like - $variable = " blah blah .. . . . index.php?X=<?php echo $_GET['x']; ?>..........blah"; thank you I am building a member-based website, and I've got a bunch of buttons that lead from page to page. The links for these buttons are generated based on user ID and subsequent pages receive this variable as well. So, if you hover over the buttons, you get a link like this: http://www.mysite.com?id=423 How can I hide the last part? The '?id=423'? I must use this format of variable, and cannot resort to session variables. Is there a way to hide this portion of the links?? I have this code: Code: [Select] <?php $item_name = urlencode('product name'); $payment_amount = urlencode('20.00'); $payer_email = urlencode('me@email.com'); $getvars = "?item_name=$item_name&payment_amount=$payment_amount&payer_email=$payer_email"; include "http://www.mysite.com/ipn.php$getvars"; ?> It only seems to be passing $item_name, the other 2 variables come up as being set, but are empty. |