/    Sign up×
Community /Pin to ProfileBookmark

Explode problem

[CODE]$array_explode = explode(‘,’, $array);
for($i=0;$i<count($array_explode);$i++) {
if(!empty($array_explode[$i])) {
$sql = “SELECT sana, suom FROM adjektiivit WHERE sana = ‘$array_explode[$i]'”;
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$sana = $row[“sana”];
$suom = $row[“suom”];
echo “<p><b>” . $sana . “</b>&nbsp;” . $suom . “</p><br>”;
}
}
}
}[/CODE]

I have this kind of code. This code explodes a string. Then every word, which it has exploded from the string, should fetch a line from a mysql-table, but with my skills I don’t get it work. The first word from the string gets its line but the rest of the words don’t fetch anything. There is something wrong in the loop.

to post a comment
PHP

4 Comments(s)

Copy linkTweet thisAlerts:
@NogDogOct 15.2015 — I'm wondering if there is some white space after the commas? You could verify by doing the following right after the explode to see what's actually in the array:
[code=php]
die("<pre>".var_export($array_explode, 1)."</pre>");
[/code]

If that's the case, you could fix it by either using trim() on each element in the loop itself, or use preg_split(), something like:
[code=php]
$array_explode = preg_split('/s*,s*/', $array);
[/code]
Copy linkTweet thisAlerts:
@NogDogOct 15.2015 — Also, this sort of operation would be a good case for using an prepared statement and binding the param in the loop, instead of defining a new query in each iteration (assuming you're using PDO or the MySQLi extension?).
Copy linkTweet thisAlerts:
@rogkauthorOct 15.2015 — Thank you! I thought that the problem was in the code and I didn't think anything else. Yes, there was a space after every comma in the column of the table, but I took them off. Thank you, again. You saved my day. ?
Copy linkTweet thisAlerts:
@ginerjmOct 15.2015 — As suggested you should avoid doing a query inside a loop. You have an array already of your arg, why not use an "in($array)" instead of an = in your where clause and order the results by that value? One query - all your results. Just handle the break in 'keys' in your output loop.
×

Success!

Help @rogk spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.2,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,
)...