I have done my research and cannot find an answer so now I'm here to seek out professionals' advice.
I have a query which returns an array in model:
$sql = "SalesList ";
$sql = $sql."'".$current_company_code."', ";
$sql = $sql."'".trim($current_user_id)."', ";
$sql = $sql."'".$as_date."', ";
$sql = $sql.$language_no;
$DB=$this->load->database($current_database,TRUE);
$query = $DB->query($sql);
return $query->result();
In controller: I passed the result to $data['sales_list'] and load to view
$data['sales_list'] = $this->SalesList->GetSalesList($current_database,$current_company_code,$current_user_id,date('Y-m-d 23:59:59'),$language_no);
$this->load->view('Sales_Record', $data);
In view:
<?php foreach ($sales_list as $record): ?>
<input type="hidden" name="sp_name_d[]" id="sp_name_d[]" value="<?php echo set_value('sp_name_d[]',trim($record->sp_name));?>"/>
<?php endforeach; ?>
Problem:
Upon submit, the same coding (which presents no issue on first load) prompted the following error:
A PHP Error was encountered
Severity: Notice
Message: Array to string conversion
Line Number: 39
Array"/>
Line no 39 refers to:
<input type="hidden" name="sp_name_d[]" id="sp_name_d[]" value="<?php echo set_value('sp_name_d[]',trim($record->sp_name));?>"/>
Help needed. Thank you.
Sincerely, blossoming programmer.
[Update] Cause of issue (Rookie mistake):
I have some codes in view that use index in set_value (for radio button reference) which leads to multidimensional array:
<input type="radio" name="status_d[<?php echo $counter;?>]" id="status_d[]" value="1" <?php echo set_value('status_d['.$counter.']', '1', $record->status==1); ?> checked />
Solution:
in view added index in set_value:
<input type="hidden" name="sp_name_d[]" id="sp_name_d[]" value="<?php echo set_value('sp_name_d['.$counter.']',trim($record->sp_name));?>"/>
The Problem is:
set_value() - The first time there is no input so it becomes an empty string, but after submit it is an array which remains array.
On an Fresh load of a page there is no previous input data, So everything is empty in Form When setting via set_value.
Related
I want to process form input into a MYSQL database but I am having trouble getting other files to recognize data in the _POST array and keep getting the typical "Undefined index" error.
My form:
<?php
$category = '';
$item = '';
// Check if form is posted
if (isset($_POST['item'])){
// Declare POST'd values into variables
$category = $_POST['Category'];
$item = $_POST['item'];
}
?>
<!-- Item Input form -->
<form id='additem' method='post' action="">
<fieldset>
<legend>Add Item</legend>
<table>
<tr>
<td><label for='Category'>Category: </label></td>
<td><input type='text' name='Category' list='categories' value='<?php $category;?>' /></td>
<datalist id='categories'>
<option value='Protein'>
<option value='Produce'>
<option value='Baked Goods'>
<option value='Dry/Canned'>
<option value='Household'>
</datalist>
</tr><tr>
<td><label for='item'>Name: </label></td>
<td><input type='text' name='item' value='<?php $item;?>' /></td>
</tr><tr>
<td></td><td><input type='Submit' value='Submit' /></td>
</tr>
</table>
</fieldset>
</form>
When I use $_POST in this file, it works perfectly fine but when I try to use it in another file, process.php:
<?php
echo $_POST['Category'];
echo '<br>';
echo $_POST['item'];
?>
it gives:
Notice: Undefined index: Category in E:\Documents\XAMPP\htdocs\Website\process.php on line 3
Notice: Undefined index: item in E:\Documents\XAMPP\htdocs\Website\process.php on line 5
Now I know my _POST array is not empty, because I can access it within my original form file. If I change the form action to "process.php" it works, but also automatically takes me to that page. What I want is for process.php to send data to my database while the form returns to its own page ready for more input. I have even literally copy and pasted the code from that example into files and attempted to run those, but I get similar errors so I think it might be an issue with XAMPP/Apache.
To address this, I have also tried this but post_max_size was already set to 8M, and as per another post I saw somewhere I added 'variables_order = "EGPCS"' in the line below. Still I am getting the same undefined index.
Is there something wrong with my code? Is it XAMPP/Apache? I have tried fresh installing XAMPP, but the issue still persists.
Your $_POST array will not be accessible on all pages.
As much as I have understood your problem , You are trying to access $_POST array on some other file , and this can only be used in this file or the file you post to.
You need to use SESSION in order to use these values
After POST Assign your values like this
$_SESSION["Category"] = $_POST['Category'];
Then on any other page just use
session_start(); on the top of page and then print your variable like
echo "Selected Category is " . $_SESSION["Category"] . ".<br>";
You have not specified the location or file in the action attribute of form element. The file specified in the action attribute can have the values of the form in &_POST[] global array. To access the values across multiple page you should use the cookies
Put check on
category
as you are only checking the
item
in array and if category is not present in array then it will give undefined index error so try the following ways
$category = '';
$item = '';
if (isset($_POST['item']) && isset($_POST['Category'])){
// Declare POST'd values into variables
$category = $_POST['Category'];
$item = $_POST['item'];
}
or if you want you can check them in different conditions
$category = '';
$item = '';
if (isset($_POST['item'])){
// Declare POST'd values into variables
$item = $_POST['item'];
}
if (isset($_POST['Category'])){
// Declare POST'd values into variables
$category = $_POST['Category'];
}
I have a form which I want to make sticky. It has lots of check boxes:
<label><span>ASD</span></label><input type="checkbox" name="condition[]" value="ASD" <?php if (in_array("ASD", $_POST['condition'])) echo 'checked'; ?> /><br />
<label><span>SLC</span></label><input type="checkbox" name="condition[]" value="SLC" <?php if (in_array("SLC", $_POST['condition'])) echo 'checked'; ?> /><br />...
Upon submit this works fine expect if the user makes no selection. I think this is something to do with the fact that the array is empty. I get an error:
Undefined index: condition
and also
in_array() expects parameter 2 to be array, null
thanks
You can check to see if the condition array was passed and if it was not make it an empty array
if(!isset($_POST['condition'])) { $_POST['condition'] = array(); }
If the user doesn't make a selection, $_POST['condition'] will not be defined. This is a simple fix by adding:
if (!isset($_POST['condition'])) $_POST['condition'] = [];
to your script.
This is because:
1) If user does not make any selection the "condition" would not be defined.
2) You are using in_array which require second parameter of type array.
But in case user does not make any selection this parameter will have undefined variable as parameter.
So you can use:
<label><span>ASD</span></label><input type="checkbox" name="condition[]" value="ASD" <?php if (!empty($_POST['condition']) && in_array("ASD", $_POST['condition'])) echo 'checked'; ?> /><br />
SLC />...
I am trying to get some information out of a query and into the values of some inputs, the parameter that it sends to display the specific information is a ID that is being send like this:
PHP on a includes file:
<a href="modificarLab.php?idlab='.$row['idlab'] .'">
<input type = "submit" value = "Modificar" class= "btnModificar" id = "btnModificar-'.$row['idlab'].'"
style="position:absolute;left:170px;top:192px;"/>
</a>
When I click the above link it sends me to another page that reflects the idlab on the URL, so it shows idlab= X, where x depends on the idlab of the button clicked, this part seems to be working just fine.
The problem comes when trying to get the information into the inputs'values, in a example I used as reference they used the exact same syntax (including the part above with the href)and it is working, so I don't know what could I be doing wrong. This is how my code looks:
On the page the href refers to:
UPDATED php:
<?php
isset($_POST['lab']) ? $_POST['lab'] : 'Unknown';
$result = getSpecificLabModify($_GET['lab']);
?>
<form id="frmLabs" method="post">
<?php
if (isset($_GET['idlab'])){
$result = getSpecificLabModify($_GET['idlab']);
}
?>
<label for="txtCapacidad">Capacidad</label>
<input type="text" name="txtCapacidad" id="txtCapacidad" value="<?php echo utf8_encode($result['capacidad'])?>">
<label for="txtNumLab">Código de laboratorio</label>
<input type="text" name="txtNumLab" id="txtNumLab" value="<?php echo utf8_encode($result['codigolab'])?>">
<label for="txtUbicacion">Ubicación</label>
<input type="text" name="txtUbicacion" id="txtUbicacion" value="<?php echo utf8_encode($result['ubicacion'])?>">
But instead of the values inside I am getting the error:
EDIT ERROR:
Notice: Undefined index: idlab in C:\wamp\www\Proyecto\modificarLab.php on line 66
Just in case the function to get the information is this one:
On the includes PHP file:
function getSpecificLabModify($pId){
$query = "SELECT * FROM labs WHERE idlab=$pId";
$result = do_query($query);
$row = mysql_fetch_assoc($result);
return $row;
}
I've tried a lot of things but so far nothing has yielded any results. Thanks in advance.
You're using $_GET not $_POST. So change:
isset($_POST['lab']) ? $_POST['lab'] : 'Unknown';
to:
isset($_GET['lab']) ? $_GET['lab'] : 'Unknown';
I am doing a project in which as per number getting by GET method, I display dynamic number of HTML Textbox for storing Multiple values. I am giving each textbox unique name+id in ascending manner starting from 1(Like textbox1,textbox2). Now I want that when I click on submit button, it should fire an insert statement which insert all textbox values at once. I know I can do by array, but my question is that how to get all textbox's value in an array and How to perform insert statement?
I have done following code:
Here is PHP Code for submit button:
$schedules = array();
if(isset($_POST['submit']))
{
for($d=1; $d<=$_GET['totalDay'] ;$d++)
{
array_push($schedules,$_POST['txtSchedule'.'$d']);
}
print_r($schedules);
}
Here is the html code:
<form method="post">
<table>
<tr>
<td>Day</td>
<td>Schedule</td>
</tr>
<?php
if(isset($_GET['tour_code']) and ($_GET['totalDay']!=1))
{
$tour_code = $_GET['tour_code'];
$total = $_GET['totalDay'];
$i=0;
do
{
$i=$i+1;
?>
<tr>
<td><?php echo $i;?></td>
<td>
<input name="txtSchedule<?php echo $i;?>" type="text" size="30"/>
</td>
</tr>
<?php
$start = date('Y-m-j',strtotime($start.'+1 days'));
}while($i!=$total);
}
?>
</table>
<input type="submit" name="submit" value="Add Tour Details" />
But I am getting an empty array.
Note: $total is coming through URLString's $GET method.
Below is the output of HTML:
Simplest thing first. You have an error, you can't use
array_push($schedules,$_POST['txtSchedule'.'$d']);
You must use DOUBLE QUOTES on the $d (single quotes won't evaluate d, it will literally read "txtSchedule$d" with a dollar sign, and not actually 0, 1,..., n)
array_push($schedules,$_POST['txtSchedule'."$d"]);
//or no quotes at all
array_push($schedules,$_POST['txtSchedule'.$d]);
(that may sovlve your problems)
But now let's get to how to make an array available to the $_POST object in the processing page via form naming conventions
You're not using array syntax, but you are oh-so close. In PHP, whatever is submitted needs to be of an expected format, and iterating txtSchedule0, txtSchedule1, ...txtScheduleN is not an Array(), but $_POST[] is an array that contains each (given what you've named your input fields, which is missing 1 small thing - square brackets).
What you need to do is be naming your inputs as an array is the array name followed by square brackets (arrayName[]), here is how you create an input array of the name txtSchedule (that way when you print_r($_POST['txtSchedule']) you get an Array())
<input name="txtSchedule[<?php echo $i;?>]" type="text" size="30"/>
I had the same issue when I started in PHP, you were forgetting the square brackets around [<?php echo $i;?>]
Just make sure that if you want to do an iteration over an array of inputs:
for($i=0; $i < count($_POST['txtSchedule']); $i++){
echo "They entered " . $_POST['txtSchedule'][$i] . " in the $i" . "th position";
}
... you have used the <input name="arrayName[$i]"> sytax, or even more simply <input name="arrayName[]"> for it to auto-magically generate an array on submit in the order the inputs were in the HTML page. The naming convention is so important, and since you have it wrong (you used arrayName0, arrayName1, ... arrayNameN instead of arrayName[0], arrayName[1], ... arrayName[n]), it will never be available to you as an array.
if i understand your question correctly you are trying to retrive user input from each textbox and save it in an array?
if so I would use jquery to select all textboxes and loop through them and retrive the value
If you are looking purely at the SQL syntax, then you can just append extra records to insert at the end of your query by providing more value sets:
INSERT INTO myTable (fieldName1, fieldName2) values ("Value1A", "Value1B"), ("Value2A", "Value2B")
If you looking at the PHP logic, then my first suggestion is to use the http POST method instead of GET. Then start with processing the $_POST fields:
$data= array();
foreach($_POST as $key => $value) {
if (preg_match('/^TextBox\d+$/', $key)) {
$data[] = $mysqli->real_escape_string($value);
}
}
The construct the SQL query based on the available data
if (count($data) > 0) {
$sql = 'INSERT INTO `myTable` VALUES("' . implode('"),("', $data).'")';
// log query
// execute query
// process query results
// redirect user to a thankyou page
header('Location: thankyou.php');
}
Note that the code assumes that you have a mysqli connection instance available at $mysqli
Not sure if this is what you are looking for but should give you at least a start..
String []ar=request.getParameterValues("name");
String cmd=request.getParameter("cmd");
if(cmd==null) cmd="";
if(cmd.equals("Submit")){
for(int i=0;i<ar.length;i++) {
insert logic;
<form method="post" action="page3.jsp">
<br/><input type="text" name="name"/>
<br/><input type="text" name="name"/>
<br/><input type="text" name="name"/>
<br/> <input type="submit" value="Submit" name="cmd"/>
</form>
Orignal post http://www.daniweb.com/web-development/jsp/threads/197777/insert-dynamic-textbox-value-in-database
Now before we begin let me inform you all that this is just a school assignment and that I am not overly an expert in php and sql coding.
I have the problem, whenever I execute the script, I receive the following error:
Notice: Undefined variable: Team in
C:\xampp\htdocs\NFL\searchmatches.php on line 30.
From my understanding, there would be a spelling error in the link up between the script and the form file, but I can't seem to find the problem.
This is a file to search the database:
Script:
<?php
mysql_connect("localhost","root","0gd1d0wgpg") or die(mysql_error());
mysql_select_db("NFL") or die(mysql_error());
$query=mysql_query("SELECT * FROM Matches where Team ='$Team'") or die(mysql_error());
$numfields = mysql_num_fields($query);
print("<table border=\"1\">\n<tr>\n");
for ($i=0; $i<$numfields; $i++) {
printf("<th>%s</th>\n", mysql_field_name($query,$i));
}
print("</tr>\n");
while ($row = mysql_fetch_row($query)) {
print("<tr>\n");
for ($i=0; $i<sizeof($row); $i++) {
printf("<td>%s</td>\n", $row[$i]);
}
print("</tr>\n");
}
print("</table>\n");
?>
Form:
<form name="addmatch" method="post" action="searchmatches.php">
Search for the match history of a particular team here.<br>
<br>
Team Name: <input type="text" name="Team_Name" value="Team Name">
<br>
<br>
<input type="submit" value="Search">
</form>
Yes there is more coding in the actual files but I figured that, the PHP would be all you needed to help me.
So could somebody please tell me how rid of this error and make the search work.
PHP uses a special "super global" to give you access to submitted form values. The $_POST superglobal is an array with keys that match the name attribute of the form elements (when the form is submitted with the "post" method). Add this line:
$Team = mysql_real_escape_string($_POST['Team_Name']);
above the use of $Team in the query.
To recap, the 'Team_Name' identifier comes from your HTML:
<input type="text" name="Team_Name" value="Team Name">
and then when the form is submitted, whatever you put in that form control is available at $_POST['Team_Name']. I passed the value through the "escape" function so to protect your query from going bonkers (or worse) if that value happened to contain special characters.