Php mysql array question

Hi

I am currently setting up a sort of flash game.
I’ve managed to get data from a php file to display in my flash file which is ideal.

I also have a php script that will randomly display a value form an array.
The bit I’m confused about is getting a php file to select the data I need form the database and show it as an array so that my php file will randomly display one value which will in turn be read into the flash file and displayed.

Can anyone tel me how I set up a script to select data from a mysql table and put it into an array please?

I think its something fairly easy to do I’m just driving myself crazy trying to work it out!!

Any help as always much appreciated.

Thanks in advance.

Well, it depends on how you format the array to use in flash, but here’s an example on how to obtain a random row from your database/schema.


<?php
$con = mysqli_connect('host', 'anthony', 'password', 'schema', 3306);
$sql = 'SELECT value FROM table ORDER BY RAND() LIMIT 1;';
$res = mysqli_query($con, $sql);
$row = mysqli_fetch_assoc($res);
?>

$row is now an associative array containing the row data. :slight_smile:

What method are you using to get the array? Something like fetch_assoc is already an array… then you can use [URL=“http://us2.php.net/manual/en/function.array-rand.php”]array_rand() or [URL=“http://us2.php.net/manual/en/function.shuffle.php”]shuffle() to mix/pick.

Thanks for the super quick reply!

My table is set up like so:

Item, Remaining

There are 5 different rows in the table. I need the array to display and items that have a remaining value greater than 0.

Here’s the php file that I have set up which shows the array with static values in it.

$input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank");
$rand_keys = array_rand($input, 2);
echo $input[$rand_keys[0]] . "\
";

Could you tell me how I would go about using the code you have above to get the above format of array from the dynamic data please?

Thanks in advance.


<?php
$con = mysqli_connect('host', 'anthony', 'password', 'schema', 3306);
$sql = 'SELECT item FROM table WHERE remaining > 0 ORDER BY RAND() LIMIT 1;';
$res = mysqli_query($con, $sql);
$row = mysqli_fetch_assoc($res);
echo $row['item'] . "\
" ;
?>

Sorry Anthony I think I’m being a bit thick with this. I can’t get your code to work and I think it might be due to the version of php the server is running. I’m getting the following error:

Fatal error: Call to undefined function: mysqli_connect()

Any ideas?

Ah, OK. :slight_smile:


<?php
$con = mysql_connect('host', 'anthony', 'password');
mysql_select_db('schema', $con);
$sql = 'SELECT item FROM table WHERE remaining > 0 ORDER BY RAND() LIMIT 1;';
$res = mysql_query($sql, $con);
$row = mysql_fetch_assoc($res);
echo $row['item'] . "\
" ;
?>

Excellent, thanks very much for all your help.