Appending loop number to SQL row variable - php

"Undefined variable: payout_item_1" so it's getting the variable name correctly but I must have the format wrong.
for ($x = 1; $x <= 5; $x++) {
echo "<input name = 'payout_item_" . $x . "' type = 'text' value = '" . $row[${"payout_item_" . $x}] . "' style = 'width : 150px;' ";
}

I'm making a couple assumptions
You have a table with columns "payout_item_1" through "payout_item_5"
You do not have variables called $payout_item_1 through $payout_item_5 in which the actual column names are stored.
Currently your code is building variable variables:
This statement builds a variable name with payout_item_1 (in the first iteration). Effectively $payout_item_1.
${"payout_item_" . $x}
The code is then looking for a value in that variable to use as the column header name. Effectively, it's expecting somewhere further up for there to be something akin to
$payout_item_1 = "column1";
Which, as the error suggests, it cannot find. If my assumption in 1. was correct, all you need to do is reformat to
$row["payout_item_" . $x]
and you will be referencing the column payout_item_1 (through 5) from your $row object. Written literally:
$row["payout_item_1"]

Related

Creating a Loop To get info from form Where the amount of fields can vary

I have a form that allows users to register into a database. They can register up to a group of 6 at a time. Currently the webpage displays two forms. The first (userNumberForm) is just a drop down list where the user picks how many names to register. That gets posted and when the page reloads the 2nd form (userInfoForm) runs a while loop to populate the correct number of fields for the user to enter their information in. It also contains a hidden field where the value from the userNumberForm is stored. When the userInfoForm gets posted the first thing I have the addUser.php (the page it posts to) do is check the number of users and store that in a variable called userNum. Currently I have a switch statement based on that variable to get the rest of the information from the form and sanitize the data.
case 2:
$FirstName1=$_POST['FirstName1'];
$FirstName2=$_POST['FirstName2'];
$FirstName1 = stripslashes($FirstName1);
$FirstName1 = mysql_real_escape_string($FirstName1);
$FirstName2 = stripslashes($FirstName2);
$FirstName2 = mysql_real_escape_string($FirstName2);
break;
case 3:
$FirstName1=$_POST['FirstName1'];
$FirstName2=$_POST['FirstName2'];
$FirstName3=$_POST['FirstName3'];
$FirstName1 = stripslashes($FirstName1);
$FirstName1 = mysql_real_escape_string($FirstName1);
$FirstName2 = stripslashes($FirstName2);
$FirstName2 = mysql_real_escape_string($FirstName2);
$FirstName3 = stripslashes($FirstName3);
$FirstName3 = mysql_real_escape_string($FirstName3);
break;
//... and so on
As you can see this is starting to be a lot of code. I am hoping there is a way to set something up like this:
$x = 1;
while($x < $userNum)
{
$FirstName.$X=$_POST['FirstName.$X'];
$FirstName.$X = stripslashes($FirstName.$X);
$FirstName.$X = mysql_real_escape_string($FirstName.$X);
++$x;
}
Obviously that doesn't work, but that is the format I am looking for. I don't fully understand variable variables yet, Or maybe I'm making this more complicated than it needs to be and there is a way to stick this in an array.
Yes a while statement can be used. Remember to append $x outside the string when accessing the variable from $_POST - i.e. $_POST['FirstName' . $x]; (though you could use double-quoted strings, since the variables will be expanded: $_POST["FirstName$x"];). Also the looping condition needs to be updated to less than or equal (i.e. <=) - otherwise the last name will not be processed.
So update the condition from :
while($x < $userNum)
To:
while($x <= $userNum)
Then instead of using $FirstName.$X for the variable, just use a single name - e.g. $FirstName. As long as it is consistent, it will be used for that iteration separately.
$x = 1;
while($x <= $userNum)
{
$FirstName = $_POST['FirstName' . $x];
$FirstName = stripslashes($FirstName);
$FirstName = mysql_real_escape_string($FirstName);
//use $FirstName to insert into database, or store in temporary structure
++$x;
}
But then also a for statement could also be used. That can reduce the number of lines needed, as the variable to iterate (i.e. $x) is started and incremented in one line.
for ($x = 1; $x <= $userNum; $x++)
{
$FirstName = $_POST['FirstName' . $x];
$FirstName = stripslashes($FirstName);
$FirstName = mysql_real_escape_string($FirstName);
//use $FirstName to insert into database, or store in temporary structure
}
And taking it one step further, a foreach statement can be used with range(). With this structure, the variable doesn't need to be incremented manually and there is no need for the looping condition (i.e. $x <= $userNum).
foreach (range(1, $userNum) as $x)
{
$FirstName = $_POST['FirstName' . $x];
$FirstName = stripslashes($FirstName);
$FirstName = mysql_real_escape_string($FirstName);
//use $FirstName to insert into database, or store in temporary structure
}
Or maybe I'm making this more complicated than it needs to be and there is a way to stick this in an array
Yes you could store those names in an array, like this:
$FirstNames = array();
foreach (range(1, $userNum) as $x) {
$FirstNames[$x] = $_POST['FirstName' . $x];
}
//use $FirstNames later to add values to the database
See a demonstration of this in this phpfiddle.
$x = 1;
$FirstName = array();
while($x < $userNum){
$FirstName[]=$_POST["FirstName.$x"];
$x++;
}
// you will get array of names then you can insert it to mysql

