Not getting array values when posting them in a form - php

I have gone through various posts but can't find a solution to this problem:
I have a form with several rows of fields to insert in a database table with one Click of the submit button. This is the code of the HTML:
<form action="filename.php?cartID=<?php echo $_GET['cartID'];?>&customer_id=<?php echo $_GET['customer_id'];?>&total_count=<?php echo $_GET['total_count'];?>&action=add" method="post" id="add_participants" >
<table>
<?php for ($i=0, $n=$_GET['total_count']; $i<$n; $i++) { ?>
<input type="hidden" name="customer_id[]" id="customer_id[]" value="<?php echo $_GET['customer_id'];?>" />
<input type="hidden" name="cartID[]" id="cartID[]" value="<?php echo $_GET['cartID'];?>" />
<input type="hidden" name="products_id[]" id="products_id[]" value="<?php echo $_GET['products_id'];?>" />
<tr><td><label for="title[]">Title</label></td><td><select id="title[]" name="title[]">
<option value="Dr">Dr</option>
<option value="Miss">Miss</option>
<option value="Mr">Mr</option>
<option value="Mrs">Mrs</option>
<option value="Ms">Ms</option>
<option value="Prof">Prof</option>
</select>
</td>
<td><label for="firstname[]">First Name</label></td><td><input type="text" id="firstname[]" name="firstname[]"/></td>
<td><label for="surname[]">Surname</label></td><td><input type="text" id="surnam[]e" name="surname[]"/></td>
<td><label for="email[]">E-mail</label></td><td><input type="text" id="email[]" name="email[]"/></td></tr>
</table>
<?php } ?>
<input value="Add participant" type="submit" />
On the action page the code is the following:
for ($i=0, $n=$_GET['total_count']; $i<$n; $i++) {
$title[$i] = tep_db_prepare_input($HTTP_POST_VARS['title.$i]']);
$firstname =tep_db_prepare_input($HTTP_POST_VARS['firstname.$i']);
$surname =tep_db_prepare_input($HTTP_POST_VARS['surname.$i']);
$email = tep_db_prepare_input($HTTP_POST_VARS['email.$i']);
$customer_id = tep_db_prepare_input($HTTP_POST_VARS['customer_id.$i']);
$cart_id = tep_db_prepare_input($HTTP_POST_VARS['cartID.$i']);
$products_id = tep_db_prepare_input($HTTP_POST_VARS['products_id.$i']);
$query = "INSERT INTO participants (title,Firstname,Surname,Email,customers_id,cart_id,products_id) VALUES ('$title[$i]', '$firstname[$i]', '$surname[$i]', '$email[$i]', $customers_id[$i], $cart_id[$i], $products[$i])";
echo $query . "<br />";
mysql_query($query) or die(mysql_error());
}
However, I cannot get the values of the $_POST variables into the variable arrays to use in the insert statement.
Can anyone help me with this please? I have tried different permutations of the code, and I'm still not getting anywhere.
Many thanks.

I'm fairly certain that $HTTP_POST_VARS is deprecated.. you should be using $_POST instead.
Secondly, your processing doesn't really need to loop over a for loop. You could use foreach to loop over all posted values instead.
Example (untested):
foreach($_POST['customer_id'] as $key => $customerID) {
$title = !empty($_POST['title'][$key]) ? $_POST['title'][$key] : "";
$firstName = !empty($_POST['firstname'][$key]) ? $_POST['firstname'][$key] : "";
// etc...
}

if your keeping the loop the same way, you need to make a change to how you refer to your array elements. change $title[$i] = tep_db_prepare_input($HTTP_POST_VARS['title.$i]']); to
$title[$i] = tep_db_prepare_input($_POST['title'][$i]);
and change the rest of your assignments to follow the same pattern.

