in my wordpress blog i have a table consist of users and their products seperated by ";" for example :
mytable
----------------------
userid | products
----------------------
1 | camera
2 | books;keyboard;computer
3 | mouse;printer
4 | scanner
now in my script the user will add a new product so i need to check if that user has more than 3 products because in this case i will do nothing and will not add this product for him but if he has less than 3 products i need to add the new product to his products seperated by ";" something like :
$userid = 3;
$newproduct = "ball"
if (pruduct field for that user has more than 2 ";" ) {
do nothing
}else{
$wpdb->update(
'mytable',
array( 'product' => concat(product, ";", $newproduct)),
array( 'userid ' => $userid ),
array( '%s' ),
array( '%d' )
);
so the result in this example would be :
mytable
----------------------
userid | products
----------------------
1 | camera
2 | books;keyboard;computer
3 | mouse;printer;ball
4 | scanner
Despite the data normalization arguments, which are incredibly valid, if for some reason you cannot correct that and must work with what exists.
Select the products
column as a string and use the PHP explode()
and implode()
functions. You'd end up with something like this:
$current_products = explode(';', $user['products']);
// $current_products is now an array of the user's products.
if !(count($current_products) >= 3) {
$current_products[] = $new_product;
}
$user_products = implode(';', $current_products);
// Insert $user_products into your table via UPDATE
The implode
and explode
functions convert strings to and from arrays based on given delimiters.
In WordPress, the right way to do this is with the user_meta
table. With respect, your proposed way is not a good way.
You can set these values into the user_meta table with code like this.
$meta_key = '_my_products'; /* be sure to choose a unique key prefix */
add_user_meta( $userid, $meta_key, 'football', false );
add_user_meta( $userid, $meta_key, 'basketball', false );
You can get them back with code like this
$vals = get_user_meta( $userid, $meta_key, false );
foreach ($vals as $value) {
echo $i;
}
There are other functions for updating and deleting user_meta items. They work well. Read this. https://codex.wordpress.org/Function_Reference/get_user_meta