Splitting and Running a code in PHP
I am currently working on a project where people write articles, which are stored in a database. The credit for the article is stored as [USER ID]:Role
and then loaded into the page by loading the user information from another table using the USER ID then implementing the role into the credit.
For example: 1:Writing
would produce Brad - Writing
But as there are multiple credits per page they will be stored in the same column separated by a comma. For example: 1:Writing,4:Images,8:Music
which would then appear as
Brad - Writing
Ben - Images
Jay - Music
To do this I am exploding the contents of the column with the separator ,
and then running a foreach();
on the array.
In this foreach();
I need to look up the ID's of the users then load the information from the table and then include the Role as well in the credit.
I can't think of the best way to do this. Would I need to run a preg_replace
to run a separate function to get the information or would there be another way to do it? Or would there even 开发者_高级运维be a better way to store the information in the database?
Thanks in advance, Brad.
You can store them in MySQL in a separate table
article_id user_id role
---------------------------
Brad | 1 | Writing
and then issue a query like this
SELECT u.name, ac.role FROM article_credits ac
LEFT JOIN users u ON ac.user_id = u.id
WHERE ac.article_id = ?
Or you can extract it from your current field using preg_match
to catch all user_id
s and feed them to
SELECT * FROM users WHERE users.id IN (' . implode(',', $user_ids).')'
Do all the things you are doing but don't run query to load information from table in foreach loop instead you can use:
$query = "Select * from table where id in ('" . implode("','", $columns) . "')";
then execute query
精彩评论