Changing the value of a column in an entry using $wpdb - php

I have a table in my WordPress application, with some entries present. One of the columns in my table is flag, which could either be 1 or 0 depending on a condition. BY default, all entries have the flag column set as 1.
Now, I'm trying to change the value of flag for some entries from 1 to 0 as follows:
$res = $wpdb->get_results( 'SELECT * FROM wp_q33uds_campaign WHERE flag = 1 ORDER BY date1' );
foreach($res as $re)
{
$re->flag = 0;
}
However, the above method doesn't seem to change the value of the flag column from 1 to 0. Am I trying to do this the wrong way?

For this you can use update query to change flag value
$wpdb->update(
$wpdb->prepare(
$wpdb->prefix.'item_info', // table name
array(
'post_id' => $post_id, // table column that need change
'item_stock' => $item_stock
),
array('post_id' => $post_id) // id of table
)
);

Related

I want affected rows data and column which has affected by update query in codeigniter

Is there a way to obtain only the affected columns after an update query?
After an update query, that involves 10 columns, I know that only 2 columns are
really updated (because the values of the other cols don't change).
I need to know the names of the changed cols, for logging purpose.
$this->db->query("UPDATE `table1` SET name = $name,......................,column10=10 WHERE id=$id")->result();
$this->db->affected_rows();
This code gives number of affected rows but i want the data and updated
column information.
As far as I know there are no built-in CodeIgniter functionality for that. You could compare old value with new value though :
$last_record = $this->db->get_where('table1', array('id' => $id))->row_array();
$this->db->query("UPDATE `table1` SET name = $name,......................,column10=10 WHERE id=$id")->result();
// $this->db->affected_rows();
$new_record = $this->db->get_where('table1', array('id' => $id))->row_array();
$affected_columns = array_diff($new_record, $last_record);
foreach ($affected_columns as $field => $value) {
echo "[field] : $field\r\n";
echo "[old_value] : $last_record[$field]\r\n";
echo "[new_value] : $value\r\n";
echo "\r\n";
}
This will print each of the of the updated column with it's old-new value respectively.

Mysql update all columns starting with same Name

I have a dynamic table named 'products' with multiple Languages.
The table columns looks like this:
id, product_id, store_de, store_en, store_fr, store_es... etc
The languages can be more or less.
Now I want to update this table and set all columns beginning with "store_" to value 1.
I tried the following:
$stmt = $dbh->prepare( "UPDATE products SET `store_%` = ? WHERE product_id = ?" );
$stmt->execute( array( 1, $lastID ) );
I get following error message:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'store%' in
'field list'
Is there a way to update all columns beginning with 'store_' or do I have to list all the columns?
Based on the answer from jekaby here is the full solution that worked for me:
$get_stores = $dbh->prepare("SHOW COLUMNS FROM products_active WHERE field REGEXP '^store'");
$get_stores->execute();
$stores = $get_stores->fetchAll();
$update_string = "";
$first_store = true;
foreach($stores as $store) {
if(!$first_store) {
$update_string .= ", ";
} else {
$first_store = false;
}
$update_string .= $store['Field']." = '".$status."'";
}
$update_activity = $dbh->prepare("UPDATE products_active SET $update_string WHERE product_id = ?");
$update_activity->execute(array($product_id));
You need to set each column explicitly. SQL doesn't support wildcards for column names (with the exception of * for SELECT *):
update products
set store_de = 1,
store_en = 1,
store_fr = 1,
store_es = 1,
. . .
where product_id = ?;
Your data structure suggests that you really want a ProductStores table. This would have one row per language (?) and per product. It would have at least three columns:
ProductId
Language
Value
Then you would simply do:
update ProductStores
set Value = 1
where ProductId = ?;
You can not do like this store_% - it is nonexistent column in table as it is written in your error.
You should get all colums with names like /^store_/ (regexp). And than update all this fields having listed them.
mysql> SHOW COLUMNS FROM products where field REGEXP '^store_'
Than collect all fields from 'Field'... You can read more how to get all columns here.

Add new user and usermeta into database with SQL

I've using this to create a new user in the WordPress database...
// Add user to WP users table.
$user_table_name = $wpdb->prefix . "users";
$unique_string = substr(md5(rand(0, 1000000)), 0, 10);
$wpdb->insert( $user_table_name, array(
'user_login' => sanitize_text_field($_POST['email']),
'user_pass' => sanitize_text_field(MD5($unique_string)),
'user_email' => sanitize_text_field($_POST['email']),
'user_registered' => sanitize_text_field(date("Y-n-d G:i:s")),
'user_status' => $_POST['1'],
'display_name' => sanitize_text_field($_POST['first_name']) . " " . sanitize_text_field($_POST['last_name'])
) );
...which works fine, and let's pretend that the ID of that user turned out to be 1234 in the database table (thanks to auto increment).
So now I also need to add the corresponding user meta information into the usermeta table for that user, and this is where I get a little confused.
The code above is easy because it's just adding a row to a table. But the usermeta table is different because it will need - in this case - a bunch of rows with the corresponding user_ID of 1234 each respectively with:
nickname (I'll use the email address for this)
wp_capabilities (value to be a:1:{s:10:"subscriber";b:1;})
sales (a custom field I have - value will be set to the word "yes")
colour (another custom field I have - value will be set to the word "green")
I'm guessing the SQL statement is going to be similar to the one at the start of this post.
If anyone could show me, that would be awesome.
UPDATE:
So this is mostly done. This works:
// Add corresponding user metadata to WP users table.
$usermeta_table_name = $wpdb->prefix . "usermeta";
$last_id = $wpdb->insert_id;
$role = sanitize_text_field('a:1:{s:10:"subscriber";b:1;}');
$wpdb->query(
$wpdb->prepare(
"
INSERT INTO $usermeta_table_name (
`umeta_id`,
`user_id`,
`meta_key`,
`meta_value` )
VALUES (
NULL,
$last_id,
$usermeta_table_name . 'capabilities',
'$role' )
",
$last_id, $last_id
)
);
That will add one row to the usermeta table, but how can I add 2 more rows within the same statement?
Store the last inserted row's ID to a variable:
$last_id = $wpdb->insert_id;
now, use this $last_id variable for metadata insertion. The insert_id variable is provided by the wpdb class.
OK so I feel a little silly about this - though to be fair it's been a long time since I wrote any SQL :-)
The answer is simply to follow this method:
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);

CodeIgniter set a column value another existing column value without make a select

I have a table which has columns status and new_status, so when i change status i put in new_status the new value for status.
But i want to have a backup solution, so i need an update which set value for new_status value from column status.
I use codeigniter, i tried
$data = array(
'new_status'=>Status,//'new_status'=>'Status'//'new_status'=>`Status`
);
But none above worked.
I made a custom query and i called with
$query = $this->db->query($text);
and $text = "UPDATE table SET new_status = status WHERE [condition]" and it's working 100%.

$wpdb->insert produces " Duplicate entry '0-0' for Key '1' "

I'm writing a plugin and trying to insert a new row into the wp_term_relationships table inside of a foreach loop. I know the variables have values because of a var_dump, but for some reason, I'm getting an error consistently. This shows up about 600 times on the show_errors() function:
WordPress database error: [Duplicate entry '0-0' for key 1] INSERT
INTO wp_term_relationships
(object_id,term_taxonomy_id,term_order) VALUES ('','','')
My Code:
foreach ($cb_t2c_cat_check as $values) {
global $wpdb;
$prefix = $wpdb->prefix;
$table = $prefix . 'term_relationships';
$object_id = $values->object_id;
$taxo_id = $values->term_taxonomy_id;
$num_object_id = (int)$object_id;
$num_taxo_id = (int)$taxo_id;
//var_dump($num_object_id); //This produces values, so why are they not getting inserted into the table?
//var_dump($num_taxo_id); //This produces values, so why are they not getting inserted into the table?
$wpdb->insert(
$table,
array(
'object_id' => $num_object_id,
'term_taxonomy_id' => $num_taxo_id,
'term_order' => 0
), ''
);
//$wpdb->show_errors();
//$wpdb->print_error();
}
As for why it does not work: do not set third parameter of $wpdb->insert to empty string. It formats every field accordingly..
What it does now is equivalent to:
$wpdb->insert($table, array(
'object_id' => sprintf('', $num_object_id),
'term_taxonomy_id' => sprintf('', $num_taxo_id),
'term_order' => sprintf('', 0)
));
If you really want to set third parameter you should do:
$wpdb->insert($table, array(
'object_id' => $num_object_id,
'term_taxonomy_id' => $num_taxo_id,
'term_order' => 0
), array('%d', '%d', '%d'));
As for error: wp_term_relationships table has a unique primary key on (object_id, term_taxonomy_id). This means that you cannot have two rows in that table which have both same object_id and term_taxonomy_id.
Though this has happened because by setting third parameter of insert to empty string, you are trying to insert rows with object_id=0 and term_taxonomy_id=0 over and over again.
The answer above was correct in that the database needs to have unique keys and cannot insert a row where the key-value pair already exists, and the format of each new value needs to be set. In addition, specific to Wordpress, there was a problem I wasn't addressing, specifically dealing with the term_taxonomy table and updating the count.
First it's important to note that the plugin was designed to update certain categories for posts in the term_relationships table. This was actually accomplished using the $wpdb-> insert method. However, my test for determining whether the plugin actually inserted new rows in the term_relationships table was not to look at the table directly, but to go to the Wordpress dashboard, select categories, and see if the number of posts with that category was more than before. This didn't work, because the plugin never updated the count in the term_taxonomy table. I only discovered this by clicking 'view' next to a category in the Wordpress dashboard and seeing that there were multiple posts with that category, even though the official Wordpress "count" said there were none.
I confirmed that the term_taxonomy table, the 'count' column, needed to be updated as well by going straight to the database and putting WHERE = 'term_taxonomy_id' in the statement. Sure enough, there were over 1700 results, even though Wordpress thought there were none.
Lesson: Confirm the $wpdb->insert method is working by using PHPMyAdmin, not necessarily relying on the Wordpress dashboard.
With a few modifications, the code now works great. Here's an example:
foreach ($cb_t2c_objects as $values) {
global $wpdb;
$prefix = $wpdb->prefix;
$table = $prefix . 'term_relationships';
$object_id = $values->object_id;
$taxo_id = $values->cat_taxo;
$num_object_id = (int)$object_id;
$num_taxo_id = (int)$taxo_id;
//Need to check to see if row exists for each, if not, then insert.
$cb_t2c_get_row = $wpdb->get_row("
SELECT *
FROM ".$prefix."term_relationships
WHERE object_id = ".$num_object_id." AND term_taxonomy_id = ".$num_taxo_id."
GROUP BY object_id, term_taxonomy_id
", OBJECT);
//var_dump($cb_t2c_get_row);
if ( is_null($cb_t2c_get_row) ) {
//Insert the new values.
$wpdb->insert(
$table,
array(
'object_id' => $num_object_id,
'term_taxonomy_id' => $num_taxo_id,
'term_order' => 0
),
array(
'%d',
'%d',
'%d'
)
);
}
//Set the variables for the count update.
$cb_t2c_term_taxonomy_table = $prefix . 'term_taxonomy';
$cb_t2c_update_data = $wpdb->get_var("
SELECT count(term_taxonomy_id) as 'new_count'
FROM ".$prefix."term_relationships
WHERE term_taxonomy_id = ".$num_taxo_id."
",0,0); //returning NULL
//var_dump($cb_t2c_update_data);
//Update the count in the term_taxonomy table.
$wpdb->query("
UPDATE ".$prefix."term_taxonomy
SET count = ".$cb_t2c_update_data."
WHERE term_taxonomy_id = ".$num_taxo_id."
");

Categories