explode and check if exist - php

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...

$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

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
}
}

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

Related

Fetch Mysql Results into serialized data

I have this table:
| id | related_id |
| 1 | 100 |
| 1 | 200 |
| 1 | 300 |
| 2 | 400 |
| 2 | 500 |
| 2 | 600 |
I need to retrieve serialized data as:
a:3:{i:1;s:3:"100";i:2;s:3:"200";i:3;s:3:"300";}
Query
SELECT id, related_id from mytable where id = 1;
I'm trying to get this using 'while'
$result = $link->query($query);
$item = array();
while($f = $result->fetch_assoc()){
$id = $f['id'];
if ($id == $f['id']){
$item[] = $f['related_id'];
}
print serialize($item);
break; // for test
}
SOLUTION that works for me (provided by Erwin - Thanks!)
$item = array();
while($f = $result->fetch_assoc()) {
$id = $f['id'];
if (!array_key_exists($id, $item)) {
$item[$id] = [1 => $f['related_id']];
} else {
$item[$id][] = $f['related_id'];
}
}
foreach ($item as $value) {
print serialize($value) . PHP_EOL;
}
Collect first each related_id and store to id array with your while loop. Then print each using foreach.
$item = array();
while($f = $result->fetch_assoc()) {
$id = $f['id'];
if (!array_key_exists($id, $item)) { // create id array if not exist
$item[$id] = [1 => $f['related_id']]; // To start with index 1
} else {
$item[$id][] = $f['related_id']; // Push each new related_id
}
}
foreach ($item as $value) {
print serialize($value); // Print each serialized
echo '<br>'; // New line
}
What you are trying to do is something like this:
$result = $link->query($query);
$items = array();
while($f = $result->fetch_assoc()){
$id = $f['id'];
if(!isset($items[$id])) {
$items[$id] = array();
}
$items[$id][] = $f['related_id'];
}
foreach($items as $item) {
print serialize($item);
}
For your serialized string, you have to work with an array with related_id in the second layer. The first layer is to save all related_id in an array with the same id.
You have 6 rows, 3 have id 1 and 3 have id 2. You are specifying that you want to use these ids as array keys so you will end up with 2 arrays, each holding 3 values.
If you want each row in its own array you do this:
while($f = $result->fetch_assoc()){
$item[] = array($f['id'] => $f['related_id']);
}

Remove Duplicates in while loop PHP

I'm trying to remove duplicate results from my SQL query using PHP.
table categories:
id | name
1 | sony
2 | nintendo
table subcategories:
id | name | category_id
1 | playstation | 1
2 | playstation2 | 1
3 | wii | 2
table video_games
id | name | subcategories
1 | grand theft auto | 1,2
2 | super mario | 3
My PHP code:
$query = $database->query('SELECT id FROM subcategories WHERE category_id = "'.$_GET['id'].'"');
while($return = $query->fetch()) {
$subcategories = $return['id'];
$request = '%'.$subcategories.'%';
$game_query = $database->prepare('SELECT * FROM video_games WHERE subcategories LIKE :request');
$game_query->bindValue('request', $request);
$game_query->execute();
if($game_query->rowCount() > 0) {
while($game_return = $game_query->fetch()) {
echo $game_return['name'];
}
}
}
My code works but I have duplicate video games when there have multi subcategories.
I tried using SELECT DISTINCT * FROM video_games WHERE subcategories LIKE :request but same problem.
Any idea to remove duplicate results using SQL or PHP ?
MySql is able to solve this problem by its own means.
Use 'DISTINCT' and 'FIND_IN_SET'.
Like this:
"SELECT DISTINCT
vg.id,
vg.name,
vg.subcategories
FROM
video_games vg
WHERE
FIND_IN_SET( (SELECT id FROM subcategories WHERE category_id='".$_GET['id'])."' , vg.subcategories ) > 0 "
and also you can use array_unique at first save video game names in an array and next remove duplicate value.
.
.
.
your code
.
.
$game_query->execute();
if($game_query->rowCount() > 0) {
$fetch =array_unique($game_query->fetch());
foreach ($fetch as $key => $value){
echo $value;
}
}
test
<pre>
<?php
$arr=array("name"=>"1","name2"=>"2","name1"=>"2","name3"=>"3","name4"=>"1","name5"=>"2","name6"=>"3","name7"=>"22");
print_r($arr);
$fetch =array_unique($arr);
print_r($fetch);
foreach ($fetch as $key => $value)
echo $key."=>".$value."<br>";
?>
</pre>
You can save video game names in an array, and print it afterwards. For example:
$games = array();
$query = $database->query('SELECT id FROM subcategories WHERE category_id = "'.$_GET['id'].'"');
while($return = $query->fetch()) {
$subcategories = $return['id'];
$request = '%'.$subcategories.'%';
$game_query = $database->prepare('SELECT * FROM video_games WHERE subcategories LIKE :request');
$game_query->bindValue('request', $request);
$game_query->execute();
if($game_query->rowCount() > 0) {
while($game_return = $game_query->fetch()) {
if (!in_array($game_return['name'], $games)) {
$games[] = $game_return['name'];
}
}
}
}
//now print the games
foreach ($games as $game) {
echo $game;
}
EDIT If you want more than just 'name', you can expand $games array with $key => $value combination. For example:
. . .
while($game_return = $game_query->fetch()) {
foreach ($games as $game) {
if ($game['name'] === $game_return['name']]) {
continue 2;
}
}
$games[] = array(
'name' => $game_return['name'],
'price' => $game_return['price'],
)
}
And afterwards print it like:
foreach ($games as $game) {
echo $game['name'];
echo $game['price'];
}

