php查询mysql数据库并将结果保存到数组的方法。具体分析如下:
创新互联专业提供成都主机托管四川主机托管成都服务器托管四川服务器托管,支持按月付款!我们的承诺:贵族品质、平民价格,机房位于中国电信/网通/移动机房,达州主机托管服务有保障!
主要用到了mysql_fetch_assoc函数
mysql_fetch_assoc语法如下:
?
1
array mysql_fetch_assoc (resource $Result_Set)
范例代码如下:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
?php
$UserName = 'abc';
$Password = '1234';
$DbHandle = mysql_connect ('localhost', $UserName, $Password);
if (!$DbHandle) {
die 'No database connection could be established.';
}
$DBName = 'w3db;
if (!mysql_select_db ($DBName, $DbHandle)) {
die 'Database could not be selected.';
}
$Query = "SELECT ISBN, Title, Author FROM articles";
$articles = mysql_query ($Query, $DbHandle));
while ($Row = mysql_fetch_assoc ($articles)) {
echo "ISBN = $Row['ISBN']br /\n";
echo "Title = $Row['Title']br /\n";
echo "Author = $Row['Author']br /\n";
}
?
$str='{"data":[{"name":"111","img":"748.jpg","dz":"uang","sz":"22"},{"name":"222","img":"888.jpg","dz":"ngzhu","sz":"13"},{"name":"333","img":"999.jpg","dz":"ve","sz":"27"}]}';
$json=json_decode($str,true);
echo $json['data'][0]['name']."br /";
echo $json['data'][0]['img']."br /";
echo $json['data'][0]['dz']."br /";
echo $json['data'][0]['sz']."br /";
//或者
$json=json_decode($str);
echo $json-data[0]-name."br /";
echo $json-data[0]-img."br /";
echo $json-data[0]-dz."br /";
echo $json-data[0]-sz."br /";
数据库提到的数据一般是资源类型的,要逐一读出,添加到数组
while($row = mysql_fetch_assoc($res)){
$data[] = $row;
}
遍历数据表,把相应的数据放到数组中即可
例如:
?php
//定义一个数组,用于保存读取到的数据
$contents = array();
$query = mysql_query("select * from table");
//遍历数据表
while($array = mysql_fetch_array($query)){
$contents[] = $array;
}
print_r($contents);
//然后循环数组,或者通过键名使用数组
foreach($contents as $value){
print_r($value);
}
echo $contents[0]['字段名称'];
?