简体   繁体   中英

How to get data from MySQL database with PHP?

I am trying to connect to a MySQL database and echo a variable that's created from the data. Here's my code:

<?php
// Connects to Our Database 
mysql_connect("localhost", "escalat1_local", "database88") or die(mysql_error()); 
mysql_select_db("escalat1_local") or die(mysql_error()); 

$query = "SELECT * FROM cities ORDER BY RAND() LIMIT 1";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
$variable= print_r($row); // This will show it to you 
echo $variable;
?>

This is how it's being displayed:

Array ( [0] => white haven center ) 1

How do I make it just display this?

white haven center

Thanks for your time.

This line i think must have a bug :

$row = mysql_fetch_array($row); 

Must be changed to :

$row = mysql_fetch_array($result);

If I understand it well, it should be really simple:

echo $row[0];

Also that print_r is not needed.

use $row = mysql_fetch_array($result);

instead of $row = mysql_fetch_array($row);

This is how you do it (you said your column is also called cities) :

$result = mysql_query("SELECT cities FROM cities ORDER BY RAND() LIMIT 1");
$row = mysql_fetch_array($result);
echo $row["cities"];

FYI as of PHP 5.5.0 mysql_* functions are depreciated. Hope it helps.

This is just for one row if you want to do it for all rows then you have to create a for loop

Array ( [0] => white haven center ) 1
echo $row[0];
//output-> white haven center

At the end of your code,

Simply change

echo $variable;

to

echo $variable[0];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM