I need some help with this code.
In my code, I have the following hidden form fields as array:
Code:
<form action='final.php' method = 'POST'>
<input type="hidden" name="employeename" value="<?php echo $employeename; ?>">
<input type="hidden" name="ttitle" value="<?php echo $ttitle; ?>">
<input type="hidden" name="sourcename[]" value="<?php echo $_POST['sourcename' . $id]; ?>">
<input type="hidden" name="sourceaddress[]" value="<?php echo $_POST['sourceaddress' . $id]; ?>">
<input type="hidden" name="income[]" value="<?php echo $_POST['income' . $id]; ?>">
<input type="hidden" name="spousename[]" value="<?php echo $_POST['spousename' . $id]; ?>">
<input type="hidden" name="spouseAddress[]" value="<?php echo $_POST['spouseAddress' . $id]; ?>">
<input type="hidden" name="spouseIncome[]" value="<?php echo $_POST['spouseIncome' . $id]; ?>">
</form>
These hidden form fields are on a page called reviewe.php passed from pervious page called order.php.
I am trying to insert the values of these form fields from a page called finel.php as the action on the form indicates.
Code:
$sql = 'INSERT INTO `myDB`.`wp_myTable` ( `employeeID`'
. ', `sourcename`, `sourceaddress`, `income`,`spousename`,`spouseAddress`,`spouseincome` )'
. ' VALUES ( ? , ? , ? , ? , ? , ? , ? )';
if( $sth = mysqli_prepare($conn,$sql) ) {
mysqli_stmt_bind_param($sth,'sssssss'
,$last_id
,$_POST["sourcename"]
,$_POST["sourceaddress"]
,$_POST["income"]
,$_POST["spousename"]
,$_POST["spouseAddress"]
,$_POST["spouseIncome"]
);
When this code is excuted, I get this error:
Notice: Array to string conversion in c:\xampp\folder\final.php
I know this error means that I have hidden form fields I am trying to pass as an array but I am trying to insert them as string.
However, I don't know how to modify the code to accept the variables as array.
Any advice ? Thankyou.
You can get the value of the hidden inputs, while they are in an array, by simply getting the first index of the array.
if( $sth = mysqli_prepare($conn,$sql) ) {
mysqli_stmt_bind_param($sth,'sssssss'
,$last_id
,$_POST["sourcename"][0]
,$_POST["sourceaddress"][0]
,$_POST["income"][0]
,$_POST["spousename"][0]
,$_POST["spouseAddress"][0]
,$_POST["spouseIncome"][0]
);
You can use implode function to write the array as string by doing something like this:
implode(",", $array);
and then use explode function to read it back in an array like this:
explode(",", $array);
Related
I am doing a program with PHP but this is the first time I need to enter many arrays in a table. In the input I must place [] but when making the query insert how should I do? What I present in the code only saves me the last value without the [], and in the console, it passes the values that I need, but it only inserts the last value.
<form class="" action="asignar-fechas.php" method="post">
<?php foreach ($infoGrupo2 as $iGrupo2){
if(($iGrupo2['fechaInicio']==$fechaA['numero_fecha'])){
?>
<input type="hidden" name="id_grupo2[]" value="<?php echo $iGrupo2['id_grupo'];?>">
<input type="hidden" name="modo2[]" value="<?php echo $iGrupo2['modo'];?>">
<input type="hidden" name="fecha2[]" value="<?php echo $iGrupo2['fechaInicio'];?>">
<input type="hidden" name="participante[]" value="<?php echo $iGrupo['participante'];?>">
<input type="hidden" name="jugador<?php echo $juga;?>[]" value="<?php echo $in2['id_users'];?>">
}}?>
<input type="submit" name="enviar" value="ASIGNAR FECHAS">
asignar-fechas.php
$id_grupo = $_POST['id_grupo2'];
$modo = $_POST['modo2'];
$fecha = $_POST['fecha2'];
$participante = $_POST['participante'];
$j1 = $_POST['jugador1'];
$j2 = $_POST['jugador2'];
$j3 = $_POST['jugador3'];
$j4 = $_POST['jugador4'];
$insertarF = "INSERT INTO fechaxgrupo (grupo, fecha,estado) VALUES (:grupo, :fecha,0)";
$insertF = $conn->prepare($insertarF);
$insertF->bindParam(':grupo', $id_grupo);
$insertF->bindParam(':fecha', $fechaa);
$insertF->execute();
The $_POST variables elements will be arrays, you can loop over them. You need to bind to the iteration variables, not the arrays.
$insertarF = "INSERT INTO fechaxgrupo (grupo, fecha,estado) VALUES (:grupo, :fecha,0)";
$insertF = $conn->prepare($insertarF);
$insertF->bindParam(':grupo', $id_grupo);
$insertF->bindParam(':fecha', $fecha);
foreach ($_POST['id_grupo2'] AS $i => $id_grupo) {
$fecha = $_POST['fecha2'][$i];
$insertF->execute();
}
I want to get three values separated by a comma when the form is submitted. The value from the checkbox, textbox 1 and textbox 2.
This is my code that retrieves values from mysql database and generates checkboxes and two corresponding textboxes.
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<?php
$query = "SELECT * FROM subject";
$data = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($data)){
$s = $row['sub'];
echo $s;
?>
<input type="checkbox" name="req_sub[]" value= "<?php echo $s; ?>" />
<input type="text" name="<?php echo $s; ?>" placeholder="Total Number" />
<input type="text" name="<?php echo $s; ?>" placeholder="Pass Number" />
<?php
}
?>
<input type="submit" name="submit" value="Add">
</form>
Suppose the user checks the first three boxes , and enters the values like in this picture -
when I click add, I get the values --
Physics
Math
Chemistry
by using the code below:
<?php
if (isset($_POST['submit'])) {
if (!empty($_POST['req_sub'])) {
foreach ($_POST['req_sub'] as $selected) {
echo $selected."</br>";
}
}
}
?>
but how do I get the values like this-
Physics,40,30
Math,40,30
Chemistry,30,25
I want this output in a variable so that I can store it in my database table.
I have spent several hours behind this in last few days. Please help me with this one.
you need to assign unique names to the <input type="text" ... /> so you can recieve its values in the PHP.
Second, you need to write PHP code, that's concatenating those values.
For example, your HTML code might be:
<input type="checkbox" name="req_sub[]" value= "<?php echo $s; ?>" />
<input type="text" name="total[<?php echo $s; ?>]" placeholder="Total Number" />
<input type="text" name="pass[<?php echo $s; ?>]" placeholder="Pass Number" />
and your PHP code might be:
if (isset($_POST['submit'])) {
if (!empty($_POST['req_sub'])) {
foreach ($_POST['req_sub'] as $selected) {
$total = $_POST['total'][$selected];
$pass = $_POST['pass'][$selected];
$var = $selected . ',' . $total . ',' . $pass;
echo $var . '<br />';
}
}
}
I start with the following:
<form action="" method="post" enctype="multipart/form-data" id="form">
<?php foreach($attributes as $attribute){ ?>
<input type="checkbox" name="attribute[][attr_id]" value="<?php echo $attribute['attribute_id']; ?>">
<input type="text" name="attribute[][attr_name]"> value="<?php echo $attribute['attribute_name']; ?>">
<?php } ?>
</form>
So each $attribute has a checkbox and a text input; whenever someone would check (one or more boxes) and would insert text (only to the checked items) I want to get in the DB the [attr_id] and the [attr_name] for the specific item.
So I continue with the following:
if(isset($_POST['attribute'])){
foreach($_POST['attribute'] as $attribute){
$attr_id = $attribute['attr_id'];
$attr_name = $attribute['attr_name'];
"INSERT INTO " . DB_PREFIX . "attribute_xref SET productid = '" . $productid . "', attribute_id='". $attr_id ."', attribute_name='" . $attr_name . "'";
}
}
But, the result is a little different as of I would have expected. Every time a box is checked and its text input is typed, their values are sent to two different DB rows:
productid -- attribute_id -- attribute_name
10 -- 102 -- empty
10 -- 0 -- somename
On the above second row the attribute_id has zero value for not being checked.
I cannot get the whole picture where is my mistake.
Finally. The tricky answer was to add an identical numerical index to the associative inputs like this:
<form action="" method="post" enctype="multipart/form-data" id="form">
<?php foreach($attributes as $attribute){ ?>
<input type="checkbox" name="attribute[i][attr_id]" value="<?php echo $attribute['attribute_id']; ?>">
<input type="text" name="attribute[i][attr_name]"> value="<?php echo $attribute['attribute_name']; ?>">
<?php } ?>
</form>
where "i" in my case would take the variable number from 'attribute_id':
<input type="checkbox" name="attribute[<?php echo $attribute['attribute_id']; ?>][attr_id]" value="<?php echo $attribute['attribute_id']; ?>">
<input type="text" name="attribute[<?php echo $attribute['attribute_id']; ?>][attr_name]"> value="<?php echo $attribute['attribute_name']; ?>">
Hopefully my answer would help somebody in the future, too.
I am having the hardest time figuring out something that I think should be simple. I need to update multiple rows in my database with one submit button. I have it working with a submit for each row now, but I need to combine it. Here's what I'm trying. Where have I gone wrong? (I've been going off of multiple tutorials I found online and I think I have things all mixed up).
Here's the form:
<?php foreach ($teams as $team):
$id[]=$team['id'];?>
<form action="?update" method="post">
<div class="team-box">
<h2><?php echo $team['name'] ?></h2>
<label for="name">Name:</label>
<input type="text" name="name" value="<?php echo $team['name'] ?>" />
<label for="name">Match Wins:</label>
<input type="text" name="mwins" value="<?php echo $team['mwins'] ?>" />
<label for="name">Match Losses:</label>
<input type="text" name="mlosses" value="<?php echo $team['mlosses'] ?>" />
<label for="name">Match Ties:</label>
<input type="text" name="mties" value="<?php echo $team['mties'] ?>" />
<label for="name">Game Wins:</label>
<input type="text" name="gwins" value="<?php echo $team['gwins'] ?>" />
<label for="name">Game Losses:</label>
<input type="text" name="glosses" value="<?php echo $team['glosses'] ?>" />
<input type="hidden" name="id" value="<?php echo $team['id'] ?>" />
</div>
Here's the PHP to handle the UPDATE:
try
{
foreach($_POST['id'] as $id) {
$sql = 'UPDATE teams SET
name = "' . $_POST['name'.$id] . '",
mwins = "' . $_POST['mwins'.$id] . '",
mlosses = "' . $_POST['mlosses'.$id] . '",
mties = "' . $_POST['mties'.$id] . '",
gwins = "' . $_POST['gwins'.$id] . '",
glosses = "' . $_POST['glosses'.$id] . '"
WHERE id = "' . $_POST['id'.$id] . '"';
$pdo->exec($sql);
}
}
catch (PDOException $e)
{
$error = 'Error adding submitted team: ' . $e->getMessage();
include 'error.html.php';
exit();
}
header('Location: .');
exit();
Thanks in advance!
There are a couple of things that need fixing.
The FORM must be outside the foreach.
The '...name="name" value="...', to agree with the _POST code, should read instead:
... name="name" value="...
This way, a single POST will submit, say,
name123="Rangers"
mwins174="123"
Then you need all IDs. You can do that by issuing, in the foreach, this:
<input type="hidden" name="id[]" value="<?php print $team['id']; ?>" />
This will result in HTML:
<input type="hidden" name="id[]" value="123" />
...
<input type="hidden" name="id[]" value="456" />
and in $_POST['id'] being an array containing 123, 456 and so on.
You could also put in HTML:
<input type="text" name="name[<?php print $team['id']; ?>]" value="...
so that $_POST['name'] would be a vector with the same keys as the values of id, and therefore:
foreach($id as $team_id)
{
// Pseudocode
UPDATE... SET name=$name[$team_id]... WHERE id = $team_id;
}
This way you have one SUBMIT, and multiple UPDATEs.
Since all your field names change for each UPDATE query, you will need to execute separate queries as you already do. I don't think you would be able to perform a single UPDATE query.
I don't understand, what's wrong with executing several update queries?
I have a list
Each row has a common input field "sort_order" that's stored in MySQL db.
<input name="sort_order" type="text" value="<?php echo $cat['sort_order']; ?>" size="3" />
I want to be able to change the sort order inline, without going into the edit form.
How do I get all the values into the database. I think I need to loop through each row adding the sort_order[row_id] and value to an array. But I am stuck on how to achieve this.
all the values are posting according to firePHP. sort_order[50] 1, sort_order[51] 2 etc.
New Attempt at explaining:
I have a list view with 2 input fields.
<input name="cat_id" type="hidden" value="<?php echo $cat['cat_id']; ?>" />
<input name="sort_order" type="text" value="<?php echo $cat['sort_order']; ?>" size="3" />
I have a function that's called on post in the controller:
public function sortOrderUpdate(){
//collect the values of cat_id and sort_order from each input into a array
//$this->request->post['sort_order']
//$this->request->post['cat_id']
//send to the model
$this->model_cat->updateCatSortOrder($sortorderarray);
}
And the database model file function:
public function updateCatSortOrder($sortorderarray){
foreach((int)$sortorderarray as $sort){
$this->db->query("UPDATE cat SET sort_order='" . (int)$sort['sort_order'] . "' WHERE cat_id = '" . (int)$sort['cat_id'] . "'");
}
}
Whats the best way to achieve this?
Just use empty square brackets:
<input type="text" name="sort_order[]" value"<?php echo $sort_order; ?>" />
You can then access the input as an array, saving you from building it yourself. It'll be stored as $_POST['sort_order'] (or $_GET, depending on the method attribute specified in your <form> tag).
On a related note, you should probably escape $sort_order when echoing it:
<input type="text" name="sort_order[]" value"<?php echo htmlspecialchars($sort_order); ?>" />
i would not recommend using [ ] in html names.
<input type="text" name="sort_order_<?php echo $row_id; ?>" value"<?php echo $sort_order; ?>" />
say, you have 50 input fields, when posted, you can build an array this way:
$sortorder = array();
for($i=0; $i<50; $i++){
$sortorder[] = $_REQUEST['sort_order_' . $i];
}
Ok this seems to work:
<input name="cat_id[]" type="hidden" value="<?php echo $cat['cat_id']; ?>" />
<input name="sort_order[]" type="text" value="<?php echo $cat['sort_order']; ?>" size="3" />
Controller:
public function updateCatSortOrder(){
$sortvals = $this->request->post['sort_order']; //$this->request->post same as $_POST
$row = $this->request->post['cat_id'];
$n = count($this->request->post['cat_id']);
$sortorder = array();
for($i=0; $i<$n; $i++){
$sortorder[] = array(
'cat_id' => $row[$i],
'sort_order' => $sortvals[$i]
);
}
$this->model_cat->updateCatSortOrder($sortorder);
}
Model:
//UPDATE CAT SORT ORDER
public function updateCatSortOrder($sortorder){
foreach($sortorder as $sort){
$this->db->query("UPDATE cat SET sort_order='" . $this->db->escape($sort['sort_order']) . "' WHERE cat_id = '" . $this->db->escape($sort['cat_id']). "'");
}
}