how to insert multuple row to mysql database - php

i have a upload result form for a certain semester. where i have collected all the subjects and student list for a certain semester.but my problem is i can't insert the result to the database.only a single row is inserted,
controller
$data=array();
for($i=0;$i<count($_POST['Number']);$i++){
if($_POST['Number'][$i] != ''){
$data=array(
'Id'=>$_POST['id'][$i],
'Dept'=>$_POST['Dept'][$i],
'SubjectCode'=>$_POST['sCode'][$i],
'SubjectName'=>$_POST['sName'][$i],
'Semister'=>$_POST['Semister'][$i],
'MidNumber'=>$_POST['Number'][$i]
);
$this->load->model('Upload_Result_model');
$this->Upload_Result_model->upload_midResult($data);
}
}
form:
<table>
<tr>
<th>Student ID</th>
<?php foreach($subjects as $s):?>
<th><?php echo $s->subjectName; echo "<br>"; echo "(".$s->subjectCode.")"; ?></th>
<?php foreach($student as $st):?>
<input type='hidden' id='id[]' name='id[]' value='<?php echo $st->Id;?>'>
<?php endforeach;?>
<input type='hidden' name='Dept[]' id='Dept[]' value=<?php echo $Dept;?>>
<input type='hidden' name='Semister[]' id='Semister[]' value=<?php echo $Semister;?>>
<input type='hidden' id='sCode[]' name='sCode[]' value='<?php echo $s->subjectCode?>'>
<input type='hidden' id='sName[]' name='sName[]' value='<?php echo $s->subjectName?>'>
<?php endforeach;?>
</tr>
<?php foreach($student as $st):?>
<tr>
<td><?php echo $st->Id?></td>
<?php for($i=0;$i<count($subjects);$i++):?>
<td><input type='text' size='7' id='Number[]' name='Number[]'/></td>
<?php endfor;?>
</tr>
it will be very much helpful for me if anyone fix this problem

i dont think the html form elements will come in as arrays in php. try doing print_r($_POST); to see the passed variables and their values. they might come in just comma separates.
i think you might need to do something like $_POST['id']=explode(',',$_POST['id']); and so on to fix your problem
the Numbers variable also has other problems you should look in to

i think
foreach($student as $st):
should be after the . Now you open multiple rows, but not closing them. Also Ids are inside 2 for loops, so they are more than the other elements, I am not sure if this is what you try to do.
So, if this is ok you can try:
$Numbers = #$_POST['Number'];
$ids = #$_POST['id'];
foreach($Numbers as $a => $b)
{
if($Numbers[$a]!='')
{
$data=array(
'Id'=>$ids[$a];, ... }
}
}

Related

PHP post of td content inside a for

