WordPress use wpdb -> update to update mutiple row - database

I'm trying to update multiple rows once, I use the array to store the data and I use for loop to try to update the data but it's not working because the data in the database is still the same. What am I doing wrongly?
global $wpdb;
$table_name = $wpdb -> prefix . 'test';
$check_first = 1;
$check_second = 2;
$update = array (
array ( 'value' => $check_first ),
array ( 'value' => $check_second )
);
$condition = array (
array ( 'name' => 'enable' ),
array ( 'name' => 'picked' )
);
for ( $x = 0; $x <= 2; $x++ ) {
$wpdb -> update ( $table_name, $update, $condition );
}

You only need to set array index in 'update' and 'condition' like this -
global $wpdb;
$table_name = $wpdb->prefix . 'test';
$update = array(
array( 'value' => 3 ),
array( 'value' => 4, 'state' => 'asdf' )
);
$condition = array(
array( 'name' => 'enable' ),
array( 'name' => 'picked' )
);
for ( $i = 0; $i < sizeof( $condition ); $i++ ) {
$wpdb->update( $table_name, $update[$i], $condition[$i] );
}
This will update line by line.

Related

CakePHP 3.6 - Find All Records Created Between Two Dates

I am looking for all records between two dates
My variables
$start = '01/01/2009';
$end = '07/24/2019';
I have tried
$gross = $this->CartOrders->find('all')->where(['placed >=' => $start])->andWhere(['placed <=' => $end])->all();
Query Snippet for above
... FROM cart_orders CartOrders
WHERE (placed >= :c0 AND placed <= :c1)
[params] => Array (
[:c0] => Array ( [value] => 01/01/2009 [type] => datetime [placeholder] => c0 )
[:c1] => Array ( [value] => 07/24/2019 [type] => datetime [placeholder] => c1 ) )
Results in
Cake\ORM\ResultSet Object ( [items] => Array ( ) )
I have also tried
$gross = $this->CartOrders->find('all')->where(function($exp) use($start,$end) {
$exp->lte('placed', $end);
$exp->gte('placed', $start);
return $exp;
})->all();
I also have tried
$gross = $this->CartOrders->find('all')->where(function($q) use($start,$end) {
return $q->between('CartOrders.placed', $start, $end, 'date');
})->all();
Any ideas on how I can accomplish this?
Use QueryExpression
use Cake\Database\Expression\QueryExpression;
$query = $this->CartOrders->find()
->where(function (QueryExpression $exp, Query $q) use ($start,$end){
return $exp->between('placed', $start, $end);
});
Probably add a time at condition if the user tried to search within the same day
return $exp->between('placed', $start . " 00:00:00", $end . " 23:59:59");
Try using
$this->CartOrders->find('all', array('conditions' => array(
'date(placed) BETWEEN "'.$start.'" AND "'.$end.'"')));
It's an unorthodox solution but its something that has worked for multiple scenarios for me
$this->set('gross',$this->CartOrders-> find(
'all', array(
'conditions' => array(
'CartOrders.placed >=' => $start,
'CartOrders.placed <=' => $end
))
)); // here gross is a variable to store the data from DB and CartOders is the Model name
This turned out to be a date format issue.
The following solved my problem.
$start = '01/01/2009';
$end = '07/24/2019';
$start = DateTime::createFromFormat('d/m/Y', $start);
$end = DateTime::createFromFormat('d/m/Y', $end);
$gross = $this->CartOrders->find('all')->where([
'placed >=' => $start->format('Y-m-d')
])->andWhere([
'placed <=' => $end->format('Y-m-d')
])->all();
This link helped
PHP convert date format dd/mm/yyyy => yyyy-mm-dd

how to remove rows from multidimensional array cakephp

I added some item inside cart session(Array) but i want to remove 1 rows for that i wrote following code but that is not working for me.
public function deletecart() {
$this->loadModel("Product");
if($this->Session->check('cart') AND count($this->Session->read('cart'))>0)
{
foreach ($this->Session->read('cart') as $key => $value) {
if ($value['0']['Product']['id'] == "12") {
unset($this->Session->read('cart')[$key]);
}
}
}
}
Here is my session debug value
array(
'[0]' => array(
(int) 0 => array(
'Product' => array(
'id' => '8',
'category' => 'Pendant',
)
)
),
(int) 1 => array(
(int) 0 => array(
'Product' => array(
'id' => '12',
'category' => 'Pendant'
)
)
)
)
You can't unset session key value like this. You will have to store Session key value in a temporary variable.
$sessionArr = $this->Session->read('cart');
foreach ($sessionArr as $key => $value) {
if ($value['0']['Product']['id'] == "12") {
// Unset key
unset($sessionArr[$key]);
}
}
// Assign $sessionArr value to cart key
$this->Session->write('cart',$sessionArr);