The output of tep_db_prepare_input() is of course a mistery, but apart from that it's true what Marc B. says: "Learn basic PHP syntax rules"
$query = "INSERT INTO participants (title,Firstname,Surname,Email,customers_id,cart_id,products_id) VALUES ('$title[$i]', '$firstname[$i]', '$surname[$i]', '$email[$i]', $customers_id[$i], $cart_id[$i], $products[$i])";
echo $query . "";
This will output exactly what's between the double quotes. Try using:
$query = "INSERT INTO participants (title,Firstname,Surname,Email,customers_id,cart_id,products_id) VALUES ('".$title[$i]."', '".$firstname[$i]."', '".$surname[$i]."', '".$email[$i]."', ".$customers_id[$i].", ".$cart_id[$i].", ".$products[$i].")";
echo $query . "";
Using "{$array[$key]}" within double quotes also works, but using "$array[$key]" within double quotes does not work.
Further, $HTTP_POST_VARS is deprecated. Use $_POST

Your code has multiple errors that result in unintended values:
$title[$i] = tep_db_prepare_input($HTTP_POST_VARS['title.$i]'])
foreach is definitely clearer than a for loop
What others said: $HTTP_POST_VARS must be $_POST (or $_REQUEST)
Assuming that your mysterious tep_db_prepare_input() functions correctly, $HTTP_POST_VARS['title.$i]'] is syntactically incorrect. Single quotes mean variables are not parsed: your function is passed the (invalid) contents of $_POST['title.$i]']. I believe you meant to write $POST["title$i"] (where the "." is part of the field name. (Personally an underscore would be less confusing as "." has meaning in PHP.)
So... fix all that and you should be good to go. Well, #2 & 3, at least.

Related

I'm using PHP and need to Insert into sql using a while loop

I'm after a little help. I have a page for a user to input upto 10 different rows of information. Dispatch details. I have created a page with my form using a loop..
<?php
session_start();
require("config.php");
require("header.php");
$db = mysql_connect($dbhost, $dbuser, $dbpassword);
mysql_select_db($dbdatabase, $db);
?>
<br><br><br></br>
<form action="insertdispatch.php" method="post">
<body>
<center>
<table>
<tr>
<td><center><b>Ref</td>
<td><b><center>Date</td>
<td><b><center>Service</td>
<td><b> <center>Tracking</td>
</tr>
<?php
$index = 1;
$name = 1;
while($index <= 10){
?>
<td><input type="text"
name="transno<?php echo $index;?>"
id="transno<?php echo $index;?>" />
</td>
<td><input type="text" name="date<?php echo $index;?>"
id="date<?php echo $index;?> "/>
</td>
<td><select name = "service<?php echo $index;?>"><?php
$viewsql = "SELECT * FROM dispatch_service ORDER BY service ASC";
$viewresult = mysql_query($viewsql);
while($row = mysql_fetch_assoc($viewresult)){
?> <option value=<?php echo $row['service'] ;?>>
<?php echo $row['service'] ;?></option>
<?php
}
echo "</select>";?>
<td><input type="text"
name="tracking<?php echo $index;?>"
id="tracking<?php echo $index;?>"/>
</td>
</tr>
<?php $index ++;
}?>
<center>
<td><input type="submit" value="Add Product" />
</form>
</center>
</td>
</tr>
</table>
</center>
<center><a href='javascript:history.back(1);'>Back</a>
</body>
</html>`
I have 10 of each text box, the name of the text box adds the value of index to the end. (with my limited coding experience I am very pleased with myself) so I go to the insertdispatch.php page and the plan is to insert each of these values into my table... now...I have no clue... and I cannot seem to figure out how I am going to do this...
I think I will need to use a loop again.. but I can't seem to figure out how I am going to call each of the $_POST values. I don't really want to use 10 different insert statements, as the form may increase in size. here is what I have so far..
<?php
session_start();
require("config.php");
$db = mysql_connect("localhost","root","");
if (!$db)
{
do_error("Could not connect to the server");
}
mysql_select_db("hbt",$db)or do_error("Could not connect to the database");
$index = 1;
while($index <= 10){
$insertsql = "INSERT into dispatch (trans_no, date, service, tracking) values ()";
mysql_query($insertsql);
$index ++;
}
//header("Location: " . $config_basedir . "home.php");
?>
I am not looking for anyone to finish the coding for me, but any tips would be grateful! :)
you can build 1 insert statement that inserts multiple rows:
INSERT into dispatch (trans_no, date, service, tracking) values
(1, '2013-09-12', 'myService1', 'on'),
(1, '2013-09-12', 'myService2', 'on'),
(1, '2013-09-12', 'myService3', 'on'),
(1, '2013-09-12', 'myService4', 'on'),
(1, '2013-09-12', 'myService5', 'on');
Just build this inside your the while, and execute it after the while has finished.
To build this query, you will need to perform the exact same loop as when you are generating the HTML, but now just fetch the values from $_POST instead of create a html field for them...
note while building your HTML, you are firing a static query inside your for loop. since this query is static, the results will also not change, and it is best to execute that query outside of the outer while loop.
(you really should read up more on basic HTML - tehre are lots of mistakes there even before considering the PHP code).
name="transno<?php echo $index;?>"
This is really messy too - you are creating extra work and complication for yourself. Use arrays:
name="transno[]"
If you do exlpicitly want to reference the item again then set the index:
id="transno[<?php echo $index; ?>]"
And at the receiving end....use a single insert statement to add the rows - not 10 seperate ones (it will be much faster).
You've already set up your while loop with $index - you could simply use that to iterate through the POST values, since you set their name attribute with an index. Consider:
$index = 1;
while($index <= 10){
$trans_no = $_POST["transno$index"];
$service = $_POST["service$index"];
$date = $_POST["date$index"];
$tracking = $_POST["tracking$index"];
$insertsql = "INSERT into dispatch (trans_no, date, service, tracking)
VALUES($trans_no, $date, $service, $tracking)";
mysql_query($insertsql);
$index++;}
Though it would be much cleaner to set up your form inputs as arrays, as noted by others here.
Also, please read up on SQL injection. You need to sanitize any user input before it's inserted into a database - otherwise a malign user could wipe your whole database.

How to retrieve imploded array from a cell in an MySQL database through PHP

Thanks for taking the time to look at this question.
Currently, I have a piece of code that creates four checkboxes labeled as "Luxury, Brand, Retailer," and "B2B." I have looked into a number of PHP methods to create checkboxes, and I felt the implode() function was the most simple and suitable for my job. I have looked into a number of tutorials to create the implosions, however, they did not fit my criteria, as I would like the database values be reflected in the front-end. Currently in my database, the implode() works, therefore (for example), if I check "Luxury", "Brand", "Retailer", and press the "Submit" button, the three items "Luxury, Brand, Retailer" will be in that specified cell. It looks like my code works in the back-end, but these are my issues:
I am not exactly sure (despite multiple Googles) how to retrieve those values stored in the single-cell array, and have it selected as "selected" (this would "check" the box in the front-end)
Could someone kindly take a look at my code below and let me know what seems to be missing/wrong/erroneous so I could attempt the revisions? Anything would be appreciated, thank you!
<?
if (isset($_POST['formSubmit2'])){
$category = mysql_real_escape_string(implode(',',$_POST['category']));
$accountID = $_POST['accountID'];
mysql_query("UPDATE Spreadsheet SET category='$category' WHERE accountID='$accountID'");
}
$query = mysql_query("SELECT * FROM Spreadsheet LIMIT $firstRow,$rpp");
while($row = mysql_fetch_array($query)){
// Begin Checkboxes
$values = array('Luxury','Brand','Retailer','B2B');
?>
<form name ="category" method ="POST" action ="" >
<?
echo "<input type = 'hidden' name = 'accountID' value = '" . $row['accountID'] . "' >";
for($i = 0; $i < count($values); $i++){
?>
<input type="checkbox" name="category[]" value="<?php echo $values[$i]; ?>" id="rbl_<? echo $i; ?>" <? if($row['category'] == $i) echo "checked=\"checked\""; ?>/>
<? echo $values[$i] ?><br>
<? } ?>
<input type ="Submit" name ="formSubmit2" value ="Submit" />
</form>
<? } ?>
The best approach i can recommend given what you have is to, explode the values out of the db giving you a new array of all the select fields. Then use in_array to compare the list you have with this new list in the loop. then flag the checkboxs as needed.

PHP:Variable in function not working

I'm trying to get dns records of a domain through dns_get_record() but the function doesn't seem to work when a variable is inserted..here's my code
<form action="" method="post">
<input type="text" name="host" placeholder="Enter IP or Domain"/>
<select name="dns">
<option value="DNS_A" selected="selected">A</option>
....
<option value="DNS_ANY">ANY</option>
</select>
</form>
<?php
$host=$_POST['host'];
$dns=$_POST['dns'];
$type=end(explode('_',$dns));
if ($host==""){
exit();
}
echo "Results for $host $type record<br />";
$result = dns_get_record($host, $dns);
echo "Result = ";
print_r($result);
?>
but if i put
$result = dns_get_record($host, DNS_A);
instead of
$result = dns_get_record($host, $dns);
it works..help!
DNS_A is a constant of value 1, while you are passing string "DNS_A", try by passing value of constant, using $result = dns_get_record($host, constant($dns));
This is because your POST returns a literal string: "DNS_A", if you prefer. This is NOT the same as DNS_A, which is a constant and most likely contains an integer.
You'll need a mapping table for this one. Or just pass the integer value straight off.

Posted multiselect box selection to database only adding the first selected item

i am using the following multiselect box to take input from users, this then gets posted to my php form which adds it to the database, the problem is, all I am getting added is the first selection, if the user selects more than one field I still only get the first field.
If the user selects lets say internet, drawing,maths I want that to be put into the database, at the moment all that is inserted is internet, or whatever is the first thing selected in the list.
My form looks like this >>
<form action="../files/addtodb.php" method="post" style="width:800px;">
<select name="whatisdeviceusedfor[]" size="1" multiple="multiple" id="whatisdeviceusedfor[]">
<option value="games">Games</option>
<option value="takingphotos">Taking Photos</option>
<option value="maths">Maths</option>
<option value="reading">Reading</option>
<option value="drawing">Drawing</option>
<option value="internet">Internet</option>
<option value="other">Other (enter more info below)</option>
</select>
<input type="submit" name="submit" id="submit" value="Submit">
</form>
The php side looks like this >>
<?php
// Implode what is device used for
$usedfor = $_POST['whatisdeviceusedfor'];
$arr = array($usedfor);
$whatisdeviceusedfor = implode(" ",$arr);
// Insert posted data into database
mysql_query("INSERT INTO itsnb_year5questionaire (whatisdeviceusedfor) VALUES '$whatisdeviceusedfor'") or die(mysql_error());
?>
you are already getting array by select so you dont need to use $arr = array($usedfor);this again
just try
$usedfor = $_POST['whatisdeviceusedfor'];
$whatisdeviceusedfor = implode(" ",$usedfor);
or
$usedfor = $_POST['whatisdeviceusedfor'];
$strings ='';
foreach ($usedfor as $item){
$strings .=' '. $item;
}
echo $strings;
and
<select name="whatisdeviceusedfor[]" size="5" multiple="multiple" id="whatisdeviceusedfor[]">
^^
||change to option you want to select
i have changed size="5" so it will select now 5 at a time ...you have only 1 so it will let only 1 select at a time
result
warning
your code is vulnerable to SQL injection also use of mysql_* function are deprecated use either PDO or MySQLi
If you have selected mutliple items via a SELECT or via CHECKBOXES, the form will return an array-like data structure. You will always need to loop over that data and store each item individually into the database or concatenate the values to a string before inserting.
first change size = "5" to see good the list
then try to make like that (its second option if you like it)
if ($_POST) {
// post data
$games = $_POST["games"];
$takingphotos = $_POST["takingphotos"];
.
...
// secure data
$games = uc($games);
$boats = uc($takingphotos);
.
...
}
// insert data into database
$query = "INSERT INTO itsnb_year5questionaire (games, takingphotos,....)
VALUES('$games','$takingphotos',......)";
mysql_query($query) or die(mysql_error());
echo 'Thanks for your select!';
Because $usedfor is contain the array you can directly use it in foreach to save the each value in the value.Try this it may help you:
<?php
$usedfor = $_POST['whatisdeviceusedfor'];
foreach($usedfor as $arr){
mysql_query('INSERT INTO itsnb_year5questionaire(whatisdeviceusedfor) VALUES("'.$arr.'"') or die(mysql_error());
}

Populate Text Field with PHP variable

I'm retaining values in form elements after a form submit. I've got it to work fine with a select box using the following:
<select name="BranchManager" class="formfield" id="BranchManager"onchange="document.forms[0].submit();SEinit();"><option value="">-- Select Manager --</option>
<?php
$area = $_POST['Area'];
if ($area); {
$BMquery = "SELECT DISTINCT Branch_Manager FROM Sales_Execs WHERE AREA = '$area' ".
"ORDER BY Branch_Manager";
$BMresult = mysql_query($BMquery);
while($row = mysql_fetch_array($BMresult))
{
echo "<option value=\"".$row['Branch_Manager']."\">".$row['Branch_Manager']."</option>\n ";
}
}
$branchmanager = $POST['BranchManager'];
?>
<script type="text/javascript">
document.getElementById('BranchManager').value = <?php echo json_encode(trim($_POST['BranchManager']));?>;
</script>
Which works fine (apologies if it isn't the cleanest/most efficient code, I'm doing my best!) The next field is a text field that needs to be populated based off the Branch Managers name above. So I've used :
<input name="BranchNum" type="text" class="formfield" id="BranchNum" size="3" maxlength="3" />
<?php
$bm = $_POST['BranchManager'];
if ($bm); {
$BNumquery = "SELECT DISTINCT BRANCH_NUM FROM Sales_Execs WHERE Branch_Manager = '$bm' ";
$BNumresult = mysql_query($BNumquery);
}
$branchnum = $POST['BranchNum'];
?>
<script type="text/javascript">
document.getElementById('BranchNum').value = <?php echo json_encode($BNumresult);?>;
</script>
Which isn't working... where am I going wrong here?
why are you having semicolons after if condition checks?
if ($bm);
if ($area);
This will always terminate the statement and whatever is in the curly braces will always get executed irrespective of the value in $bm or $area
You need mydql_fetch functions to retrive data from $result.
if($row = mysql_fetch_array($BNumresult))
$branchNum = $row[BRANCH_NUM];
why are you using json_encode when your input tag has size = 3?
You need to put value="<? echo $variableName; ?>" inside the input field
The reason is because a) you're not echoing, and b) you must echo in a different spot than in a select. You must echo in the value portion of the input.
<?php
$bm = mysql_real_escape_string($_POST['BranchManager']);
if ($bm) {
$BNumquery = "SELECT DISTINCT BRANCH_NUM FROM Sales_Execs WHERE Branch_Manager = '$bm' ";
$BNumresult = mysql_query($BNumquery);
}
$branchnum = $POST['BranchNum'];
?>
<input name="BranchNum"
type="text"
class="formfield"
id="BranchNum"
size="3"
maxlength="3"
value="<?php echo htmlspecialchars($branchnum); ?>" />
As per the comments, they are correct; you should not be using mysql_*. Instead, look at PDO; though this is outside the scope of your question.

Categories