I just need to send a line of a table in my PHP page after click on button.
This is my code :
$login = $_POST['login'];
$requete = Connexion::query("SELECT id
FROM session
WHERE login='$login'");
$requete = $requete[0][0];
$application = Connexion::query("SELECT titre,cleAk,cleAs,cleCk
FROM cles
WHERE sessionId='$requete'");
echo "<form class='login-form' method='POST'><table class='table'><th>Titre</th><th>Cle ak</th><th>Cle as</th><th>Cle ck</th><tr>";
for($i=0;$i<sizeof($application);$i++)
{
for($j=0;$j<4;$j++)
{
echo "<td><input type='hidden' name='titre' value='".$application[$i][$j]."'>".$application[$i][$j]."</td>";
}
echo "<td><button type='submit' name='api'>Submit</button></td></tr></form>";
}
And this var_dump($_POST['titre']); return the last cell of the last line.
Can you help me ?
As was briefly mentioned in the comments of a previous answer, if you only want to submit the contents of one line, then you will need a separate <form> on every line (table row). You were trying this with a closing </form> inside the loop, but you opened it outside the loop resulting in invalid HTML with lots of closing </form> tags but only one opening <form> tag.
Another problem with your form inputs is that they were all named the same after the first column name='titre' but you had specified each column separately in the table header. To fix this, others offered an imprecise option by creating an array name='titre[]', but I think it's better to dynamically name the inputs to match the column key.
I don't know what database API you're using, but it appears to only produce a numeric multidimensional array without associative keys. There's probably a class method to get the column names, or you can manually assign it based on your SQL query as I have done with the array $cols
<?php
// debugging to show you everything posted
print_r($_POST);
// generate some random data for example
$application[0][0] = "first titre";
$application[0][1] = "first cleAk";
$application[0][2] = "first cleAs";
$application[0][3] = "first cleCk";
$application[1][0] = "second titre";
$application[1][1] = "second cleAk";
$application[1][2] = "second cleAs";
$application[1][3] = "second cleCk";
$application[2][0] = "third titre";
$application[2][1] = "third cleAk";
$application[2][2] = "third cleAs";
$application[2][3] = "third cleCk";
// get the columns for input names
$cols = array('titre','cleAk','cleAs','cleCk');
// semantically complete HTML table
echo "
<table class='table'>
<thead>
<tr><th>Titre</th><th>Cle ak</th><th>Cle as</th><th>Cle ck</th><th>Submit</th></tr>
</thead>
<tbody>
";
for($i=0;$i<sizeof($application);$i++)
{
echo "
<tr>
<form class='login-form' method='POST'>";
for($j=0;$j<sizeof($cols);$j++)
{
echo "
<td><input type='hidden' name='".$cols[$j]."' value='".$application[$i][$j]."'>".$application[$i][$j]."</td>";
}
echo "
<td><button type='submit' name='api'>Submit</button></td>
</form>
</tr>\n";
}
echo "
</tbody>
</table>
";
Results in this rendered output when I click on the first row's submit button. Note that you can't post data in the snippet below, this is purely for static HTML demonstration purposes.
Array
(
[titre] => first titre
[cleAk] => first cleAk
[cleAs] => first cleAs
[cleCk] => first cleCk
[api] =>
)
<table class='table'>
<thead>
<tr><th>Titre</th><th>Cle ak</th><th>Cle as</th><th>Cle ck</th><th>Submit</th></tr>
</thead>
<tbody>
<tr>
<form class='login-form' method='POST'>
<td><input type='hidden' name='titre' value='first titre'>first titre</td>
<td><input type='hidden' name='cleAk' value='first cleAk'>first cleAk</td>
<td><input type='hidden' name='cleAs' value='first cleAs'>first cleAs</td>
<td><input type='hidden' name='cleCk' value='first cleCk'>first cleCk</td>
<td><button type='submit' name='api'>Submit</button></td>
</form>
</tr>
<tr>
<form class='login-form' method='POST'>
<td><input type='hidden' name='titre' value='second titre'>second titre</td>
<td><input type='hidden' name='cleAk' value='second cleAk'>second cleAk</td>
<td><input type='hidden' name='cleAs' value='second cleAs'>second cleAs</td>
<td><input type='hidden' name='cleCk' value='second cleCk'>second cleCk</td>
<td><button type='submit' name='api'>Submit</button></td>
</form>
</tr>
<tr>
<form class='login-form' method='POST'>
<td><input type='hidden' name='titre' value='third titre'>third titre</td>
<td><input type='hidden' name='cleAk' value='third cleAk'>third cleAk</td>
<td><input type='hidden' name='cleAs' value='third cleAs'>third cleAs</td>
<td><input type='hidden' name='cleCk' value='third cleCk'>third cleCk</td>
<td><button type='submit' name='api'>Submit</button></td>
</form>
</tr>
</tbody>
</table>
You should pass an array to handle the multiple elements with the inputs. In Your code it should be look like this:
for($j=0;$j<4;$j++)
{
echo "<td><input type='hidden' name='titre[$j]' value='".$application[$i][$j]."'>".$application[$i][$j]."</td>";
echo "<td><button type='submit' name='api'>Submit</button></td></tr></form>";
}
The modification is name='titre[]'. Hope this will help you

html dynamic form, pass multiple values through post and insert mysql

i have this database
and this form, dynamically generated from the database
<table border="1" cellspacing="0" cellpadding="6">
<tr bgcolor="#CCCCCC">
<td><strong>product id</strong></td>
<td><strong>product name</strong></td>
<td><strong>product price</strong></td>
<td><strong>quantity</strong></td>
</tr>
<form method="post" action="insert.php">
<?php
$query = $dbh->query('SELECT * FROM products');
$results = $query->fetchAll(PDO::FETCH_ASSOC);
foreach ($results as $row)
{
?>
<tr>
<td><?php echo $row['product_id']; ?></td>
<td><?php echo $row['product_name']; ?></td>
<td><?php echo $row['product_price']; ?></td>
<td><input name="quantity" type="text" value="0"></td>
</tr>
</form>
<?php } ?>
</table>
<br>
<input type="submit" value="Add Records">
the quantity in the form is a textbox so i can modify it.
I would like to enter the quantities and the pressing the button to insert the values in the order_products table (including the quantity).
1) How can i pass ALL the quantities and product_id (and the rest) to the next page through post? (until now i know how to pass single values)
2) is there a better way to achieve it?
3) the insert statements should be in the same page or the page where i get the post vars?
db scheme
http://i.stack.imgur.com/oqdOy.jpg
thanks
Rob
1) First, you have to wrap your <input>s inside a single form (move your </form> tag after your <input type="submit" value="Add Records">, the way you have it now closes the <form> tag at first iteration) and submit it via HTTP POST method. Then, based on your schema, the only field you'll have to insert aside of quantity is product_id, which value you can assign inside a hidden field, like:
<?php
echo "<input type='hidden' name='pid_$row['product_id']' value='$row['product_id']'>";
echo $row['product_id'];
?>
Notice that you can still echo the value itself for viewing purposes. You also have to generate your quantity <input> field name property dynamically, otherwise $_POST will overwrite values when their keys are the same.
<?php
echo "<input type='text' name='pid-qtd_$row['product_id']'>";
?>
2) It depends on your development priorities. There are some frameworks out there that might simplify your process. I'd recommend you to keep all your DB queries and connection data within a DB helper class and require it wherever you need it.
3) Since you're using PDO, I assume you have an OOP design, which implies in doing that at your DB helper class or such. The page receiving the HTTP request must require your helper and deal with the $_POST parsing to parameters to its query methods. Don't forget to prepare your statements and parameterizing your queries.
Using hidden element you can post your data to second page. Using counter variable you can add dynamic form element and post it into second page.
<form method="post" action="test2.php">
<table border="1" cellspacing="0" cellpadding="6">
<tr bgcolor="#CCCCCC">
<td><strong>product id</strong></td>
<td><strong>product name</strong></td>
<td><strong>product price</strong></td>
<td><strong>quantity</strong></td>
</tr>
<?php
$query = $con->query('SELECT * FROM product'); //your query goes here
$results = $query->fetchAll(PDO::FETCH_ASSOC);
$i=0; //counter variable
foreach ($results as $row)
{
?>
<tr>
<td>
<?php echo $row['prod_id']; ?>
<input type="hidden" name="prod_id<?php echo $i; ?>" value="<?php echo $row['prod_id']; ?>" />
</td>
<td>
<?php echo $row['prodname']; ?>
<input type="hidden" name="name<?php echo $i; ?>" value="<?php echo $row['prodname']; ?>" />
</td>
<td>
<?php echo $row['price']; ?>
<input type="hidden" name="price<?php echo $i; ?>" value="<?php echo $row['price']; ?>" />
</td>
<td><input name="quantity<?php echo $i; ?>" type="text" value="0"></td>
</tr>
<?php
$i++; //increment counter variable
}
?>
<input type="hidden" name="rows" id="rows" value="<?php echo $i; ?>" />
</table>
<br>
<input type="submit" value="Add Records">
</form>
Your insert page code goes here....
for($i=0;$i<=$_POST['rows'];$i++)
{
$prodid = $_POST['prod_id'.$i];
$pname = $_POST['name'.$i];
$pprice = $_POST['price'.$i];
$con ->exec("insert into product(prod_id,prodname,price)values('$prodid', '$pname','$pprice' )" );
}
I suggest putting the product_id in a hidden form element like this:
<tr>
<input type='hidden' name='product_id' value='<?php echo $row['product_id']; ?>'/>
<td><?php echo $row['product_id']; ?></td>
<td><?php echo $row['product_name']; ?></td>
<td><?php echo $row['product_price']; ?></td>
<td><input name="quantity" type="text" value="0"></td>
</tr>
This will send the product_id with your quantity and you can use it in your insert statement.
The only problem with this is if you have more than one row, there will be more than one hidden element for product_id, etc. Ways to overcome this include differentiating them by appending an incrementing number on the hidden element's name, e.g.:
$i = 1;
foreach ($results as $row)
{
$product_id_name = 'product_id_'.$i;
$quantity_name = 'quantity_'.$i;
... echo your table row, using $product_id_name in the hidden element, and $quantity_name in your text input
$i++;
}
Then in your inserting code you have to look for all the items in $_POST whose keys start with "quantity_", and if they are non-zero, get the integer NNN after the key prefix "quantity_", and get the corresponding product_id_NNN value to do your insert.

