this is MySQL table structure:
TABLE: products
|----------------------------------------------|
| id | product_ids |
| 1 | 51 |
| 2 | 616,2,38 |
| 3 | (NULL) |
| 4 | 426,605,604 |
|----------------------------------------------|
What im looking is a way for the code to check if the id 605 exists in product_ids
row, and if it does to replace for another ID:
any idea how can i accomplish this?
I was thinking of a sql QUERY...
To find out if it contains '605':
SELECT id, product_ids FROM products
where product_ids REGEXP '^.*[^\d]605(?!\d).*$'
Comment: this is, by the way, a very good example why we shouldn't use multiple values in the same field!
Now once you have it - you can do whatever you want, you can play with it:
$new_product_ids = preg_replace('/^(.*[^\d])(605)(?!\d)(.*)$/','${1}new_id${3}',$row1['product_ids']);
and update the row:
update products set product_ids = '$new_product_ids' where id = $id
while ($row1 = mysql_fetch_array($r1, MYSQL_ASSOC)) {
if($row1['product_ids']){
$val_changed = false;
$prod_ids = $row1['product_ids'];
$ids = explode(',', $prod_ids);
for($i = 0; $i < count($ids); $i++) {
if($ids[$i] === '605') {
$ids[$i] = $new_id;
$val_changed = true;
}
}
if($val_changed) {
$prod_ids = implode(',', $ids);
//update db with new value $prod_ids
}
}
}
To get only records that have the id you're looking for, and use preg_replace to change the value, and update the table with the new value
$new_id = '999';
$new_val = preg_replace('/,605,/', $new_id, $row1['product_ids']);
Query with Regex (Fancy!):
SELECT * FROM products WHERE product_ids REGEXP '^[^0-9]605[^0-9]$';
Script to modify data:
while( $row1 = mysql_fetch_array( $r1, MYSQL_ASSOC ) )
{
$product_ids = explode( ',', $row1['product_ids'] );
if( ( $key = array_search( '605', $product_ids ) ) !== FALSE )
{
$product_ids[$key] = $new_id_number;
$product_ids = implode( ',', $product_ids );
// Enter Code to Update Table Here
}
}
$sql = "SELECT * FROM products";
$r1=$con->execute_query($sql);
while ($row1 = mysql_fetch_array($r1, MYSQL_ASSOC)) {
if($row1['product_ids']) {
$data = preg_split('/,/', $row1['product_ids']);
if(is_array($data)) {
foreach($data as $key => $value) {
if($value == 605) {
echo $value;
}
}
}
}
}
Check it out on CodePad
This is the best http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_find-in-set for denormalization problem