WordPress MySQL update DB multiple columns by relationship key
Question
Hello guys. I am trying to figure out how can I update the values of a database’s columns with a relational key by passing an array of IDs (relational key), here is my code so far
protected function get_ad_block_impressions($value = null)
{
global $wpdb;
$table_name = $wpdb->prefix . 'ad_block_tracking';
$all_impressions = $wpdb->get_results( "SELECT * FROM $table_name" );
$ad_impressions = [];
foreach ($all_impressions as $ad) {
if ($value == 'impressions') {
$ad_impressions[] = $ad->ad_id;
$ad_impressions[] = $ad->impressions;
} elseif ($value == 'clicks') {
$ad_impressions[] = $ad->ad_id;
$ad_impressions[] = $ad->clicks;
}
}
// Check if if ad_id exist and update the impressions
if (in_array(846995, $ad_impressions)) { //Impression for one Ad_Id
// Update the impressions and clicks
$this->update_ad_block_tracking_status(array(
'impressions' => 1100000,
'clicks' => 10
), 846995); //Example Update 1 column by ad_id (relationship key)
}
// Check all active(by ad_id) add impressions
if ($this->ad_block_status()) { //This check for all active ad_block and return true
$this->update_ad_block_tracking_status(array(
'impressions' => 2000, //Values
'clicks' => 3000 //Values
), array(
'ad_id' => this->get_ad_by_ad_ID() // Array of ad_id to be update
));
}
return;
}
protected function update_ad_block_tracking_status($data = array(), $ad_id = array())
{
global $wpdb;
$table_name = $wpdb->prefix . 'ad_block_tracking';
// Get ad_block ad_id
$wpdb->update(
$table_name,
array(
'impressions' => $data['impressions'],// integer (number)
'clicks' => $data['clicks'] // integer (number)
),
array( 'ad_id' => $ad_id ), //Array of ad_id (relational key)
array(
'%d', // value1
'%d' // value2
),
array( '%d' )
);
// Clear cache
}
protected function get_ad_by_ad_ID()
{
global $wpdb;
$table_name = $wpdb->prefix . 'ad_block_tracking';
$all_ad_IDs = $wpdb->get_results( "SELECT * FROM $table_name WHERE ad_id" );
$IDs = [];
foreach ($all_ad_IDs as $id) {
$IDs[] = $id->ad_id;
}
// print_r($IDs);
// die;
return $IDs;
}
0
2 years
2020-12-30T07:10:42-05:00
2020-12-30T07:10:42-05:00 0 Answers
3 views
0
Leave an answer