How to move comma seperated ids from one row to another row? - php

I have a database table like this
Id user_id folder product_ids
1 4 test1 2,3,4
2 4 test2 7,8,9
3 4 test3 10,11,12
Here I have saved product ids comma separated.Users have created their folders like this and wanted to move one or more products to another folder. Let say if user want he can select product id(8) and move it from test2 to test3 and the result set will look like this:
Id user_id folder product_ids
1 4 test1 2,3,4
2 4 test2 7,9
3 4 test3 10,11,12,8
How can I do it with sql and php?

Unfortunately, MySQL doesn't have a built-in REPLACE by REGEX :(
NOTE :
Please, update PRODUCT_TABLE by your Table Name
Here is a solution :
<?
/**
* #param String $folderSrc
* #param String $folderDst
* #param String $movedProductIds
* #param String $userId
* #return String Built SQL Query
*/
function buildSqlQueryMoveProductId ($folderSrc, $folderDst, $movedProductIds, $userId) {
return
"UPDATE PRODUCT_TABLE
SET PRODUCT_IDS =
CASE
WHEN FOLDER = '" . $folderSrc . "' THEN (REPLACE (REPLACE (REPLACE (PRODUCT_IDS, '," . $movedProductIds . "', ''), '" . $movedProductIds . ",', ''), '" . $movedProductIds . "', ''))
WHEN FOLDER = '" . $folderDst . "' THEN (CONCAT (IF (LENGTH(PRODUCT_IDS) > 0, CONCAT (PRODUCT_IDS, ','), '' ), '" . $movedProductIds . "'))
ELSE PRODUCT_IDS
END
WHERE USER_ID = " . $userId;
}
// Example
print moveProductId ('test1', 'test2', '3', 4);

Try not to store comma separated values in one column.
MySQL can perfectly handle large tables, so you could enter each product ID as a separate row.
You could also create multiple tables, say one holds the folder data.
Then another table could hold the primary keys of the folder table, along with the product IDs, and the user ID.
The more you store in a single table, the less organised it becomes.
I am not sure what's best performance-wise, but organisation is key, especially later on.
EDIT:
So let's say you create a table like this:
ID User_ID Folder Product_ID
1 4 test1 2
2 4 test2 7
3 4 test3 10
You could now simply look for the Product_ID, and UPDATE the folder name.
So when you pass the Product ID on to the update script, you could use a query somewhat like this:
UPDATE your_table_name SET Folder = :folder WHERE Product_ID = :pid
Then bind the folder name and product ID.
Please read this about PDO if you're unfamiliar with prepared statements.
I would recommend binding the values, as you're talking about user input, which can always be manipulated, causing a possible security breach.

<?php
/*Fetch your product ids and you will return sting of ids like "1,2,3,4,5,6,7"
*
*/
// product Ids. From where you want to remove id
$productOne="1,2,3,4,5";
// product Ids, From where you want to put id
$productTwo="6,7,8,9";
//product 1 array
$productOneArray=explode(",",$productOne);
//product 2 array
$productTwoArray=explode(",",$productTwo);
//Id which you want to change
$movingId = "5";
//Let's remove your product.
foreach ($productOneArray as $key=>$id){
if($id == $movingId){
unset($productOneArray[$key]);
}
}//BINGO !! you remove your id
//Add it to another product ids
array_push($productTwoArray,$movingId);
//Bingo You did it
//now turn both into string
$productOne=implode(",",$productOneArray);
$productTwo=implode(",",$productTwoArray);
//Update both the values in database
?>
If you need more help in hindi or gujrati, you can ask me.
If you want to move multiple ids
<?php
$name="parag";
if($name=="parag"){
echo uniqid().$name;
}
?>
<script>
$("div").css("width", "100px");
$("div").css("height", "100px");
</script>
<?php
echo "<pre>";
/*Fetch your product ids and you will return sting of ids like "1,2,3,4,5,6,7"
*
*/
// product Ids. From where you want to remove id
$productOne="1,2,3,4,5";
// product Ids, From where you want to put id
$productTwo="6,7,8,9";
//product 1 array
$productOneArray=explode(",",$productOne);
//product 2 array
$productTwoArray=explode(",",$productTwo);
//Id which you want to change
$movingId = "2,3,4";
$movingIdArray = explode(",", $movingId);
//Let's remove your product.
foreach($movingIdArray as $movingIds){
foreach ($productOneArray as $key=>$id){
if($id == $movingIds){
unset($productOneArray[$key]);
}
}//BINGO !! you remove your id
}
print_r($productOneArray);
//Add it to another product ids
array_push($productTwoArray,$movingId);
//Bingo You did it
//now turn both into string
$productOne=implode(",",$productOneArray);
$productTwo=implode(",",$productTwoArray);
//Update both the values in database
echo "productOne = ".$productOne."<br />";
echo "productTwo = ".$productTwo."<br />";
?>

