I’m trying to figure out how and which is best for storing and getting multiple entries into and from a database. Either using explode, split, or preg_split. What I need to achieve is a user using a text field in a form to either send multiple messages to different users or sharing data with multiple users by enter their IDs like “101,102,103” and the PHP code to be smart enough to grab each ID by picking them each after the “,”. I know this is asking a lot, but I need help from people more skilled in this area. I need to know how to make the PHP code grab IDs and be able to use functions with them. Like grabbing “101,102,103” from a database cell and grabbing different stored information in the database using the IDs grabbed from that one string.
How can I achieve this? Example will be very helpful.
Thanks
If I understand your question correctly, if you’re dealing with comma delimited strings of ID numbers, it would probably be simplest to keep them in this format. The reason is because you could use it in your SQL statement when querying the database.
I’m assuming that you want to run a
SELECTquery to grab the users whose IDs have been entered, correct? You’d want to use aSELECT ... WHERE IN ...type of statement, like this:Alternatively, you could use
explodeto create an array of each individual ID, and then loop through so you could do some checking on each value to make sure it’s correct, before usingimplodeto concatenate them back together into a string that you can use in yourSELECT ... WHERE IN ...statement.Edit: Sorry, forgot to add: in terms of storing the list of user ids in the database, you could consider either storing the comma delimited list as a string against a message id, but that has drawbacks (difficult to do JOINS on other tables if you needed to). Alternatively, the better option would be to create a lookup type table, which basically consists of two columns:
messageid,userid. You could then store each individualuseridagainst themessageide.g.The benefit of this approach is that you can then use this table to join other tables (maybe you have a separate
messagetable that stores details of the message itself).Under this method, you’d create a new entry in the message table, get the id back, then explode the userids string into its separate parts, and finally create your
INSERTstatement to insert the data using the individual ids and the message id. You’d need to work out other mechanisms to handle any editing of the list of userids for a message, and deletion as well.Hope that made sense!