php从查询中匹配的数据库中获取所有值
I am new to PHP. I have a problem in my PHP code. In MySQL, I have my database like this:
CREATE TABLE IF NOT EXISTS `propertylocator` (
`store_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`store_name` varchar(255) NOT NULL,
`country_name` varchar(255) NOT NULL,
`state_name` varchar(255) NOT NULL,
`city_name` varchar(255) NOT NULL,
`address` varchar(255) NOT NULL,
`description` varchar(255) NOT NULL
PRIMARY KEY (`store_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=4 ;
INSERT INTO `propertylocator` (`store_id`, `store_name`, `country_name`, `state_name`, `city_name`, `address`, `description`) VALUES
(1, 'My property1', 'India', 'uttar pradesh', 'Ghaziabad', 'Pilkhuwa, Uttar Pradesh 245304, India', 'this is demo test','this is dummy description'),
(2, 'My new Property', 'India', 'Maharashtra', 'Thane', 'Kudavali, Maharashtra 421401, India', 'test propery again', 'another dummy property'),
(3, 'Dummy store', 'United Arab Emirates', 'Sharjah', 'Halwan Suburb', 'Al Ghubaiba - Sharjah - United Arab Emirates', 'this is another dummy store','another text with dummy');
Now I want to show all the city_names
whose country_name
is India
. For that I made a simple query in phpMyAdmin like this:
SELECT `city_name` FROM `ps_storelocator` WHERE `country_name`= 'india'
and it showed me two results
Ghaziabad
Thane
Now when I tried to fetch this from my php code. It showed only one value. The code was like this
$host = "localhost";
$user = "root";
$pass = "";
$databaseName = "stores";
$tableName = "propertylocator";
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
$result = mysql_query("SELECT `city_name` FROM `propertylocator` WHERE `country_name`= 'india'");
$arrayvalue = mysql_fetch_array($result);
print_r($arrayvalue);
Now I am getting the value like this
Array
(
[0] => Ghaziabad
[city_name] => Ghaziabad
)
Can someone kindly tell me how to get those two values from database? Any help and suggestions will be really appreciable.
You fetched the first row the the data and displayed it, which is what your code said.
if you want to display multiple rows, folks generally do it inside a loop like the following:
while($arrayvalue = mysql_fetch_array($result))
{
print_r($arrayvalue);
}
This runs the code inside the while loop for each row that is fetched from the database.
Also, the reason you (appear to have) two entries for the same row of data is that you are using the fetch_array function - which returns the data in both an indexed array and an associative one.
$result = mysql_query("SELECT city_name FROM ps_storelocator WHERE country_name= 'india'");
while($row = mysql_fetch_array($result))
{ echo $row['city_name'];}
Try like this..