I am new to php and MySQL.
I am making a script on my website, that deals with mobile downloads.
I have 3 tables set up that I am dealing with here.
- d开发者_开发百科ownloads (contains info about a specific download, each with its own id).
- models (contains a list a possible device models(model names), each with its own id).
- downloads_models (linking table stating download_id = model_id, eg. (1,2) (1,3) (2,1)).
I have a simple query to display the models that support each specific download. It goes as follows:
$dlDetailsQuery = 'SELECT models.model
FROM models,downloads_models
WHERE downloads_models.modId = models.model_id
AND downloads_models.downId = "'.$pageId.'"
ORDER BY models.model ASC;
';
To display which models support the download, this line is echo
d:
$dpModSupport .= stripslashes($row['model']);
Now as an example, my page has a $pageId of "1" which is the download "example1", "example1" supports models 1(model1), 2(model2) and 3(model3). When$dpModSupport
is echo
d, it echoes as "model1model2model3"
.
My question is this: how do I get spacing, or a comma between the results?
What I am aiming for is an output of "model1, model2, model3".
I'm looking for a way to do this via php. I don't know whether a query can be structured to output spacing between results, so I'm guessing that php is the only solution there.
I do not want to add the spacing or commas into the model name field, or create a new field containing the spacing or commas along with the model's name.
Problem
By writing this in a loop:
$dpModSupport .= stripslashes($row['model']);
you're building up a string like this:
$dpModSupport .= stripslashes(<MODEL1>);
$dpModSupport .= stripslashes(<MODEL2>);
$dpModSupport .= stripslashes(<MODEL3>);
thus ending up with a string that's just the contents of each row splattered next to each other.
Solution
Instead, you could write this before your loop:
$dpModSupport = Array();
And then, inside it, instead of the line with .=
building up a string, build up the array:
$dpModSupport[] = stripslashes($row['model']);
Finally, to obtain output consisting of each element of said array, joined by a comma:
echo implode(', ', $dpModSupport);
I will leave it as an exercise to the reader to look up these functions and language features in the PHP manual.
Store the names in an array, and then join them at the end.
$dpModSupport = array();
$dpModSupport[] = stripslashes($row['model']);
echo implode(', ', $dpModSupport);
精彩评论