Why don't you use json_encode() while adding product_ids.
When you insert product id just encode it and save. & while moving from folder read that json and decode it.
Add or remove respective ids from json then again save to database

You got answers on how to achieve this with php-code. But you really should normalize your database. A normalized database only contains tables where each table holds data describing a certain entity and relates to other entities through foreign-keys. You already did this by connecting your user-data through the foreign key "user_id", now move on and refactor your table to the other entities "folder" and "product".
Your final schema may look like this:
Table users
user_id
user_name
etc.
Table folders
folder_id
folder_name
user_id
etc.
Table products
product_id
folder_id
product_name
etc.
With this, to move a product from one folder to another, just change the folder_id of a record from products-table.
To fetch all products from one folder you use joins:
SELECT folders.*, products.* from products
JOIN folders on folders.folder_id = products.folder_id
WHERE folders.folder_id = your_desired_folder_id
Read more on database-normalization with lots of examples and reasons why to do this (despite the problems you are already facing) here:
http://www.dbnormalization.com/
Regards,
jojo

Related

PHP (and SQL) how to get given record

I have Data base "players" with:
id Name gold
1 joe 50
2 tom 40
3 jzd 70
I use a PHP to get info from base to variable:
$base = $connection->query("SELECT * FROM Players");
$data = $base->fetch_assoc();
When i use
$data['name'];
I get only a name FIRST id, how to get name for example id 2 or 3?
If you want to return the record for a specific user use
SELECT * FROM players WHERE id = <id>;
If you want to list all the players returned from your first query (select all, no where statement), you need to loop through the array returned from doing your query. Use a foreach (here are some examples

I need a Query with 2 dynamic values

i have an array where i can get id's from a database table, now i need to extract those values as i run a domain link array such as: domain.com/page?id=1
Now this page will bring a category, lets say A category with ID 1 i need to list items under this category on the same database table example products, i can use it without a filter now i need a filter using arrays, here is my code, thank you in advance.
$query ="SELECT * FROM tablename WHERE id = '".$id."' DESC";
before this i have on my php code:
$id = $_GET["id"];
So when i call from this table all comes out, but i need to filter where category 1 (example) have items, not all items with category 2, 3, 4 etc.
With my code i can get the item id as the link with array works fine for example: domain.com/page.php?id=1, but here is the catch, i get item id 1 and i need let's say category id 2, if i run the same link with id=2 i get item id 2 and that's not what i want.
I need to retrieve those values as arrays, any idea? Thank you in advance!
EDITED
Table structure example:
Items
ID, Name, Category
I need Category from Items as a filter like this: domain.com/?id=2&category=2
So i get all items under row Category only
Update your URI to something like this domain.com/page.php?id=1&category=2
$category = $_GET["category"];
$query ="SELECT * FROM tablename WHERE id = '".$id."' AND `Category` = '".$category."'";
Pass the query string parameter optionally
domain.com/page.php?id=1&category=2
Add the where clause dynamically like this
$query ="";
$conact =" where 1=1 ";
if(isset($_GET['id']))
{
$conact.=" and id=".$_GET['id'];
}
if(isset($_GET['category']))
{
$conact.=" and category=".$_GET['category'];
}
$query ="SELECT * FROM tablename $conact DESC";

Set Magento Product Group Permissions Programatically

When you edit a Product in Magento there is a Permissions tab with two multi-selects on it.
Disable product for
and
Hide product price for
We need to set the Disable product groups programatically by including 'Mage.php' and using a script to update the Disabled Groups.
For example we want to Disable a product for 10 specific groups for a product. We've been able to do pretty much everything else you can do in the Admin Interface in script so there should be a way to access this using Mage::getModel('catalog/product') or another Model. Call a function, pass in the group ID's you want to set the product to disabled for.
But can't seem to track it down.
Thanks!
Found where the data is stored in the database and just ended up modifying the database directly.
$groupsDisabledArray is an array that contains an ID for each group I want to disable product permissions for. The data in magento is simply stored as a comma separated list of Group ID's
Example:
1,2,3,4,5,6,7,8,9,10
So I implode my disabled group ID's array to get a comma separated list
$groupsList=implode(",", $groupsDisabledArray);
Then either insert or update the catalog_product_entity_text table which is where the value is stored.
The value is stored in catalog_product_entity_text where
entity_id = PRODUCT_ID
attribute_id = 155 (This corresponds to the table eav_attribute where attribute_code = 'aw_cp_disable_product')
entity_type_id = 4 (This corresponds to table eav_entity_type where entity_type_code = 'catalog_product')
store_id = STORE_ID (If you just have one store you should just be able to put 0 here for the Default Store)
Code to do the complete update below. May need to update the path to Mage.php depending where you put your script.
include("/app/Mage.php");
/* Get DB Connections */
$resource = Mage::getSingleton('core/resource');
$readConnection = $resource->getConnection('core_read');
$writeConnection = $resource->getConnection('core_write');
$tableName = $resource->getTableName('catalog_product_entity_text');
/* $groupsDisabledArray - Array of all of the Magento Group ID's I want to disable this product for */
$groupsList=implode(",", $groupsDisabledArray);
$sql="SELECT * FROM $tableName WHERE entity_id=$product_id AND attribute_id=155 and entity_type_id=4 AND store_id=0;";
$results = $readConnection->fetchAll($sql);
if (count($results) > 0) {
$sql="UPDATE $tableName SET value='$groupsList' WHERE entity_id=$product_id AND attribute_id=155 and entity_type_id=4 AND store_id=0;";
}
else
{
$sql="INSERT INTO $tableName (entity_id, entity_type_id, store_id, attribute_id, value) VALUES ($product_id, 4, 0, 155, '$groupsList')";
}
$writeConnection->query($sql);

Pull a data from db where each array holds the column name category and its subinfo

I am trying to create an accordion menu where each accordion menu pulls the rutines of workouts where it differs by the category column in the db example below;
I got my PDO::db design like this;
id
title
describtion
category
hashtags
video
seen
date_published
how can i pull the info from the database by the category to use it in foreach in my view file. I hope i could make my problem clear enough.
thanks in advance.
You could order by category and then name (make sure you have an index on category, name)
Your Query would be:
SELECT * FROM `workouts` ORDER BY category, name
Then when you iterate you check if the category changed and if, close the sublist and open a new one showing the category first.
Another, slightly cleaner Solution would be to iterate twice, using the first loop to sort in an associative array by category:
$sth = $dbh->prepare("SELECT * FROM workouts");
$sth->execute();
$workouts = array();
/* First Loop */
while(($result = $sth->fetch(PDO::FETCH_ASSOC)) !== FALSE) {
$workouts[$result['category']][] = $result;
}
Now you can loop over $workouts, using the key as the Category.
foreach($workouts as $category => $workoutsByCategory) {
//display category and start subset
foreach($workoutsByCategory as $workout) {
//display workout
}
}
It would be a lot cleaner thou to use a second table which holds the category names and use the id of that table in your workouts table to connect. You can then get the results using join. You might want to look into Relational Database Design and Normalization
Example (not tested) Table Layouts:
table "workouts"
id | category_id | title | description | hashtags | video | seen | date_published
table "categories"
id | title
Then you can get the results using:
SELECT workouts.*, categories.title as category_title FROM workouts LEFT JOIN categories ON (category.id = workouts.category_id)
This will make it easier to change the name of a category amongst other advances ... but you'll read up on that i guess.

How can i search all tables for a specific node value's parent_id?

There are several other posts like this but none which match my specific parameters/needs.
How do i find the parent_id associated with one of 50 different outputted query results a user could click on?
Like, if the user clicks on "Transportation" I need code that can find the parent_id corresponding to the transportation node.
Problem is, my data is structure over multiple tables, so if they click on a link I don't necessarily know which table to search.
Essentially what I want is SELECT parent_id FROM * WHERE * = communication
But I can't * for parameters such as table name.
So how do I create code to automatically find the parent_id of a specific query once the user selects it?
There must be a better option than listing all my 20 tables in the query parameters?
Should I restructure my data into 1 table?
You have to search each table for the parent_id. If you want shorter codes, you can try this:
<?php
$tables = mysql_query('SHOW TABLES');
while($table = mysql_fetch_row($tables)){
$queries[] = 'SELECT parent_id FROM `' . $table[0] . '` WHERE method=\'Transportation\'';
}
$result = mysql_query(implode(' UNION ', $queries));
?>

Categories