Assign variables from array

I created a settings table in my database and I would like to assign value to a variable based on the setting and I'm not sure how to go about doing it.
table: settings
id | setting | value
1 | setting_one | value_one
2 | setting_two | value_two
3 | setting_three | value_three
Query
if ($result = $db->query("SELECT * FROM settings")) {
while($row = mysqli_fetch_assoc($result)) {
$SettingOne = $row['setting_one'];
$SettingTwo = $row['setting_two'];
$SettingThree = $row['setting_three'];
}
}
The select will return you 3 rows, assuming your table has only 3 rows in it
that is why you process the result in a while lop.
Each $row will contain an Assoc array in the form of the columns that you selected in your query.
In this case as you use SELECT * the $row array will contain 3 occurances
id, setting, value
So your loop should look like
if ($result = $db->query("SELECT * FROM settings")) {
while($row = mysqli_fetch_assoc($result)) {
$id = $row['id'];
$setting = $row['setting'];
$value = $row['value'];
echo "The id = $id, the setting = $setting, the value is $value <br>";
}
}
This will produce you 3 lines of output, assuming you only have 3 rows in your table
I got it figured out and just echo the row['setting'] as $setting for each :)
if ($result = $db->query("SELECT * FROM settings")) {
while($row = mysqli_fetch_assoc($result)) {
$key = $row['setting'];
$$key = $row['value'];
}
$result->free();
$result->close();
}

Get each category id from column table with separate comma to show value

I realy need help to fix this code. Actualy I want get gcm_id from table where the user selects several category from table category. An example of what I want main point is gcm_id data
"gcm_id will show if user select category A,B,C" etc.. How do I do this in php mysql. I try FIND_IN_SET with no luck
uid | email | gcm_id | app_type | categories
1 demo#gmail.com xzxzxzxz A 2,5,6
How get gcm_id if user have been select categories id 2,5, and 6?
the code :
if (!empty($cat)) {
foreach ($cat as $key => $value) {
$wc.="FIND_IN_SET('$value',categories) > 0 OR ";
}
}
$pos = strrpos($wc, "OR");
if ($pos !== false) {
$wc = substr_replace($wc, "AND", $pos, strlen("OR"));
}
$wc.=" is_active=1";
$q = "select * from datanotif where app_type='$type' AND $wc ";
$r = mysqli_query($mysqli,$q);
$users = array();
while ($row1 = mysqli_fetch_assoc($r)) {
$users[] = $row1;
}
$ids = array();
foreach ($users as $key => $value) {
$ids[] = $value['gcm_id'];
}

PHP show the most popular tags

I have a database like this:
+----+---------------------+
| id | tags |
+----+---------------------+
| 1 | test1, test2, test3 |
| 2 | test1, test2, test3 |
| 3 | test1, test2, test3 |
| 4 | test1, test2, test3 |
| 5 | buh1, buh2, buh3 |
+----+---------------------+
Now i want to display the most popular tags from this database. I have a function, and it works with a array like this:
$tag_array = array(
'test1, test2 test, test3',
'test2, test4, test2',
'buh, buh2, buh3' );
The function:
function popularTags($tag_array) {
$p = array();
foreach($tag_array as $tags) {
$tags_arr = array_map('trim', explode(',', $tags));
foreach($tags_arr as $tag) {
$p[$tag] = array_key_exists($tag, $p) ? $p[$tag]+1 : 1;
}
}
arsort($p);
return $p;
}
This is how to display the most popular tags:
foreach(popularTags($tag_array) as $tag=>$num)
{
echo $tag, " (", $num, ")<br />";
}
This works so far, with a normal array.
Now, i want to get the tags from the Database, so i extract the values from the database and run the function like this:
$result = mysql_query("select * from DB ORDER BY date DESC");
while($row = mysql_fetch_array($result)){
$tag_array = $row["$tags"];
foreach(popularTags($tag_array) as $tag=>$num)
{
echo $tag, " (", $num, ")<br />";
}
}
This give me an error though:
Warning: Invalid argument supplied for foreach()
So my question is how to show the most popular tags from the database with this function?
Thanks
My suggestion is that you normalize your database. Then a query like this becomes trivial, as well as much better performing.
select TagID, count(*)
from EntityTag
group by TagID
order by count(*) descending
limit 5
mysql_fetch_array returns all the rows. So do this:
$rows = mysql_fetch_array($result);
foreach($rows as $row) {
$tag_array = $row["tags"]; // note removing the $
foreach(...) {
}
}
This one works for me:
$result = mysql_query("select tags from DATABASE LIMIT 20");
$tags = array();
while ($row = mysql_fetch_array($result)) {
$row_tag_array = split(",", $row[0]);
foreach ($row_tag_array as $newtag) {
asort($row_tag_array);
if (array_key_exists($newtag, $tags)) {
if ($tags[$newtag] < 200) {
$tags[$newtag] = $tags[$newtag] + 20;
}
}
else {
$tags[$newtag] = 100;
}
}
}
foreach ($tags as $tag => $size) {
echo "<a style=\"font-size: $size%;\" href=\"?t=$tag\">$tag</a> ";
}
Thank you for your help though

Categories