I have an html form with dynamic (user-determined) number of rows, each with several inputs; I'm trying to achieve a MySQL query which will insert rows
into the db table, more or less row-for-row (although there is a value $_POSTing from outside this table which I will also add to the INSERT).
I'm retrieving these values like this:
<?php
if (isset($_POST['submit'])) {
$lineItems = array();
foreach ($_POST['date'] as $i => $value) {
$customer = $_POST['customer'][$i]; // this value is from *outside* the line items table
$date = $_POST['date'][$i];
$time = $_POST['time'][$i];
$fee = $_POST['fee'][$i];
$lineItems[] = "('$customer', '$date', '$time', '$fee')";
// I realize the query should be outside the loop, but what I'm trying to do is something like this (pseudo-code):
$query = "INSERT INTO Line_Items (CUSTOMER, DATE, TIME, FEE) VALUES ". implode(", ", $lineItems)
. "ON DUPLICATE KEY UPDATE
CUSTOMER = VALUES(CUSTOMER),
DATE = VALUES(DATE),
TIME = VALUES(TIME),
FEE = VALUES(FEE)
";
}
}
?>
With this query - inside or outside the loop - I'm only inserting values from the last row of inputs; can someone please explain with an example how
to construct a query to insert multiple line items and the appropriate query? Thank you so much.
Inside the loop you will get a row for each line in the post - outside the loop you will only insert the last row.
If you just need the last row - then there is no need to loop over the entire set to get to it.
You could count the rows - and then target the last row directly - see php
count()
Change line
$lineItems[] = "('$customer', '$date', '$time', '$fee')";
to
$lineItems[] = "(".$customer.",".$date.",".$time.",".$fee.")";
Related
I have a Table where user can create row with adding input fields dynamically (combination with jquery). I'm successfully able to insert it into the mysql database.
If users want to edit the added already existing fields, I have an edit page where the values are fetched from the mysql DB and populated again into the dynamically creatable table.
Now there are the below probabilities:-
User only makes minor changes on the existing values. In that case
the table has to be UPDATED with the changed values
User Deletes one/multiple row(randomly selected and as per users wish). So when form submitted the php query should only DELETE that perticular row/s in the DB.
User ADDS another row to the previous existing row values, in that case the php query should UPDATE the previous values and INSERT the newly added row values.
The above sequence is not necessarilly restricted the same order. User can perform all the above three function simultaneously at the same time.
Now my problem is(only for the backend) I'm finding a hard time to frame a php & sql query so as to update to the mysql.
my php
if(isset($_POST['submit'])){
$number1 = count($_POST['item']); //
for($i=0; $i<$number1; $i++){
$item = strip_tags(trim($_POST['item'][$i]));
$description = strip_tags(trim($_POST['description'][$i]));
$unitcost = strip_tags(trim($_POST['unitcost'][$i]));
$qty = strip_tags(trim($_POST['qty'][$i])); // Quantity
$sno = strip_tags(trim($_POST['sno'][$i]));// serial number
//QUERY1 if minor updates to above variable then UPDATE (eg, qty value is changed from 3 to 4)
//QUERY2 if row is deleted then DELETE that particular row from db (eg, sno 3 deleted from the table should DELETE corresponding mysql DB values also)
//QUERY3 if row is added then that particular row values should be INSERT (eg, sno 4 is added which is not in the mysql db. So this has to be INSERTED.)
}
}
Pardon me to have asked such question. I'm wasting a whole lot of time with the above queries unable to execute properly. I only require an idea not necessarily the whole code.
Hope all of you out there would advice me some ideas on how this could be implemented. Thanks for the help in advance. Expecting a positive reply.
NB: Just to remind you again, The front end is a Dynamically ADD/DELETE Input Field table
This sounds like a frontend problem. You need to define how you tell the backend whats happening.
<input name="items[$i][name]" />
This will show up as nice array to loop through in php.
foreach($_POST[items] AS $item){
if( $item['delete'] ){
//delete code
}
}else{
//Insert/Update
}
If you want to delete something simply make the field hidden and add a flag to it.
<input type="hidden" name="items[$i][delete]" value="1" />
<input type="hidden" name="items[$i][id]" />
Thank for the reply, appreciate #ckrudelux and #codefather for their intention to help me.
Although their advise didn't help me to structure my query. So I had a long workaround and found out below solution. I'm posting the solution because I couldn't find any article online when it comes to UPDATE/DELETE a dynamically generated input table.
Hope this would be of help to someone.
So what I did basically is that I took all the values into array.
In my dynamically generated add input table code, I added an <input type="hidden" name="sno[]" value="newrow">. So this will be clubbed with the form post. I'm using the normal html post and not ajax.
now my submit.php has ben changed to below
if(isset($_POST['submit'])){
$productid = $_POST['productd'];// No striptag functions
// due to illustration purpose
// First of all, we need to fetch the querying db table.
// This is required in order to compare the existing row values
// with the posted values
$fetchproduct = $link->prepare("SELECT * FROM product WHERE productid=?");
$fetchproduct ->bind_param('s',$productid);
$fetchproduct ->execute();
$fetchresult = $fetchproduct ->get_result();
$serialnumber=array(); // Assigning array to fetch the primary key: Serial Number
while($row = $fetchresult->fetch_assoc()){
$serialnumber[] = $row["sno"];
}
//Newly Inserted Values
//$_POST['sno'] is taken from the dynamic input field defined earlier in this post.
//Basically what we are doing here is we are comparing (the values
//which have been posted from the primary page) and (values present in the db table).
//The difference will give an array of newly inserted table input field values
$insert = array_diff($_POST['sno'],$serialnumber);
//Deleted Values
// This will Difference those values in the db table and values which are
// deleted from the primary dynamic table page
$delete = array_diff($serialnumber,$_POST['sno']);
$countdelete = count($delete); // Counting how many values have been
// lined up for deleting
//Updated Values
// array_intersect will give us the common values present in both the array.
// This means that there is no deletion or insertion to the dynamic table fields.
$intersect = array_intersect($serialnumber, $_POST['sno']);
$update = array_values($intersect);
$countupdate = count($update);
//INSERT ADDED VALUES TO DB
foreach($insert as $key=>$ivalue){
// ID
if(isset($_POST['id'][$key]) && !empty($_POST['id'][$key])) {
$id = strip_tags(trim($_POST['id'][$key]));
}
// ITEM
if(isset($_POST['item'][$key]) && !empty($_POST['item'][$key])) {
$item = strip_tags(trim($_POST['item'][$key]));
}
// DESCRIPTION
if(isset($_POST['description'][$key]) && !empty($_POST['description'][$key])) {
$description = strip_tags(trim($_POST['description'][$key]));
}
// UNITCOST
if(isset($_POST['unitcost'][$key]) && !empty($_POST['unitcost'][$key])) {
$unitcost = strip_tags(trim($_POST['unitcost'][$key]));
}
// QUANTITY
if(isset($_POST['qty'][$key]) && !empty($_POST['qty'][$key])) {
$qty = strip_tags(trim($_POST['qty'][$key]));
}
// AMOUNT
if(isset($_POST['amount'][$key]) && !empty($_POST['amount'][$key])) {
$amount = strip_tags(trim($_POST['amount'][$key]));
}
// INSERT INTO THE DATABASE
$inserttable = $link->prepare("INSERT INTO product (productid, item, description, unitcost, qty, amount) VALUES(?,?,?,?,?,?)");
$inserttable->bind_param('ssssss', $id, $item, $description, $unitcost, $qty, $amount);
$inserttable->execute();
if($inserttable){
header( 'Location:to/your/redirect page.php' ) ; // NOT MANDADTORY, You can put whatever you want
$_SESSION['updatemsg'] = "Success";
}
}
//UPDATE EXISTING VALUES TO DB
for($j=0; $j<$countupdate; $j++){
// ID
if(isset($_POST['id'][$j]) && !empty($_POST['id'][$j])) {
$uid = strip_tags(trim($_POST['id'][$j]));
}
// ITEM
if(isset($_POST['item'][$j]) && !empty($_POST['item'][$j])) {
$uitem = strip_tags(trim($_POST['item'][$j]));
}
// DESCRIPTION
if(isset($_POST['description'][$j]) && !empty($_POST['description'][$j])) {
$udescription = strip_tags(trim($_POST['description'][$j]));
}
// UNITCOST
if(isset($_POST['unitcost'][$j]) && !empty($_POST['unitcost'][$j])) {
$uunitcost = strip_tags(trim($_POST['unitcost'][$j]));
}
// QUANTITY
if(isset($_POST['qty'][$j]) && !empty($_POST['qty'][$j])) {
$uqty = strip_tags(trim($_POST['qty'][$j]));
}
// AMOUNT
if(isset($_POST['amount'][$j]) && !empty($_POST['amount'][$j])) {
$uamount = strip_tags(trim($_POST['amount'][$j]));
}
// UPDATE THE DATABASE
$updatetable = $link->prepare("UPDATE product SET item=?, description=?, unitcost=?, qty=?, amount=? WHERE sno=?");
$updatetable->bind_param('ssssss', $uitem, $udescription, $uunitcost, $uqty, $uamount, $update[$j]);
$updatetable->execute();
if($updatetable){
$_SESSION['updatemsg'] = "Success";
}
}
//DELETE VALUES FROM DB
foreach($delete as $sno){
$deletetable = $link->prepare("DELETE FROM product WHERE sno=?");
$deletetable->bind_param('s', $sno);
$deletetable->execute();
if($deletetable){
$_SESSION['updatemsg'] = "Success";
}
}
}else {
$_SESSION['updatemsg'] = "Error";
}
}
I have researched several related question in this forum and google, Kindly assist . I am trying to insert some values into database from several arrays stored in session. I also have some single values stored in some session also which i want to insert into multiple rows of dbase table.
//First, I recall the values stored in sessions from previous pages into the current page as below.
//take note of the comment in front of the sessions and All array contains the same number of values except for the first two sessions.
$ticketid="t".date('dmyHis').mt_rand (1000,9999);
$bettime= date('d/m/y H:i');
$_SESSION['bettime']=$bettime;//Not array, contains single value
$_SESSION['ticketid']=$ticketid;//Not array, Contains single value
$_SESSION['gamecode'];//array
$_SESSION['starttime'];//array
$_SESSION['optioncode']//array
$_SESSION['home'];//array
$_SESSION['away'];//array
$_SESSION['odd'];//array
Here, I connected to dbase. //Works fine.
require('gumodb.php');
Here i try to start a loop using one array session as key
foreach($_SESSION['starttime'] as $ro => $col){
mysql_query("INSERT INTO reg_bet (bettime, ticketid,matchcode,starttime,home,away,optionodd,optioncode) VALUES('$_SESSION[bettime]','$_SESSION[ticketid]','$_SESSION[gamecode]', '$_SESSION[starttime]','$_SESSION[home]','$_SESSION[away]','$_SESSION[odd]','$_SESSION[optioncode]' ) ")
or die(mysql_error());
}
It returns Notice: Array to string conversion in C:\xampp\htdocs\gumo\consel.php on line 61
EDIT QUESTION
I am trying to achieve something like this.
foreach($_SESSION['gamecode'] as $gc => $gcvalue && $_SESSION['starttime'] as $st =>$stvalue && $_SESSION['optioncode'] as $oc => $ocvalue ){
mysql_query("INSERT INTO reg_bet (matchcode,starttime,optioncode) VALUES('$gcvalue','$stvalue','$ocvalue') ")
or die(mysql_error()); }
$x = json_encode($_SESSION);
$query = "INSERT INTO ".$TABLE_NAME data "VALUES ("$x");";
$mysqli->query( $query );
Encode the session array into a single string and insert in to the table on a row of data.
When you fetch the same data use json_decode to convert the string into array.
Assuming the arrays in the $_SESSION variable are numeric, you could try something like this:
for ($i = 0; $i < $max_index_count; $i++) {
$query = "INSERT INTO ".$TABLE_NAME;
$query += "VALUES (".$_SESSION['index'][$i].");";
$mysqli->query( $query );
}
The above is pseudo code, but the problem is you are trying to use an array as a string. The $_SESSION variable is a multidemsional array, therefore, specify two ibdexes.
After so many trials, i was able to get it done with this
$ticketid="t".date('dmyHis').mt_rand (1000,9999);//ticket id generateed
$bettime= date('d/m/y H:i');
$_SESSION['bettime']=$bettime;
$_SESSION['ticketid']=$ticketid;
$_SESSION['gamecode'];
$_SESSION['starttime'];
$_SESSION['optioncode'];
$_SESSION['home'];
$_SESSION['away'];
$_SESSION['odd'];
require('gumodb.php');
foreach ($_SESSION['gamecode'] as $index => $value)
{
$ge = $_SESSION['gamecode'][$index];
$se = $_SESSION['starttime'][$index];
$oe = $_SESSION['optioncode'][$index];
$he = $_SESSION['home'][$index];
$ay = $_SESSION['away'][$index];
$od = $_SESSION['odd'][$index];
This post the arrays and non array into table row and display
mysql_query("INSERT INTO reg_bet (matchcode,ticketid,bettime,starttime,home,away,optionodd,optioncode) VALUES('$ge','$ticketid','$bettime','$se','$he' ,'$ay','$od' ,'$oe' ) ")
or die(mysql_error());
echo $_SESSION['gamecode'][$index] .'-'. $_SESSION['starttime'][$index].'- '. $_SESSION['optioncode'][$index].' -'. $_SESSION['home'][$index].'- '. $_SESSION['away'][$index].'- '. $_SESSION['odd'][$index].$bettime.' -' .$ticketid.'</br>' ;
}
Thanks for your contributions.
I am pretty new to PHP, but have tried searching for other questions similar to mine and been unable to find anything that is close enough to my situation to help me solve this.
I am trying to code a web page that allows users to select as many or as few items as they would like to order. The item values are identical to their Primary Key in the Item table.
Once submitted, each different item value should be input into the same row of a database table based on the date{pk}. Within that row, there are numerous columns: Item1ID, Item2ID, Item3ID, etc.
So far, the value of each item selected is assigned to a new array. However, I cannot simply input the array values into a column -- I need each array index to be placed into a sequential column. The code is below:
$date = new DateTime();
$td = $date->format('Y-m-d');
$x = 1;
$checkedItems = $_POST['Item'];
$count = count($checkedItems);
echo $count;
$foodID = "Item".$x."ID";
While($x<=$count){
if(isset($_POST['Item'])){
if (is_array($_POST['Item'])) {
foreach($_POST['Item'] as $values){
$selectedFoods = substr($values,0,4);
$addFoodOrderQuery= sprintf("UPDATE WeeklyBasketFoodOrder SET '%s' = %s WHERE `foodOrderDate` = '%s'",
$foodID, $selectedFoods, $td);
$result= mysqli_query($db, $addFoodOrderQuery);
}
}
} else {
$values = $_POST['Item'];
echo "You have not selected any items to order.";
}
$x++;
}
If you need any further clarification, please let me know. After submitting the code, the database item#ID tables are different, but they are now empty instead of "NULL."
I have a group chat feature on my site and people can add friends by selecting HTML checkboxes, so multiple can be added at one point. However, when my PHP script inserts the data into the MySQL database, only the last value is added. For example, if the user selects 3 friends, PHP separates their ID's by commas (as it will be stored as an array in the database); so it would display like ,1,2,3. However, when I insert into MySQL, only the ",3" is submitting.
PHP code to assemble data from HTML checkbox:
$invite = $_POST['invite'];
if(empty($invite))
{
//echo("You didn't select any friends.");
}
else
{
$N = count($invite);
//echo("You selected $N friends(s): ");
for($i=0; $i < $N; $i++)
{
$userinput = ("," . $invite[$i]);
}
}
MySQL query:
$sql = "INSERT INTO group_chat (title, created_date, last_modified, created_by, user_array) VALUES ('$title', now(), now(), '$logOptions_id', '$logOptions_id$userinput')";
$logOptions_id contains the ID of the current user.
I've echoed the $userinput variable out before and it appears as it should be: ,1,2,3 (comma at the start seperates from current user ID when adding to MySQL.
You are overwriting the values in the loop with this line
$userinput = ("," . $invite[$i]);
Change it to this
$userinput .= ("," . $invite[$i]);
Remember to initialize the the variable $userinput before appending to it to avoid undefined variable warning.
you can create the comma separated id string using implode
$userinput = implode(',', $invite); // output as 1,2,3
If you want to add current user id to it
$userinput = $logOptions_id.','.implode(',', $invite);
I think I've got a tiny mistake in my code so when I try to add two records to MySQL database it adds them both, but at the moment its only adding the second row that should be inputted. SO for example I have two RefTitle fields, two RefSurname fields and so on!
Some PHP Code:
<?php
if(empty($err)) {
for($i = 0; $i < 2; $i++)
{
$RefTitle = $_POST['RefTitle'][$i];
$RefSurname = $_POST['RefSurname'][$i];
$RefForenames = $_POST['RefForenames'][$i];
$RefInstitute = $_POST['RefInstitute'][$i];
$RefEmail = $_POST['RefEmail'][$i];
$RefTelephone = $_POST['RefTelephone'][$i];
$EmailOK = $_POST['EmailOK'][$i];
$sql_insert = "INSERT into `referees`
(`RefTitle`,`RefSurname`,`RefForenames`,`RefInstitute`, `RefEmail`,
`RefTelephone`,`EmailOK`)
VALUES
('$RefTitle','$RefSurname','$RefForenames','$RefInstitute','$RefEmail',
'$RefTelephone','$EmailOK'
)
"; ?>
I have the [] after each name field in my html form.
Thanks
Here's what I think is happening.
In the loop, you're adding the current query to a string, overwriting the previous query. After the loop ends, you run mysql_query but this will only run on the last query generated by the loop.
You have two ways to fix this:
Execute the query within the loop on every iteration. Pseudo code:
for ($i = 1 to 100)
{
$query = //build your query;
mysql_query($query);
}
Alternatively, (and the better way) is to use a value list in your insert statement.
An insert with a list of values looks like this
INSERT INTO table VALUES (1,2,3), (4,5,6), (7,8,9)
So, (pseudo code again)
$query = "INSERT INTO table VALUES ";
for ($i = 1 to 100)
{
$query .= " (";
$query .= "" //comma seperate the values of the current iteration
$query .= "),";
}
//after loop ends, remove the trailing extraneous comma
// execute the entire query at once
mysql_query($query);