How to create dynamic variables from SQL results

This one should be easy and it's killing me I can't find the solution!
I have a SQL query return records from a database. The two fields I am using are $row["staff_id"] and $row["name"].
From that I want to build a dynamic variable which is something like:
$staffid_1 = "Mark Smith";
$staffid_2 = "Sally Baker";
$staffid_3 = "Peter Pan";
The varibale name is created dynamically be combining "staffid_" and $row["staff_id"] for the first part then $row["name"] for the name.
I've tried:
${$staff_id . $row["staff_id"]} = $row["name"];
echo ${$staff_id . $row["staff_id"]} . "<br>";
But no luck! Any assistance would be appreciated :)
I would think you might be best to change your query to return the first part of it, then whatever you're calling it from to concatenate it together, eg
Query:
SELECT '$staffid_' + ltrim(rtrim(cast(staff_id as varchar))) + ' = "' + name + '"'
FROM [table list]
ORDER BY ...
Then concatenate the individual rows of result set as required, with in-between as you seem to require.
Okay so in PHP you have an awesome option to use a double leveled variable which basically means this :
$$varname = $value;
This results in the fact that if you have a string variable ,
(for example $staffid = "staffid_1") that you can do the following:
$staffid = "Jasonbourne";
$$staffid = "Matt Damon";
// Will result in
$JasonBourne = "Matt Damon";
So for your example:
$name = "staffid_" . $row["staff_id"];
$$name = $row["name"];
Will result in the variable : $staff_id_1 = "Mark Smith";
To read more about double - leveled variables :
http://php.net/manual/en/language.variables.variable.php
EDIT: If you wanna loop through the rows :
foreach ($sql_result as $row) {
$name = "staffid_" . $row["staff_id"];
$$name = $row["name"];
}

Php variable increment

So i have the following code that works and outputs the information let's say 2 11. I would like to have $keyidcall increment in variable name so $keyidcall2, $keyidcall3....... with the additional variables I would like the variable to hold the correct value so I can call it later. so expected output would be $Apiammount ="2";
echo $keyidcall; would echo 2
echo $keyidcall: would echo 11
while($Apiammount > 1){
$Keyidquery = mysqli_query($connection, "SELECT ID FROM `Characterapi` WHERE UserId = '$Idcall'");
while($keyid = mysqli_fetch_assoc($Keyidquery)){
$keyidcall = $keyid['ID'];
echo $keyidcall;
}
$Apiammount--;
}
The better way to do this would be to store the values in an array.
$keyidcall[] = $keyid['ID'];
Then you can refer to them later as
echo $keyidcall[0];
echo $keyidcall[1];
in the order that they were entered in.
Or if you wanted something more specific to refer to it by, you could use
$keyidcall[$Apiammount] = $keyid['ID'];
then you would refer to them as:
echo $keyidcall[<apiamount>];
Assuming you know what that would be.
You can do:
$i = 0;
while($foo){
$name = 'keyidcall';
$i++;
$newvar = $name . $i;
echo $$newvar;
}
And $$newvar will echo the value of "keyidcallX" where X is an incrementing value. Not sure if that's what you meant.

While Loop Seems Endless

