Jump to content

[SOLVED] list of items from mysql into a JS array?


galvin

Recommended Posts

Below, I get the list of 20 items back from my database, but how do I get them into the Javascript array? My code below is wrong, but I'm showing you where I'm stuck at.  Don't I have to loop through the $row array, or am I overcomplicating it?  The way the code is now, it's creating MANY arrays but i just want ONE array with those "items" in it. 

Any ideas?

 

$sql = "SELECT item
FROM listitems
WHERE listid = 1";
$result = mysql_query($sql, $connection);
if (!$result) { 
die("Database query failed: " . mysql_error());
} else {

while ($row = mysql_fetch_array($result)) {


echo "var randomAnimals=new Array(\"" . implode('"',$row['item']) . "\");";


}

Yeah, I know it was bad :)  Anyway, I'm closer now to what I need.  Question... When I do this..

echo "var beautifulWords=new Array(\"" . implode('"',$all) . "\");";

 

... I get...

 

var randomAnimals=new Array("mother"passion"smile"love"eternity"fantastic"destiny"freedom"liberty"tranquility"peace"blossom"sunshine"sweetheart"gorgeous"cherish"enthusiasm"hope"grace"rainbow");

 

How can I edit the first bit of code to get a closing quote and a comma after each word in the array? Or is that not doable and that's what you meant by CSV in DB is no good?

CSV = Comma Separated Values.

 

If you have the words in the DB one on each row instead of them all in one cell, this script is very easy! Do that first, then use this:

 

$sql = "SELECT item FROM listitems";
$result = mysql_query($sql, $connection) or die("Database query failed: " . mysql_error());

$output = 'var beautifulWords=new Array(';

while ($row = mysql_fetch_assoc($result)) {
     $output .= '"' . $row['item'] . '",';
}

$output = substr($output, 0, -1);
$output .= ');';
echo $output;

 

Tell me that wasn't easier.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.