//记得端口别写错
$con = mysql_connect("localhost:3306","wscats","123456789");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("ws", $con);
//SQL语句对大小写不敏感,所以SELECT与select等效
$result = mysql_query("select * from news");
$data = array();
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
//array_pop() 删除数组的最后一个元素(出栈)
//array_push() 将一个或多个元素插入数组的末尾(入栈)
array_push($data ,$row);
}
$apiData = array("news"=>$data);
//输出jsonp数据 {"news":[{"title":"qqqqaaa","text":"sssqweqweaaa","id":"29","source":"qqqqqwe"},{"title":"asdsasd","text":"asdasd","id":"31","source":"asdasd"},{"title":"123213qwewe","text":"123123qweqwe","id":"32","source":"12323qeqe"},{"title":"qweqwe","text":"qweqwe","id":"33","source":"qwqwe"}]}
echo json_encode($apiData);
//例如Array ( [title] => qqqqaaa [text] => sssqweqweaaa [id] => 29 [source] => qqqqqwe )
$result2 = mysql_query("select * from news where id = 29");
print_r(mysql_fetch_assoc($result2));
//例如Array ( [0] => qqqqaaa [1] => sssqweqweaaa [2] => 29 [3] => qqqqqwe )
$result3 = mysql_query("select * from news where id = 29");
print_r(mysql_fetch_row($result3));
$result4 = mysql_query("select * from news");
while ($row = mysql_fetch_object($result4)) {
echo $row->title."<br />";
}
<?php
//记得端口别写错
$con = mysql_connect("localhost:3306","wscats","123456789");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("ws", $con);
$result = mysql_query("select * from news");
//1.mysql_fetch_array(data,array_type) 从结果集中取得一行作为关联数组,或数字数组,或二者兼有
//注意第二个参数是常量,不是字符串
/*MYSQL_ASSOC - 关联数组
MYSQL_NUM - 数字数组
MYSQL_BOTH - 默认。同时产生关联和数字数组*/
$data = array();
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
//var_dump($row);
//echo '<br />';
//array_pop() 删除数组的最后一个元素(出栈)
//array_push() 将一个或多个元素插入数组的末尾(入栈)
array_push($data ,$row);
}
$apiData = array("news"=>$data);
//输出jsonp数据 {"news":[{"title":"qqqqaaa","text":"sssqweqweaaa","id":"29","source":"qqqqqwe"},{"title":"asdsasd","text":"asdasd","id":"31","source":"asdasd"},{"title":"123213qwewe","text":"123123qweqwe","id":"32","source":"12323qeqe"},{"title":"qweqwe","text":"qweqwe","id":"33","source":"qwqwe"}]}
echo json_encode($apiData);
//2.mysql_fetch_assoc 从结果集中取得一行作为关联数组
//例如Array ( [title] => qqqqaaa [text] => sssqweqweaaa [id] => 29 [source] => qqqqqwe )
$result2 = mysql_query("select * from news where id = 29");
print_r(mysql_fetch_assoc($result2));
//3.mysql_fetch_row() 函数从结果集中取得一行作为数字数组
//例如Array ( [0] => qqqqaaa [1] => sssqweqweaaa [2] => 29 [3] => qqqqqwe )
$result3 = mysql_query("select * from news where id = 29");
print_r(mysql_fetch_row($result3));
//4.mysql_fetch_object() 函数从结果集(记录集)中取得一行作为对象。
$result4 = mysql_query("select * from news");
while ($row = mysql_fetch_object($result4)) {
echo $row->title."<br />";
}
mysql_close($con);
?>