Fetch Mysql Results into serialized data - php

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']);
}

Related

How to select and assign to a specific $key, a specific $value, among multiple choices?

I have a MySQL table with multiple columns, from which I need to select all of them of each record, and to create a specific $key=>$value from it.
for example
TABLE
ID | group_cat | group_sec | group_name | enabled | sent
-------------------------------------------------------------------------------------
1 | C | sct_a | Project_A | 1 | no
2 | C | sct_b | Project_B | 1 | no
3 | P | sct_c | Moderators | 1 | no
4 | C | sct_d | Ambassad | 1 | no
5 | P | sct_e | PMP | 0 | no
The MySQL query I need is "SELECT * FROM groups WHERE sent = 'no' "
By PHP is
PHP Code
$query = "SELECT * FROM `groups` WHERE `sent`= 'no' ";
$sth = $sql->prepare($query);
$sth->execute();
while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
foreach($row as $key => $value) { $$key = $value; }
...
...
...
}
Here my question:
I need that the $key is from the column 'group_sec' and the related $value is from the column 'group_name'. So that the couple $$key=>$value can return this result (for instance)
echo $sec_b;
returns: Project_B
Could you help me to get this done please?
Thank you in advance
This will do the job for you:
${$row['group_sec']} = $row['group_name'];
echo $sct_b;
Output:
Project_B
You would use this in your while loop (the foreach can probably be deleted):
while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
${$row['group_sec']} = $row['group_name'];
...
// do something with $sct_b
...
}
Alternatively, if your column names might change, but the positions will stay the same, you can use
while($row = $sth->fetch(PDO::FETCH_NUM)) {
${$row[2]} = $row[3];
...
// do something with $sct_b
...
}
You can build an array based on key and value you prefer using $row['group_sec'] for key and $row['group_name'] eg:
$query = "SELECT * FROM `groups` WHERE `sent`= 'no' ";
$sth = $sql->prepare($query);
$sth->execute();
while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
$myArray[$row['group_sec']] = $row['group_name'];
}
and you can see the result
foreach($myArray as $key => $value){
echo $key . ' - ' . $value . '<br>';
}
$sql = "SELECT * FROM groups WHERE sent= 'no'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$list=[];
while($row = $result->fetch_assoc()) {
$list{$row['group_sec']} = $row['group_name'];
}
}

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();
}

Dynamic Multi Dimensional Array

I have been trying to fureout how to create a dynamic multi dimensional array.
The reason for this is that I want to create a dropdown menu that will be created dynamically from the mysql
Sample database
|id|menu_name|menu_parent_id|
|1 |top menu1| 0 |
|2 |top menu2| 0 |
|3 |top menu3| 0 |
|4 |top menu4| 0 |
|5 |sub menu | 2 |
|6 |sub menu | 2 |
|7 |sub menu | 5 |
|8 |sub menu | 6 |
|9 |top menu | 0 |
I thought of starting from getting the menu with no parent then put it on an array
$parentIDs[0]=0;
$tempParentIDs = array();
$childIDs = array();
$menus = array();
$rows = 0;
$rows=0;
foreach($parentIDs AS $value){
$sql = mysql_query("SELECT * FROM service WHERE service_parent_id=$value");
while($temp = mysql_fetch_array($sql)){
//$tempParentIDs[] = $temp['service_id'];
//check if parent have child
$sql2 = mysql_query("SELECT * FROM service WHERE service_parent_id=$temp[service_id]") or die(mysql_error());
$rows = mysql_num_rows($sql2);
if($rows >= 1){
//This means there is a child
while($temp2 = mysql_fetch_array($sql2)){
$childIDs[] = $temp2['service_id'];
}
$tempParentIDs[$temp['service_id']] = $childIDs;
unset($childIDs);
} else {
//This means there is no child
}
}
}
echo "<pre>";
print_r($tempParentIDs);
echo "</pre>";
but after then I'm stuck.
I think you are looking for this:
$parentIDs[0]=0;
$tempParentIDs = array();
$childIDs = array();
$menus = array();
$rows = 0;
$multiDimensionalArray = NULL; //here I made change - vijay
$rows=0;
foreach($parentIDs AS $value){
$sql = mysql_query("SELECT * FROM service WHERE service_parent_id=$value");
while($temp = mysql_fetch_array($sql)){
$tempParentIDs = $temp['service_id']; //here I made change - vijay
//check if parent have child
$sql2 = mysql_query("SELECT * FROM service WHERE service_parent_id=$temp[service_id]") or die(mysql_error());
$rows = mysql_num_rows($sql2);
if($rows >= 1){
//This means there is a child
while($temp2 = mysql_fetch_array($sql2)){
$multiDimensionalArray[$tempParentIDs][] = $temp2['service_id']; //here I made change - vijay
}
// $tempParentIDs[$temp['service_id']] = $childIDs; //here I made change - vijay
// unset($childIDs); //here I made change - vijay
} else {
//This means there is no child
}
}
}
echo "<pre>";
print_r($multiDimensionalArray); //here I made change - vijay
echo "</pre>";
You should store array in php like this way :
This will maybe work for you
$next = 0;
$level = 0;
$sql = mysql_query("SELECT * FROM service WHERE service_parent_id=$next");
$temps = array();
while($temp = mysql_fetch_array($sql))
{
$temps[] = $temp;
}
foreach($temps as $temp)
{
echo $temp['service_id'];
}

explode and check if exist

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

Categories