简体   繁体   中英

How to import comma separated database values into an array

Rather then creating a db column for each value, I want to include them into one field, and then call those comma separated values into a PHP array to be called individually later.

Example; db value for 'data_set' is; 111, 222, 333

$sql_data = $get['data_set'];

$data_set = array ( $sql_data ); 

I want $data_set[0] to return 111, $data_set[1] to return 222, etc

Instead, it returns the entire db value, indicating that the import is not recognizing the comma separated values.

How can I fix this? Or is there a better approach?

I highly suggest using a one to many or many to many design for this rather than cramming the values into a single field. Doing this will cause issues in the future and maintenance will be a nightmare. If you provide a bit more information about what kind of data you're working with (What do the numbers represent? What uses the numbers?) I'd be happy to illustrate a more usable design.

That said, if you insist on having multiple values in a single field, you can use the PHP function explode() :

$data_set = explode(',', $sql_data);

Updated Answer Based On Comment

In that case, there are a few ways you could do this. If the properties are always in the same order and represent the same thing (and there are only 5-6), I'd recommend just breaking them out into separate columns and naming the columns appropriately.

If there are a lot of potential properties and they're variable, I'd recommend creating a profiles table, a properties table (just id and name), and a profilesToProperties table. That will allow the most flexible adjustments to properties over time. To get all properties for a given profile, you'd do something like:

SELECT prof.username, prop.name
FROM profiles prof
    LEFT JOIN profilesToProperties ptp ON prof.id = ptp.profile_id
    LEFT JOIN properties prop ON prop.id = ptp.property_id
WHERE prop.id = :id

This would still return profiles with zero properties.

What it can be used fore: Quiz webpage where every question have for example 4 different choice 1-4. The user goes to next question (program extracts numbers from field in db (4,4,2,4,1,3)) representing previous question answered, ads the number from present question to the string and update the field in db (4,4,2,4,1,3,1) With 50 questions it will otherwise be 50+ columns in the table for answers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM