Deleting Table Data Before Inserting New Data - php

I have these two tables, table A and table B. Before updating my table B I want to delete it's datas before inserting a new one.
I have this query where it will delete the data in that table and insert a new one after it succeeded in deleting the old records. It is inserting the values but it's not deleting the old one, so it ended up duplicating some of my new id's that were already inserted before. I tried it with this code:
public function editDiscount(){
foreach ($this->searchFields as $field => $value) :
if($field == 'KEY'){
$key = $value;
} else if($field == 'NAME'){
$discountName = $value;
} else if($field == 'CODE'){
$discountCode = $value;
} else if($field == 'DESC'){
$discountDesc = $value;
}else if($field == 'TYPE'){
$discountType = $value;
}else if($field == 'TRANS'){
$discountTransaction = $value;
}else if($field == 'EXPTYPE'){
$expiration = $value;
}else if($field == 'START'){
$expStartDate = $value;
}else if($field == 'END'){
$expEndDate = $value;
}else if($field == 'VALUE'){
$discountValue = $value;
}else if($field == 'PRODKEY'){
$productId= $value;
}
endforeach;
$discount = VlDiscount::query()
->andWhere("autokey =?1")
->andWhere("app_id =?2")
->bind(array(1=>$key,2=>$this->session->get('appId')))
->execute();
if($discount->count() != 0){
$discountUpdate = VlDiscount::findFirst($key);
$discountUpdate->discountName = $discountName;
$discountUpdate->discountCode = $discountCode;
$discountUpdate->discountDesc = $discountDesc;
$discountUpdate->discountType = $discountType;
$discountUpdate->discountTransaction = $discountTransaction;
$discountUpdate->expiration = $expiration;
$discountUpdate->expStartDate = $expStartDate;
$discountUpdate->expEndDate = $expEndDate;
$discountUpdate->discountValue = $discountValue;
if($discountUpdate->update() == false){
$devMessage = array();
foreach ($discountUpdate->getMessages() as $key){
$devMessage[] = $key->getMessage();
}
return $this->respond(array(
'userMessage' => 'Failed',
'devMessage' => $devMessage,
'more' => 'Failed to update. One or more fields failed on validation.'));
}else if ($discountTransaction == 'p'){
foreach ($this->searchFields as $field => $value) :
if($field == 'PRODKEY'){
$productId = $value;
}
endforeach;
$exs = explode('|',$productId);
$deleteErrors = 0;
foreach ($exs as $xx) {
$deleteproductDiscount = VlDiscountProduct::query()
->andWhere("discountId =?1")
->andWhere("app_id =?2")
->bind(array(1=>(int)$xx,2=>$this->session->get('appId')))
->execute();
foreach($productdiscountDelete as $cat){
$productsDelete = VlDiscountProduct::findFirst($cat->$discountUpdate->autokey);
if ($deleteproductDiscount != false) {
if ($productsDelete->delete() == false) {
$deleteErrors++;
$devMessage = array();
foreach ($deleteproductDiscount->getMessages() as $key){
$devMessage[] = $key->getMessage();
}
}
}
}
unset($deleteproductDiscount);
}
if($deleteError == 0){
$exp = explode('|',$productId);
foreach ($exp as $item){
$productDiscount = new VlDiscountProduct();
$productDiscount->discountId = $discountUpdate->autokey;
$productDiscount->productId = $item;
$productDiscount->app_id = $this->session->get('appId');
if($productDiscount->create() == false){
$devMessage = array();
foreach ($productDiscount->getMessages() as $key){
$devMessage[] = $key->getMessage();
}
return $this->respond(array(
'userMessage' => 'Failed',
'devMessage' => $devMessage,
'more' => 'Failed to create. One or more fields failed on validation.'
));
}
}
return $this->respond(array('userMessage' => 'OK'));
}else{
return $this->respond(array(
'userMessage' => 'Failed',
'devMessage' => $devMessage,
'more' => 'Failed to delete. One or more fields produced an error.'
));
}
return $this->respond(array(
'userMessage' => 'Failed',
'devMessage' => 'Cannot find user information',
'more' => 'Failed to update. One or more fields failed on validation.'));
}
}
}