Using Count in CakePHP

I am trying to use the count function , this is what it looks like :
$sql = "SELECT COUNT(Live) as c FROM tapplicant WHERE CompletedDate >= CURDATE() ";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
echo $row['c'] ;
How do i conver this using the cakePHP way ? , i have tryed :
$count = $this->Article->find('count',
array('conditions' => array('Tapplicant.Live')));
Then to view the value of $count :
<?php echo $count ?>
I have tryed :
$this->Tapplicant = array(
'c' => 'COUNT(*)',
);
$options = array(
'fields' => array(
'Tapplicant.c',
),
);
$data = $this->find('all', $options);
$this->set('data', $data );
Basically im just trying to count the value of tapplicant.Live , there are 5 records in it.
You almost have it. In your condition, the value array should have 2 fields. 1st the column name, 2nd the value of the condition.
Considering you've binded correctly the Tapplicant table to your Article model :
$count = $this->Article->find('count', array('conditions' => array('Live >=' => 'CURDATE()' )));
Or just this, if you want to count all lines :
$count = $this->Article->find('count');
You need to set the conditions array like this:-
$count = $this->Article->find(
'count',
array(
'conditions' => array(
'Live >=' => 'CURDATE()'
)
)
);

Extracting values from arrays in custom fields

I'm trying to come up with a single array of all values in specific custom fields. The values themselves are also arrays. I've tried all sorts of array functions but haven't come across the right one or the right combination. Here is my code thus far:
$args = array(
'post_type' => 'match_report',
'post_status' => 'publish',
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'report_home-scorers'
),
array(
'key' => 'report_away-scorers'
)
)
);
$reportscore = new WP_Query($args);
$scorersResults = array();
if ( $reportscore->have_posts() ) {
while ( $reportscore->have_posts() ) {
$reportscore->the_post();
$homescorers = get_post_meta($post->ID,'report_home-scorers',false);
$awayscorers = get_post_meta($post->ID,'report_away-scorers',false);
foreach ($homescorers as $homescorer){
array_push($scorersResults, $homescorer);
}
foreach ($awayscorers as $awayscorer){
array_push($scorersResults, $awayscorer);
}
?>
<?php } wp_reset_postdata(); //endif
}//endwhile
$scorerResults = remove_empty($scorersResults);
function remove_empty($array) {
return array_filter($array, '_remove_empty_internal');
}
function _remove_empty_internal($value) {
return !empty($value) || $value === 0;
}
Here what I get if I print_r($scorerResults); :
Array
(
[1] => Array
(
[0] => 1
[1] => 63
)
[2] => Array
(
[0] => 263
[1] => 195
)
[3] => Array
(
[0] =>
)
[4] => Array
(
[0] =>
)
)
I just want the values in the internal arrays in an array.
Assuming you want the $scoreResults array to end up as array(1,63,263,195) you could use the array_reduce function like this:
function gatherScores($lhs, $rhs) {
foreach ($rhs as $key => $value)
if ($value)
$lhs[] = $value;
return $lhs;
}
$scorerResults = array_reduce($scorerResults, "gatherScores", array());
I'm not sure what the blank values are in your third and fourth arrays and how they should be handled, so you may need to change the if ($value) condition to check for something different. As it stands it'll obviously also filter out zero scores.

Need help in Cakephp updateAll

I need to use updateall to update position and column of widget
if (!empty($column3[0])) {
$column = preg_split("/,/", $column3[0]);
$name = $column[2];
switch ($name) {
case 'My Profile':
$table = 'WidgetProfile';
break;
case 'My script':
$table = 'WidgetScript';
break;
case 'My Setting':
$table = 'WidgetSetting';
break;
case 'Upload Script':
$table = 'WidgetUpload';
break;
case 'My message':
$table = 'WidgetMessages';
break;
default :
echo "Error3 0";
}
$this->loadModel($table);
$row = $this->$table->find('count',array('conditions'=>array('user_id'=>'$id));
if($row==0){
$this->$table->set(array('column',=> 3, 'position' => 1,'user_id'=>$id));
$this->$table->save();
}else{
$this->$table->updateAll(**?????????????**);
}
how to use updateAll for it
It's not very clear from the question what you're trying to do, but it looks like you're trying to update an existing record, or if there isn't a record already, create one. You can use Model::save() for both. If the model's id is set it will update, otherwise it'll insert a new row.
$row = $this->$table->find(
'first',
array(
'conditions' => array( 'user_id'=> $id ),
'fields' => "$table.id",
'recursive' => -1
)
);
if( !empty( $row ) ) {
$this->$table->id = $row[ $table ][ 'id' ];
}
$this->$table->save( array('column' => 3, 'position' => 1, 'user_id'=> $id ) );

Resources