I have a table MySQL, contains 3 parameters:
(`ID_Article`, `Designiation`, `ID_LRU`)
I fill it by a data in Excel file from PHP it contains also the same parameters:
`(`ID_Article`, `Designiation`, `ID_LRU`)`
The parsing file is work fine. the field Designiation is the description of Articles and many Articles have the same description so the field Designiation is repeated many time in my Excel file.
The problem is when I fill my table MySQL it takes just one records. For example: I have the 2 records in my Excel file:
DIEDIVBIEN DIVERSBIEN Composant
DIEDIVBIEN DIVERSBIEN Composant
Here in my table SQL I find just one line:
DIEDIVBIEN DIVERSBIEN Composant
My request is:
if ($articleid == 'DIEPRESTATION' || $articleid == 'DIEDIVBIEN' || $articleid == 'DIEDIVERS' ){
if(!($this->_db->query("INSERT INTO `article` (`ID_Article`, `Designiation`, `ID_LRU`) VALUES ('".$articleid."', '".$designation."', '".$IdLRU."');")))
{
if ($LRU != 'new'){
return $this->_db->query(" UPDATE `FLOOSE`.`article` SET `ID_LRU` = '".$IdLRU."' WHERE `article`.`ID_Article` = '".$articleid."' AND `article`.`Designiation` = '".$designation."' LIMIT 1 ;");
} else {
return false;
}
}
else{
return TRUE;
}
}
How I can change my request to take all the record in the Excel file ?
Related
this is the first time I encounter of this problem and to be honest I don't know what this called. I have module where I need to insert all the data in the first table, then every id that inserted to the first table I want to get it each then insert it to the second table. The purpose of inserting the id to the second table is for the relation of the tables. Now I used laravel for my backend and I used the transform method to insert each data.
Now the main problem here is how can I get each last inserted Id to the first table and Insert it to the second table.
Here is my data that I inserted to the first table:
$collection = $rows->transform(function($item) use ($start,$cash_amount, $bank_deposit_amount, $off_set_amount, $grand_total) {
unset($item["key"]);
$item["checkDate"] = ($item["checkDate"] != '') ? $item["checkDate"] : null;
$item['encoded_by'] = ($item['customer'] != '') ? Auth::user()->name : '';
$item['receive_date'] = ($item['customer'] != '') ? $start : null;
$item['status'] = ($item['customer'] != '') ? "exchange_check" : '';
$item['amount'] = ($item['amount'] != '') ? floatval(preg_replace('/[^\d.]/', '', $item['amount'])) : '';
$item["original_date"] = $item["checkDate"];
$item['cash'] = $cash_amount;
$item['bank_deposit'] = $bank_deposit_amount;
$item['offset'] = $off_set_amount;
$item['grand_total'] = $grand_total;
return $item;
});
ExchangeCheck::insert($collection->toArray());
For second table I used this model use App\ExchangeList; where this model use to inserted all the ID's from the the ExchangeCheck Model:
Is this possible that I can insert each ID's of ExchangeCheck to the ExchangeList?
Thanks.
When inserting your data into your table, instead of insert used insertGetId, and inject the result into a variable in order to retrieve the id.
Try something like :
$lastIDinserted = ExchangeCheck::insertGetId($collection->toArray());
Otherwise you can use this method :
$lastIDinserted2 = ExchangeCheck::select('id')->orderByDesc('id')->first();
// OR
$lastIDinserted2 = ExchangeCheck::latest('id')->first();
And to retrieve your id, do:
$lastIDinserted2 = $lastIDinserted2->id;
Hope this helped you !
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 an empty table in my database in MySQL, and I trying to add multiple records
(I do this in this way because I'm following and order; If I delete a record then the auto increment field (id) skips 1 value. For example. I delete the id = 340 and then the following record start with an id with a value = 341)
I have an If Else statement in a function in my controller where I use to compare the id itself of my table Hours.
public function showHours($id){
$complex = ComplexNew::find($id);
$fields = CourtsComplex::all();
$hours = HoursNew::all();
$last_hours = collect($hours)->last();
if ($last_hours->id == $last_hours->id){
$last_hours->id = $last_hours->id + 1;
}else{
return Redirect()->back();
}
return view('hours.FormNewHours')->with('complex', $complex)->with('fields', $fields)->with('last_hours', $last_hours);
}
And this line is the line where I have the error.
if ($last_hours->id == $last_hours->id){
//DO SOMETHING
// ...
}
The error is: 'Trying to get property 'id' of non-object'.
Also I was trying to add another if else statement something like this:
if(is_null($last_hours->id)){
$last_hours->id = 1;
}else if($last_hours->id == $last_hours->id){
//ADD +1 TO ID.
}
Because I want that if the table is empty the id of the first record must be started with value = 1 but if the table is not empty add 1 to the last id, like a for statement because this condition add always +1 to last id.
Change
$last_hours = collect($hours)->last();
to
$last_hours = $hours->last();
Plus dd($last_hours) if it returns object then try accessing id like $last_hours->id
I have a table SQL and I fill it from an Excel File. The problem is many fields are repeated. For example:
FOURNITURE MFC SERIE
FOURNITURE MFC SERIE
FOURNITURE MFC SERIE
Here in my table, I find just one line. It jumps up all the rest. However, I need to get all the lines.
My request is:
if ($articleid == 'DIEPRESTATION' || $articleid == 'DIEDIVBIEN' || $articleid == 'DIEDIVERS' ){
if(!($this->_db->query("INSERT INTO `article` (`ID_Article`, `Designiation`, `Ident`, `ID_LRU`) VALUES ('".$articleid."', '".$designation."', '".$ident."', '".$IdLRU."');"))){
if ($LRU != 'new'){
return $this->_db->query(" UPDATE `FLOOSE`.`article` SET `ID_LRU` = '".$IdLRU."' WHERE `article`.`ID_Article` = '".$articleid."' AND `article`.`Designiation` = '".$designation."' AND `article`.`Ident` = '".$ident."' LIMIT 1 ;");
} else {
return false;
}
} else{
return TRUE;
}
}
How can I change it or take a test to recover all the lines?
Thank you.
I want insert some articles. I want make a judge first, if the image value has already in the database, insert a null value.
For more explain:
If there have these data:
title1,image1
title2,image2 //this is image2 first appear, so insert it
title3,image2 //image2 has already in the database, so insert an empty value for just image field
title4
title5,image3
the final data insert into the database should like this:
title | image
title1,image1
title2,image2
title3
title4
title5,image3
Here is my code, but it still insert the repeat value into the database. So is there any one can help me? thanks.
foreach{//first here has a foreach to make all the articles as a queue
...
if(!empty($image)){ //first judge if the insert article had a image value
$query1 = mysql_query("select * from articles where .image = '".$image."' ");
while ($row = mysql_fetch_array($query1)) {
$image1 = $row['image'];
}
}
if(!empty($image1)){ //make a query first if the image has already in the database
mysql_query("INSERT INTO articles (title,image) SELECT '".$title."','' ");
}else{
mysql_query("INSERT INTO articles (title,image) SELECT '".$title."','".$image."' ");;
}
}
Your first query contains an error. You have to remove the dot before "image":
where **.**image
As Francesco mentioned that dot could be a problem for that query.
Not really clear what you are trying to do here. But if you are trying to stop same image file being stored twice then you should use something like this below:
function is_same_file( $image1, $image2 ){
if( filesize($image1) != filesize($image2)
return false;
if( hash_file('md5', $image1) != hash_file('md5', $image2) )
return false;
return true;
}