You're checking if($deleteError == 0){ instead of if($deleteErrors == 0){.
UPDATE
This whole foreach statement is off.
foreach($productdiscountDelete as $cat){
$productsDelete = VlDiscountProduct::findFirst($cat->$discountUpdate->autokey);
if ($deleteproductDiscount != false) {
if ($productsDelete->delete() == false) {
$deleteErrors++;
$devMessage = array();
foreach ($deleteproductDiscount->getMessages() as $key){
$devMessage[] = $key->getMessage();
}
}
}
}
You never define $productdiscountDelete, so it's never going into this foreach loop.

i also change
$productsDelete = VlDiscountProduct::findFirst($cat->$discountUpdate->autokey);
to
$productsDelete = VlDiscountProduct::findFirst($cat->autokey);

Related

Auto Description From Tags

I'm trying to generate auto description from tags.
The code was working but after updating my site to Laravel 6 in stop working. I need to get it back working.
if( !empty( $request->description ) )
{
$description = Helper::checkTextDb($request->description);
}
else
{
$a_key = explode(",", strtolower($request->tags));
if(count($a_key) == 0)
$description = 'This is a great thing';
else
{
$description_get_keys = '';
foreach ($a_key as &$value)
{
if($value == end($a_key) && count($a_key) != 1)
$description_get_keys = $description_get_keys.' and '.$value.'.';
else if(count($a_key) == 1)
$description_get_keys = $value.'.';
else if (count($a_key) > 1 && $a_key[0] == $value)
$description_get_keys = $value;
else
$description_get_keys = $description_get_keys.', '.$value;
}
$description = 'This is a great thing about '.$description_get_keys;
}
}
I see a couple things that could possibly be an issue, not knowing what came before this code.
I will assume that the $request variable is an instance of Illuminate\Http\Request and that it is available in the function, right?
Try this updated code:
if($request->has('description'))
{
$description = Helper::checkTextDb($request->description);
}
else if ($request->has('tags'))
{
if (strpos($request->tags, ',') === false)
{
$description = 'This is a great thing';
}
else {
$a_key = explode(",", strtolower($request->tags));
$a_count = count($a_key);
$description_get_keys = '';
for ($i = 0; $i < $a_count; $i++)
{
if ($a_count == 1) {
$description_get_keys = "{$a_key[$i]}.";
}
else {
// first
if ($i === 0) {
$description_get_keys = $a_key[0];
}
// last
else if ($i === $a_count - 1) {
$description_get_keys .= " and {$a_key[$i]}.";
}
// middle
else {
$description_get_keys .= ", {$a_key[$i]}";
}
}
}
$description = "This is a great thing about {$description_get_keys}";
}
}
I wrote that quick so hopefully there are no errors.

Value not saving outside foreach loop

I update my code from PHP 5 to PHP 7 and i got problem with foreach loop. I loocked wor answers here, but none is working. Or i dont understand where i have problem
function getStructure($pid = 0, $expand = array(), $alevel = 0)
{
$struct = array();
if ( $alevel > $this->levelCount) $this->levelCount = (int)$alevel;
$str = $this->dbStructure->getStructure($pid);
foreach ($str as &$row)
{
if ($row["type"] == STRUCT_PAGE)
{
$row["editLink"] = "editPage";
$row["target"] = "_self";
}
elseif ($row["type"] == STRUCT_MODULE)
{
$row["editLink"] = "editModule";
$row["target"] = "_self";
}
elseif ($row["type"] == STRUCT_LINK)
{
$row["editLink"] = "editLink";
$row["target"] = "_blank";
}
elseif ($row["type"] == STRUCT_CATALOG)
{
$row["editLink"] = "editCatalog";
$row["target"] = "_self";
}
$row["childrens"] = $this->getStructure((int)$row["id"], $expand, $alevel+1);
if ($row["type"] == STRUCT_CATALOG and isset($row["childrens"][0]["shortcut"]))
{
$row["shortcut"] = $row["childrens"][0]["shortcut"];
$row["target"] = $row["childrens"][0]["type"] == STRUCT_LINK ? "_blank" : "_self";
}
$struct[] = $row;
}
unset($row);
return $struct;
}
All the time $struct is NULL and I need to be multidimensional array
This code by itself is good. Has no problems, only ampersand is not needet. The problem was in different place. Sorry for spam

Mysql multiple select queries

I have 600.000 data and I strain the values.
I strain some values in my database. I have 10 criterion about strain data.
So , When i strain the 600.000 Data from 10 criterion my mysql server is very slow.How can I make it fast ? This is my source code about strain.
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
ini_set('memory_limit', '256M');
function Check($Value,$DataBase)
{
$QueryString = "SELECT UserID FROM users where ".$Value;
$query = $DataBase->query($QueryString, PDO::FETCH_ASSOC);
//echo $Sorgu;
if ($query->rowCount()) {
foreach ($query as $row) {
return true;
}
}
return false;
}
$Array = $_POST["Data"];
$Array = json_decode($Array, true);
$Keys = ' ';
$Values = ' ';
$GSM1 = array();
$GSM2 = array();
$Phone1 = array();
$Phone2 = array();
$Fax1 = array();
$Fax2= array();
$UserCode = array();
$Identitiy = array();
$Empty = array();
$EmptyCheck = true;
foreach ($Array as $Row) {
$EmptyCheck = true;
$Keys = ' ';
$Values = ' ';
foreach ($Row as $key => $val) {
if ($key == 'UserGsm1') {
if ($val != null AND is_numeric($val) AND Check('UserGsm1=' . $val,$db)) {
$EmptyCheck = false;
$Gsm1[] = $Row;
break;
}
} else if ($key == 'UserGsm2') {
if ($val != null AND is_numeric($val) AND Check('UserGsm2=' . $val,$db)) {
$EmptyCheck = false;
$Gsm2[] = $Row;
break;
}
} else if ($key == 'UserPhone1') {
if ($val != null AND is_numeric($val) AND Check('UserPhone1=' . $val,$db)) {
$EmptyCheck = false;
$Phone1[] = $Row;
break;
}
} else if ($key == 'UserPhone2') {
if ($val != null AND is_numeric($val) AND Check('UserPhone2=' . $val,$db)) {
$EmptyCheck = false;
$Phone2[] = $Row;
break;
}
} else if ($key == 'UserFax1') {
if ($val != null AND is_numeric($val) AND Check('UserFax1=' . $val,$db)) {
$EmptyCheck = false;
$Fax1[] = $Row;
break;
}
} else if ($key == 'UserFax2') {
if ($val != null AND is_numeric($val) AND Check('UserFax2=' . $val,$db)) {
$EmptyCheck = false;
$Fax2[] = $Row;
break;
}
} else if ($key == 'UserCode') {
if ($val != null AND is_numeric($val) AND Check('UserCode=' . $val,$db)) {
$EmptyCheck = false;
$UserCode[] = $Row;
break;
}
} else if ($key == 'UserIdentitiy') {
if ($val != null AND is_numeric($val) AND Check('UserIdentitiy=' . $val,$db)) {
$EmptyCheck = false;
$Identitiy[] = $Row;
break;
}
}
$Keys = $Keys . ',' . $key;
$Values = $Values . ',' . $val;
//echo $key.' : '.$val;
//echo '<br>';
}
if ($EmptyCheck == true) {
$Empty[] = $Row;
}
}

Sort multidimensional array by another array and complete missing keys in the same order

