-1
<script type="text/javascript">
var category = new Array("category1", "category2");
</script>

My question is, I have this PHP query:

<?php $query = mysql_query("SELECT category FROM table ORDER BY category DESC") or die(mysql_error());
while($sql = mysql_fetch_assoc($query))
{
echo $sql['category'];
}
?>

How can I add $sql['category'] as the javascript "category"'s parameter?

2
  • Is it just one category or multiple? Commented Aug 5, 2013 at 14:39
  • Please note that the mysql_xxx() functions are deprecated and their use is discouraged. You should consider switching to a more modern API such as the PDO library. Commented Aug 5, 2013 at 14:40

3 Answers 3

2
<?php $query = mysql_query("SELECT category FROM table ORDER BY category DESC") or die(mysql_error());

$categories=array();
while($sql = mysql_fetch_assoc($query))
{
$categories[]= $sql['category'];
}

echo json_encode($categories);
?>
0

If it's just one:

<script type="text/javascript">
var category = new Array("category1", "category2", "<?php echo $category; ?>");
</script>

Else (though it will work for just one as well):

<?php $query = mysql_query("SELECT category FROM table ORDER BY category DESC") or die(mysql_error());
$categories = array();
while($sql = mysql_fetch_assoc($query))
{
    $categories[] = $sql['category'];
}
?>
<script type="text/javascript">
    var categories = new Array("<?php echo implode('","',$categories); ?>");
</script>
0

A number of ways to do that. An example can be:

<script type="text/javascript">
    var category = new Array(
        <?php
            while($sql = mysql_fetch_assoc($query))
            {
                echo "'{$sql['category']}'";
            }
        ?>
    );
</script>

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.