Multiple row insert to table if check box is selected

I am trying to insert multiple rows to a database table if check box is selected. But in my code when I am trying to insert, new rows are inserting based on check box selection. But no data is passing. I need some advice on below code to modify:
<?php
$db=mysql_connect("localhost","root","");
mysql_select_db("kkk",$db);
$qry="select * from pi";
$result=mysql_query($qry);
?>
<form action="check.php" method="post">
<table>
<tr>
<th>A</th>
<th>B</th>
<th>C</th>
</tr>
<?php
while($row=mysql_fetch_array($result))
{
echo "<tr><td><input type=checkbox name=name[] value='".$row['id']."'>".$row['PI_NO']."</td><td>".$row['CUSTOMER_NAME']."</td><td>".$row['PI_ADDRESS']."</td></tr>";
}
?>
<input type="submit" value="save" id="submit">
<?php
$db=mysql_connect("localhost","root","");
mysql_select_db("kkk",$db);
$name=$_POST['name'];
foreach($_POST['name'] as $x)
{
$qry="INSERT INTO pi (PI_NO, CUSTOMER_NAME, PI_ADDRESS)VALUES ('$PI_NO','$CUSTOMER_NAME','$PI_ADDRESS')";
mysql_query($qry);
}
?>
Notes:
You forgot to bind the name of your checkbox using a single tick (')
You used variables in your query which you didn't defined and assigned value with yet
You only passed on the value of name, and did not include the Pi Address and Customer name. I'll be passing them by hidden input using <input type="hidden">.
I'll change the way you check your passed on form by looping them and check them using for() and if()
Use mysql_real_escape_string() before using them in your queries to prevent some of the SQL injections. But better if you consider using mysqli prepared statement rather than the deprecated mysql_*.
Is your post a single file? If it is, you must enclose your query using an isset() to prevent error upon loading the page.
You didn't close your <form>
Here's your corrected while loop:
<?php
while($row=mysql_fetch_array($result))
{
?>
<tr>
<td>
<input type="checkbox" name="name[]" value="<?php echo $row['id']; ?>">
<?php echo $row["PI_NO"]; ?>
<!-- HERE IS THE START OF YOUR TWO HIDDEN INPUT -->
<input type="hidden" name="piaddress[]" value="<?php echo $row["PI_ADDRESS"]; ?>">
<input type="hidden" name="customer[]" value="<?php echo $row["CUSTOMER_NAME"]; ?>">
</td>
<td><?php echo $row['CUSTOMER_NAME']; ?></td>
<td><?php echo $row['PI_ADDRESS']; ?></td>
</tr>
<?php
} /* END OF WHILE LOOP */
?>
<input type="submit" value="save" id="submit">
</form> <!-- YOU DID NOT CLOSE YOUR FORM IN YOUR POST -->
And your query:
<?php
$db=mysql_connect("localhost","root","");
mysql_select_db("kkk",$db);
$counter = count($_POST["name"]); /* COUNT THE PASSED ON NAME */
for($x=0; $x<=$counter; $x++){
if(!empty($_POST["name"][$x])){
$PI_NO = mysql_real_escape_string($_POST["name"][$x]);
$CUSTOMER_NAME = mysql_real_escape_string($_POST["customer"][$x]);
$PI_ADDRESS = mysql_real_escape_string($_POST["piaddress"][$x]);
$qry="INSERT INTO pi (PI_NO, CUSTOMER_NAME, PI_ADDRESS) VALUES ('$PI_NO','$CUSTOMER_NAME','$PI_ADDRESS')";
mysql_query($qry);
} /* END OF CHECKING THE CHECKBOX IF SELECTED */
} /* END OF FOR LOOP */
?>
Lots of little problems. And some big ones.
as $x){ .. $x is not being used so I assume you just loop for the number of checked boxes.
These have no values: '$PI_NO','$CUSTOMER_NAME','$PI_ADDRESS'
Missing </form>
Not being used: $name=$_POST['name'];
<?php
echo '<form action="check.php" method="post"><table><tr><th>A</th><th>B</th><th>C</th></tr>';
$db=mysql_connect("localhost","root","");
mysql_select_db("kkk",$db);
$sql = "select `id`,`PI_NO`, `CUSTOMER_NAME` ,`PI_ADDRESS` from `pi`";
$result=mysql_query($sql);
while($row=mysql_fetch_array($result)){
echo "<tr><td><input type=\"checkbox\" name=\"name[]\" value=/"$row[0]/"'>$row[1]</td><td>$row[2]</td><td>$row[3]</td></tr>";
}
echo '<input type="submit" value="save" id="submit"></form>';
foreach($_POST['name'] as $x){
$sql="INSERT INTO pi (`PI_NO`, `CUSTOMER_NAME`, `PI_ADDRESS`)VALUES ('$PI_NO','$CUSTOMER_NAME','$PI_ADDRESS')";
mysql_query($sql);
}
?>

Delete From Table - Via Form

I have a HTML table that displays all my table entries. Also in the table is a delete button next to every SQL entry.
I want to be able to delete an entry the user selects. I've made the form to Post PHP_Self, and I'm passing in the index $i from the while loop as a reference:
$i = 0;
while($row = mysqli_fetch_array($result)){
?>
<tr>
<td>
<? echo $row['uniqueIdentifier']; ?>
</td>
<td>
<form action="<? echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type='hidden' name='remove_entrie_ID' value='<? echo $i; ?>' />
<input type='submit' value='Delete' name='remove_entrie'>
</form>
</td>
</tr>
<?
$i++;
}
So this is passed to itself, I now want to do a DELETE WHERE 'INDEX OF TABLE' == $i, type thing? I don't even know if this is possible.
if(isset($_POST['remove_entrie'])){
$index = $_POST['remove_entrie_ID']
echo "Index: " . $index;
//mysqli_query($con, "DELETE FROM Users WHERE INDEX = '$index'");
}
I'm basically using the $i to pick out the index of how the table was loaded, and then using that to pick out which row I want to delete. But I have a feeling this can't be done?
I basically want to delete a row the user has selected from the table.
You don't need $i variable. Just make simple modification in your list:
while($row = mysqli_fetch_array($result)){
?>
<tr>
<td>
<? echo $row['uniqueIdentifier']; ?>
</td>
<td>
<form action="" method="post">
<input type="hidden" name="remove_entrie_ID" value="<? echo $row['uniqueIdentifier']; ?>" />
<input type="submit" value="Delete" name="remove_entrie">
</form>
</td>
</tr>
<?
}
It is also good idea to escape specials chars etc in your post variable to avoid sql injection.

Keep checkboxes in array checked on form submit

I have a list of checkboxes created by a while loop but when the form is submitted the checkboxes are cleared. I have tried to use the unique id of the value in the record by putting it in a hidden field and then using it in an if query before marking the checkbox as checked but it does nothing
<?php
while($row = mysqli_fetch_array($result)){
$posted = $row['auditID'];
?>
<tr class="hover">
<td width="180"><? echo $row['auditName']; ?>
<input type="hidden" name="audit_id_confirm" value="<? echo $row['auditID'];?>">
</td>
<td width="33"><input type="checkbox" name="audit_selected[]"
value="<? echo $row['auditID'];?>"
<?php if($_POST['audit_id_confirm'] == $posted){ echo "checked"; }?>>
</td>
</tr>
<?php
}
?>
I sorted it by checking id=f the id number was in the arrays that had been posted.
<?php
$selected = $_POST['audit_selected'];
while($row = mysqli_fetch_array($result)){
$audit = $row['auditID'];
if(in_array($audit, $selected)) {
$check="checked='checked'";
}else{
$check = '';
} ?>
<tr class="hover">
<td width="180">
<?php echo $row['auditName'].' '.$num_audited; ?></td><td width="33"> <input type="checkbox" name="audit_selected[]" value="<?php echo $row['auditID'];?>" <?php echo $check; ?> >
</td>
</tr>
<?php }
?>
<?php if($_POST['audit_id_confirm'] == $posted){ echo "checked"; }?>>
Replace above line with this:
<?php if($_POST['audit_id_confirm'] == $posted){ echo "checked='checked'"; }?>>
You are not properly providing checked attribute to the Html entity.
One of the information you need to store in the table, is the state of the checkbox.
So, you can create a new column in your table, call it "checkboxstate".
Now inside your code use the following code to insert the checkbox:
<input type="checkbox" name="<?php echo($posted); ?>">
Thus far we have created several checkboxes whom names are the same as $posted, in other words each checkbox will have the name of its row's "$posted" value.
Now the only thing that is left is submitting the form and storing the checkbox info, which will return either TRUE or FALSE, and we will save that in our table, in the "checkboxstate" column.
So now in our table we will have a bunch of rows with several columns, one of the columns will be "checkboxstate" whom value will be either TRUE or FALSE.
At this point we have pretty much solved the problem, all that is left is to insert a simple if to either show a checked checkbox or an unchecked one.
<?php
while($row = mysqli_fetch_array($result)){
$posted = $row['auditID'];
$cbs = $row['checkboxstate'];
?>
<tr class="hover">
<td width="180"><? echo $row['auditName']; ?></td>
<td width="33">
<?php if($cbs == "true") echo "<input type='checkbox' name='$posted' checked='checked'>"; else echo "<input type='checkbox' name='$posted'>";
</td>
</tr>
<?php
}
?>

Categories