PHP - Can A $_post[$variable] Use A Variable In The Argument Position?
I have a form that creates rows of data input textboxes depending on a user input number of things. I have a naming convention for all these textboxes that basically just keeps incrementing a number suffix for each row. All this is working fine.
My problem is I need to get the data inserted into this table of textboxes into an array. Here's my code where I attempt to to this (it does not work): Code: [Select] $temp = $_SESSION['Num_Part']; $count = 1; while ($count <= $temp){ $temp2[$count] = "'Participant_P".$count."'"; //echo $temp2[$count]."<br/>"; $temp3[$count]=$_POST[$temp2[$count]]; //here's the problem $temp4[$count] = "'Result_P".$count."'"; $temp5[$count]=$_POST[$temp4[$count]]; //here's the problem //echo $temp4[$count]."<br/>"; $count++; } The problem is that the $_POST does not work with the variable in the argument position - even though the argument is formatted with single quotes. Can a variable be used in a POST argument and if so what is the correct syntax? If not, is there some other simple solution to harvest the data into an array. I understand I can harvest by explicitly accessing each key in the post assoc array. But this could be dozens of rows of input fields. Thanks in advance for your help here. I couldn't find anything online re this topic. Similar TutorialsHello, i know this is a very silly question but it bothers me to know the reasoning behind it. My application has a design where the functions are stored in functions.php and variables are stored in variables.php. There are some functions that have variables that i might change often and the reason i don't directly use them in the argument itself is so that in future if i have to change the default argument's value , then i wouldn't have to scroll through all the functions and look for it. I have a slippery memory i know i will be able to remember it better if i store custom global variables separately and custom global functions separately. I tried searching these forums for this but its giving me a message like "search daemon not found" or something like that.. Anyways , coming to the point, i know that PHP doesn't accept variables as default arguments but may i know the reasoning behind this? If i understand the reasoning behind this i know it will stick better in my head.So..why does a function not allow a variable as a default value? Or if anyone has a link to explaining this behaviour in PHP, i would appreciate it if you could pass it on! Thank you Code: [Select] $amountBoxName = "amount".$id; // Constructs the name of the input field $amountToPay = strip_tags($_POST["$amountBoxName"]); $amountBoxName then goes to 'amount22' says, however $amountToPay is then showing also as 'amount22', not getting the value of the text field whose name/id is amount22 on the previous page. How do I do this? I tried having " around the $amountBoxName, ' and no quotes although still can't get it working. Hi, I need to pass value of variable to another php file. I thought it is possible to do it as following: <form action="products.php"> <INPUT TYPE=hidden NAME='id' . VALUE='$id'> </form> But the problem is like that. The php file inside which I want to write above html code has not using <form> tag and it has no buttons. So how to initiate the transfer of variable into another php file? Is the above idea is not the good idea? Are there any another ways? Why doesn't this code work... Code: [Select] // Initialize variables. $form_value = ''; $form_value = $_POST['form_value']; I get this error... Quote Notice: Undefined index: form_value Thanks, Debbie Hi Everyone, I'm trying to make an userlist where I have a button (or better a picture with a hyperlink) which if I click it I will be forwarded to a new page where the user name is send as a $_Post variable. The code below is what I have this far. In some way when I click the send button it always gives the last username in the table in the $_Post variable. Can anyone help me please. Thnx Ryflex <?php require_once('auth.php'); require_once('config.php'); $global_dbh = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die("Could not connect to database"); mysql_select_db(DB_DATABASE, $global_dbh) or die("Could not select database"); $user_query = "SELECT * FROM members"; $user_result = mysql_query($user_query); ?> <form ID="gotoresource" NAME="gotoresource" METHOD="POST" ACTION="resource_compose.php"> <table width="500" border="1" align="center" cellpadding="2" cellspacing="0"> <tr> <td><b>User</b></td> <td><b>Resource</b></td> </tr> <?php while($row = mysql_fetch_assoc($user_result)) { echo "<tr>"; echo "<td>"; echo $row['login']; $user = $row['login']; ?> <input name="User" type="hidden" maxlength="15" id="user" value="<?php echo $user; ?>"/> </td> <td> <input type="submit" name="Submit" value="Send" /> </td> <?php echo "</tr>"; } ?> <html> <head> <title>Userlist</title> <link href="loginmodule.css" rel="stylesheet" type="text/css" /> </head> <body> </body> </html> what would be the $_POST variable name for a radio button option? 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; preg_replace() asks that "Delimiter must not be alphanumeric or backslash" in the pattern. So I changed $new_text = preg_replace($_POST['withthis'] ,$_POST['withthis'],$_POST['text']); to this $replacethis = $_POST['replacethis']; $new_text = preg_replace("/$replacethis/",$_POST['withthis'],$_POST['text']); It works fine, but out of curiosity, is there any way to have the POST variable as a parameter directly, and why does it not work? Just to try it, I attempted: "/$_POST['withthis']/" and $_POST["/'withthis'/"] and both do not work. str_replace is a better option I think, but I am just trying to get a better understanding of this delimiter rule. Thanks for your time! I am trying to allow the user to update a variable he chooses by radio buttons, which they will then input text into a box, and submit, to change some attributes. I really need some help here. It works just fine until I add the second layer of variables on top of it, and I can't find the answer to this question anywhere. <?PHP require('connect.php'); ?> <form action ='' method='post'> <select name="id"> <?php $extract = mysql_query("SELECT * FROM cars"); while($row=mysql_fetch_assoc($extract)){ $id = $row['id']; $make= $row['make']; $model= $row['model']; $year= $row['year']; $color= $row['color']; echo "<option value=$id>$color $year $make $model</option> ";}?> </select> Which attribute would you like to change?<br /> <input type="radio" name="getchanged" value="make"/>Make<br /> <input type="radio" name="getchanged" value="model"/>Model<br /> <input type="radio" name="getchanged" value="year" />Year<br /> <input type="radio" name="getchanged" value="color" />Color<br /><br /> <br /><input type='text' value='' name='tochange'> <input type='submit' value='Change' name='submit'> </form> //This is where I need help... <?PHP if(isset($_POST['submit'])&&($_POST['tochange'])){ mysql_query(" UPDATE cars SET '$_POST[getchanged]'='$_POST[tochange]' where id = '$_POST[id]' ");}?> Hello all. I am very new to PHP, and I am not sure where to look or what I'm looking for in my current assignment. My task is to take in two numbers between 0-100. Once I take in that number, it should state beside it "The __ was accepted." The program should not accept any numbers greater than 100 or any characters. Once I do this, I must take a second number and do a similar thing. Finally, I must have a statement show up at the bottom stating which number is greater. Essentially, I need help in determining what I should use to place parameters, and how I can keep the program from echo ing any statement until input has been taken and tested for parameters. Any help you can provide will be greatly appreciated! I have just re-installed Xampp and suddenly my sites are now displaying lots of: Notice: Use of undefined constant name - assumed 'name' in ... Notice: Use of undefined constant price - assumed 'price' in ... this is an example of the line its refering too: $defineProducts[1001] = array(name=>'This is a product', price=>123); My login script stores the user's login name as $_SESSION[ 'name'] on login. For some unapparent reason, i'm getting errors stating that $user and $priv are undefined variables, though I've attempted to define $user as being equal to $_SESSION['name'], using $user to look up the the user's privilege level (stored as the su column ) in the SQL table, and then where the result of the sql query is $priv which is then evaluated in an if statement. I can't seem to figure out why this might not be working. The code I'm using: <?php session_start(); function verify() { //verify that the user is logged in via the login page. Session_start has already been called. if (!isset($_SESSION['loggedin'])) { header('Location: /index.html'); exit; } //if user is logged in, we then lookup necessary privleges. $_SESSION['name'] was written with the login name upon login. Privleges // are written in db as a single-digit integer of of 0 for users, 1 for administrators, and 2 for special users. $user === $_SESSION['name']; //Connect to Databse $link = mysqli_connect("127.0.0.1", "database user", "password", "database"); if (!$link) { echo "Error: Unable to connect to MySQL." . PHP_EOL; echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL; echo "Debugging error: " . mysqli_connect_error() . PHP_EOL; exit; } //SQL Statement to lookup privlege information. if ($result = mysqli_query($link, "SELECT su FROM accounts WHERE username = $user", MYSQLI_STORE_RESULT)) { //LOOP TO CYCLE THROUGH SQL RESULTS AND STORE Privlege information as vairable $priv. while ($row = $result->fetch_assoc()) { $priv === $row["su"]; } } // close SQL connection. mysqli_close($link); // Verify privleges and take action. Only a privlege of "1" is allowed to view this page. A privlege of "2" indicates special //accounts used in other scripts that have certain indermediate additional functions, but are not trusted administrators. if ($priv !== 1) { echo $_SESSION['name']; echo "you have privlege level of $priv"; echo "<br>"; echo 'Your account does not have the privleges necessary to view this page'; exit; } } verify(); ?>
I have a script that adds points together based upon the placing. This is the actual script: Code: [Select] <? $points = 0; if($place === '1st') {$points = $points + 50;} elseif($place === '2nd') {$points = $points + 45;} elseif($place === '3rd') {$points = $points + 40;} elseif($place === '4th') {$points = $points + 35;} elseif($place === '5th') {$points = $points + 30;} elseif($place === '6th') {$points = $points + 25;} elseif($place === '7th') {$points = $points + 20;} elseif($place === '8th') {$points = $points + 10;} elseif($place === '9th') {$points = $points + 10;} elseif($place === '10th') {$points = $points + 10;} elseif($place === 'CH') {$points = $points + 50;} elseif($place === 'RCH') {$points = $points + 40;} elseif($place === 'TT') {$points = $points + 30;} elseif($place === 'T5') {$points = $points + 30;} elseif($place === 'Champion') {$points = $points + 50;} elseif($place === 'Reserve Champion') {$points = $points + 40;} echo "Total HF Points: $points"; ?>What it *should* do (my friend's script works the same way and it works) it starts at points = 0, than if there is a first place, it adds 50, and so forth until it reaches the end. It is included into a file, in this area: Code: [Select] <div class="tabbertab"> <h2>Records</h2> <? $query92 = "SELECT * FROM THISTABLE WHERE VARIABLE='$id' OR VARIABLE = '$name' ORDER BY ABS(VARIABLE), VARIABLE"; $result92 = mysql_query($query92) or die (mysql_error()); echo "<table class='record'> <tr><th>Show</th> <th>Class</th> <th>Place</th></tr> "; while($row92 = mysql_fetch_array($result92)) { $class = $row92['class']; $place = $row92['place']; $entries = $row92['entries']; $race = $row92['show']; $purse = number_format($row92['purse'],2); echo "<tr><td>$race</td> <td>$class</td> <td>$place</td></tr>"; } ?> <tr><td colspan='3'><div align='right'><? include('includes/points.php'); ?></div></td></tr> </table> </div> This is the code that is relevant. When ended here, it echoes the last place that appears in the results (such as a 5th place echoing 30 points). When I move it to be included in the while loop, it shows Total Points: 50 Total Points: 25 Total Points: 10 (depending on the results displayed on that page). What am I doing wrong? Hello everyone, I can get Test 2 to successfully operate the if statement using a variable variable. But when I try the same method using a session variable (Test 1) the if statement is not executed. Please could you tell me why the if statement in Test 1 is not being executed? Code: [Select] <?php # TEST 1 $_SESSION[test_variable] = "abcd"; $session_variable_name = "_SESSION[test_variable]"; if ($$session_variable_name == "abcd") { echo "<br>line 373, abcd<br>"; } # TEST 2 $test_variable = "efgh"; $test_variable_name = "test_variable"; if ($$test_variable_name == "efgh") { echo "<br>line 379, efgh<br>"; } ?> Many thanks, Stu I have a function that get's a quick single item from a query: function gimme($sql) { global $mysqli; global $mytable; global $sid; $query = "SELECT ".$sql." FROM ".$mytable." WHERE sid = ".$sid; $result = $mysqli->query($query); $value = $result->fetch_array(MYSQLI_NUM); $$sql = is_array($value) ? $value[0] : ""; return $$sql; // this is what I've tried so far $result->close(); } It works great as: echo(gimme("name")); Then I realized that I could use that as a variable ('$name' in this case) elsewhere. However, I can't figure out how get that new, variable variable 'outside' of the function. As such, echo($name); isn't working outside the function. Is there a way to return a variable variable? In other words, is there a way to make a function that creates a variable variable that will available outside of the function?
Thanks
Probably something simple but I have searched high and low and can't figure this one out. I have a variable that is of the datetime format. I have another variable that is of the time format. I need to add them together. Example: $var1 = 2012-02-24 06:38:22 $var2 = 02:00:00 $var3 = $var1 + $var2 = 2012-02-24 08:38:22 Thanks for the help! I just moved my code from Appserv to EasyPHP and it gave me this error, it was working fine on Appserv...what's with easyPHP ?? Quote i need to store a variable from database like if i have "copies" in one of my column in my database then i have to store a particular value for copies store it to $copies here i want that i can store value of copies into $copies $update_book="update book set copies=copies-1 where bookid='$bookid'"; $result=mysql_query($update_book,$linkID1); if($result) { print "<html><body background=\"header.jpg\"> <p>book successfully subtracted from database</p></body></html>"; } else { print "<html><body background=\"header.jpg\"> <p>problem occured</p></body></html>"; } } hi all, I have an language pack for example: languages/en.php: Code: [Select] $en['mail']['letter closing'] = "regards,\n your friend!"; and in my config: Code: [Select] $language = "en"; $include_language = @include("languages/".$language.".php"); if(!($include_language)) { $try_default_language = @include("languages/nl.php"); if(!($try_default_language)) { echo "kan de taalpakket niet vinden<br>"; echo "Could not find the language pack.<br>"; echo "example on error: ".$test." shows nothing"; exit; } } In my function I want to include the language pack for example i have $language = 'en' so I want to include $en['general']['letter closing'] I will do this: Code: [Select] global $language,${$language}['general']; But that gives an error unexpected '[' blah blah. How can i call the variable variable array in the valid php way? I have a session variable that will be set to a number called... Code: [Select] $_SESSION['number'] I have page where I want to set a variable in the format of $serv# (with "#" being the value of the session variable). Is there a way to write one simple line of code that in effect says... Code: [Select] $serv . $_SESSION['number'] = "selected='selected'"; I'm just looking to avoid having to write this code... Code: [Select] if ($_SESSION['number'] == 1) { $serv1 = "selected='selected'"; } elseif ($_SESSION['number'] == 2) { $serv2 = "selected='selected'"; } etc etc It's basically putting a variable inside of a variable and I'm not sure if this is allowed/proper? Any insight would be appreciated. Thanks, Gary |