I have a table named getinvolved and in this table there are various fields and values, obviously. One such is named The Route and contains text separated by commas. For the sake of this we'll say they are Spot 1, Spot 2, Spot. Yes the spaces matter.
Now, in my code I first break this value up into an array based on the commas: $route = explode(",", $row['Content']); Content is the name of the row that contains the Spot 1, Spot 2, Spot text value. This all works fine, I have echo'd this and it appears perfectly.
Next comes the tricky bit, I have multiple other entries that are instead of being labelled The Route are instead labelled Route. This is an entry for each possible spot, while the current route is Spot 1, Spot 2, Spot it could always change to Spot 2, Spot 1, Tops.
Each possible entry has it's own row: Name, Type, Content. Type is where Route is set, Name is the name of the spot, and Content contains a Google Maps URL to show the spot in Google Maps Street View.
What I'm trying to do is take my array $route[] which currently contains Spot 1, Spot 2, Spot and check those values against all others. I've created a separate array $echoroute[] and this contains the actual route with all the information.
My code is as follows:
$sql = mysqli_query($link, "SELECT * FROM getinvolved WHERE Type='Route'");
$echoroute = array_fill(0,count($route),""); #Gives $echoroute[] 3 empty elements as $route will always contain 3 elements at the moment.
$i = 0;
$max = count($route);
if($sql)
{
foreach($route as $ii)
{
while($row = mysqli_fetch_assoc($sql))
{
if($row['Name'] == $ii)
{
$echoroute[$i] = "<a href='" . $row['Content'] . "' target='_blank'>" . $row['Name'] . "</a> --> ";
echo $i . " / " . $max . "<br />";
$i+=1;
if($i==($max)) {break 2;} else {break 1;}
}
}
}
}
I'm unable to figure out why but at present during running this code all that happens is it will go through the if as $sql passes, it enters the first and second while loops and then gets to the if($row['Name'] == $route[$i]) part. Here it seems to work fine until it actually enters the if statement (the value in $row['Name'] is equal to the one in $route[$i]).
$total is increased as where I ask it to echo it does, but only once. The code ends and displays the following:
0 / 3
3
The 1 represents the $total variable, which should go through 3 times according to while($total<$max).
The / is me adding a separator for ease of reading.
The 3 is the $max variable, or count($route), the total number of spots included in the $route array.
And finally the trailing 3 is a count() function of $echoroute letting me know there are 3 elements in that array.
Ultimately, my question is, why does $total never get to 2 and finish the loop as I would require?
This took a while to write, so I hope you understand I've put a bit of thought into this, I wrote this a while ago, and it needs some updating and this is where I am currently at.
EDIT:
Have narrowed this down now! Using several echo functions, it appears that the last run through starts, but only makes it as far as the while statement. It never actually enters the while statement. Currently I have two results echo'd and the last result just so happens to be at the bottom of the table. It's the last one to be used before the while($row = statement ends of it's own accord. Am I trapping the while statement or do I need to release it or something? I'm really confused and so close to having the final piece!
You initialize $echoroute with count($route) elements (3 in your example).
You loop over a condition and increase value of $i and $total if a condition is met.
At this point, into the while loop where $total and $i values are 2 ( while condition is met 2 < 3 ) and if they enter the if condition you get 3 value for $i and $total and if you echo $echoroute[$i] then you've got an error, because $echoroute is a 3 element array and you are pointing to a fourth element (remember array indices start from 0 ).
I think this is why you are not getting you expected output.
i'd write it this way, since there is chance (following Moor laws) that the loop on $total never ends
$sql = mysqli_query($link, "SELECT * FROM getinvolved WHERE Type='Route'");
$echoroute = array_fill(0,count($route),""); #Gives $echoroute[] 3 empty elements as $route will always contain 3 elements at the moment.
$i = 0;
$total = 0;
$max = count($route);
if($sql)
{
while($row = mysqli_fetch_assoc($sql))
{
if($row['Name'] == $route[$i])
{
$echoroute[$i] = "<a href='" . $row['Content'] . "' target='_blank'>" . $row['Name'] . "</a> --> ";
$i++;
$total++;
if ($total>$max) break;
echo $total . " / " . $max . "<br />" . $echoroute[$i] . count($echoroute);
}
}
}

variable php variables :D

I have the ability to add custom fields in a project I am making. I have a page that has all the text inputs on it. Each custom field is named consecutively (field1, field2, field3) according to the order they were created. Since the user will have the ability to add as many as they want, how can I select each one so as to post their values to the database?
Hope this makes sense...
You should name the fields with array notation, as follows:
<input name='field[]' type='text' />
<input name='field[]' type='text' />
You can then retrieve the data from $_POST (or $_GET) as
$_POST['field'][0]
$_POST['field'][1]
try this:
for($i=1;$i<=3;$i++) {
print ${'field' . $i} . "<br>";
}
Here's how you would collect them if they are passed in _GET/_POST
$i = 1;
$custom_fields = array();
while (!empty($_REQUEST["field$i"]) {
$custom_fields[] = $_REQUEST["field$i"];
$i++;
}
Assuming that each of these fields will be posted, you can use a simple while loop and check that the variable is set:
$i = 1;
while ( isset($_POST['field' . $i]) ) {
// Do what you need to do to the variable here
// Whatever you do, do not forget this line
$i += 1;
}

Categories