I'm trying to export data from leads table to excel using PHP/Laravel, the leads table caמ be customized to show specific columns and the export columns should be same as the table columns. the problem is - if column not exists in a specific row the column not shown empty and the 'xls' file is exported really messy...
my code looks like this:
public function excelExport(Request $request, $client_id=null)
{
$client_id = is_null($client_id) ? \Auth::client()->id : $client_id;
if(is_null($this->client_users)){
$this->client_users = $this->clientsController->listClientUsers($client_id);
}
$columns = $this->account_settings->getColumnsDef($client_id);
$query = Lead::select(array_keys($columns))->where('client_id',strval($client_id))->where('deleted',0);
$query = $this->setQueryDates($request,$query,$client_id);
$query = $this->leadsFiltersController->setExportQuery($request,$query);
$arr = $query->get()->toArray();
Excel::create('leads' , function($excel) use ($arr,$columns){
$excel->sheet('Leads' , function($sheet) use ($arr,$columns){
$rows = [];
$count = 0;
foreach($arr as $lead){
$row = $this->setExportRowData($lead,$count,$columns);
$rows[] = $row;
$count++;
}
$sheet->fromArray($rows);
});
})->export('xls');
private function setExportRowData($lead,$count,$columns,$order = true)
{
$row = [];
$order = null;
foreach($lead as $k => $v) {
if (is_array($v)) {
switch (strtolower($k)) {
case "ga_details":
if (count($v) > 2) {
foreach ($v as $key => $ga_detail) {
if ($key != "realTime_data" && $key != "uacid") {
$row[$key] = $ga_detail;
}
}
}
break;
case "status":
if (isset($v['name']) && count($v['name'])) {
$row['status'] = $v['name'];
} else {
$row['status'] = "no status";
}
break;
case "owner":
if (isset($v['owner_id']) && count($v)) {
$row['owner'] = $this->getClientOwnerUserName($this->client_users, $v['owner_id']);
} else {
$row['owner'] = "no owner";
}
break;
case "prediction":
if (isset($v['score']) && count($v)) {
$row['prediction'] = $v['score'];
} else {
$row['prediction'] = "no prediction";
}
break;
case "the_lead":
foreach ($v as $key => $lead_detail) {
$row[$key] = $lead_detail;
}
break;
case "quality":
if (isset($v['name'])) {
$row['quality'] = $v['name'];
} else {
$row['quality'] = "no quality";
}
break;
case "feeds":
if (isset($v['feeds']) && count($v['feeds'])) {
$row['feeds'] = array_pop($v['feeds'])['message'];
}
break;
default :
$row[$k] = $v;
break;
}
} else {
if ($k != "_id") {
$row[$k] = $v;
}
}
}
return $order == true ? sortArrayByArrayValues($this->order,$row) : $row;
}
sortArrayByArrayValues function looks like this:
function sortArrayByArrayValues(Array $array, Array $orderArray)
{
$rtn = [];
foreach($array as $arr){
if(isset($orderArray[$arr])){
$rtn[$arr] = $orderArray[$arr];
}else{
$rtn[$arr] = '';
}
}
return $rtn;
}
I really have no clue how to solve it, appreciate any help!!! :)

Change the array structure in php

How can i change the test1 array format as like in test2?
$test1 = array(
'size'=>array('V'=>array('V'),'R'=>array('R','R')),
'price'=>array('V'=>array('77'),'R'=>array('88','99')),
'unit'=>array('V'=>array('3'),'R'=>array('3','2')),
'color'=>array('V'=>array('Black'),'R'=>array('Green','Red')));
$test2 = array(
'size'=>array('V','R'),
'price'=>array('V'=>array('Black'=>'77'),
'R'=>array('Green'=>'88','Red'=>'99')),
'unit'=>array('V'=>array('Black'=>'3'),
'R'=>array('Green'=>'3','Red'=>'2')),
'color'=>array('V'=>array('Black'),'R'=>array('Green','Red')));
Thanks!
With a foreach loop you can change the array structure.
http://php.net/manual/de/control-structures.foreach.php
Something like that should work: its pretty unclear what the rules are to convert from one array to the other in your case.
$test2 = array();
foreach ($test as $type => $array) {
$newArray = array();
foreach ($array as $key => $value) {
if ($key == 'V') {
if ($value == 3) {
$newArray['V'] = array('Black' => 3);
} else if ($value = 2) {
$newArray['V'] = array('Green' => 2);
}
} else if ($key == 'R') {
//....
}
}
$test2[$type] = $newArray;
}
Thanks for the response. and sorry for not being more specific. Actually i wanted all the values in dynamic manner. I constructed a loop :). Thanks!
$myArray = array();
foreach($test as $type => $array){
$k = 0;
foreach ($array as $key => $value) {
if($type == 'size'){
$myArray['size'][] = $key;
}else if($type == 'price' || $type == 'unit' ){
$m = 0;
foreach($value as $vall){
if($type == 'price'){
$myArray['price'][$myArray['size'][$k]][$test['color'][$myArray['size'][$k]][$m]] = $test['price'][$myArray['size'][$k]][$m];
}else if($type == 'unit'){
$myArray['unit'][$myArray['size'][$k]][$test['color'][$myArray['size'][$k]][$m]] = $test['unit'][$myArray['size'][$k]][$m];
}
$m++;
}
}else if($type == 'color'){
$myArray['color'][] = $value;
}
$k++;
}
}

Categories