Question

Alright, so what I have is a very simple XAMPP setup with a database containing a single table with two rows. I have a php script that grabs one of these rows at random and then prints the resulting query in JSON. For whatever reason though the JSON has 'columns' (don't really want to call them columns because JSON can't have columns but, yeah..) that don't actually exist in the table.

I'm pretty new to everything in the XAMPP stack so I apologize in advance if this is a stupid question.

Here's my table:

enter image description here

Here's the resulting JSON:

{"0":"1","id":"0.9645465863538408","1":"Big Mac","name":"Big Mac","2":"A double layer of sear-sizzled 100% pure beef mingled with special sauce on a sesame seed bun and topped with melty American cheese, crisp lettuce, minced onions and tangy pickles.","description":"A double layer of sear-sizzled 100% pure beef mingled with special sauce on a sesame seed bun and topped with melty American cheese, crisp lettuce, minced onions and tangy pickles.","3":"http:\/\/www.mcdonalds.com\/content\/dam\/McDonalds\/item\/mcdonalds-Big-Mac.png","imgSrc":"http:\/\/www.mcdonalds.com\/content\/dam\/McDonalds\/item\/mcdonalds-Big-Mac.png","4":"2","upVotes":"2","5":"1","downVotes":"1","6":"0.9645465863538408"} 

("0", "1", etc. don't exist in the table)

here's my php:

$password = "";
$usertable = "mcdonalds"; 

//Connect
mysql_connect($hostname, $username, $password) OR DIE ("Unable to 
connect to $hostname . Please try again later.");
mysql_select_db($dbname);

//Fetch
$query = "SELECT * FROM `McDonalds`AS r1 JOIN(SELECT (RAND() *(SELECT MAX(id) FROM `McDonalds`)) AS id) AS r2 WHERE r1.id >= r2.id  ORDER BY r1.id ASC LIMIT 1";
$result = mysql_query($query);

$row = mysql_fetch_array($result);  
//Print
echo json_encode($row);

Was it helpful?

Solution

Use mysql_fetch_assoc instead of mysql_fetch_array. By default, mysql_fetch_array returns an array with both named and numeric indexes for each column.

Or you could use mysql_fetch_array($result, MYSQL_ASSOC). The default second argument is MYSQL_BOTH, which causes the result you see.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top