在PHP中使用MySQL扩展库处理结果集

来源:互联网 发布:计算机病毒 知乎 编辑:程序博客网 时间:2024/05/17 09:18
$link = mysql_connect("localhost","root","") or die("connect error!");
mysql_select_db("test") or die("select db error!");
$sql = "select id,name,price,num,desn from shops";
$result = mysql_query($sql);

/*
一、从结果集中将记录取出
mysql_fetch_row($result)//返回索引数组
mysql_fetch_assoc($result)//返回关联数组(下表就是列名)
以上两个使用哪个看个人爱好

mysql_fetch_array($result)//返回索引和关联两个数组
mysql_fetch_object($result)//将一条记录以对象的形式返回

使用一次就从结果集中取出一条记录
取完之后将指针移动到下一条记录(默认是第一条记录 mysql_data_seek($result,row))
再取就是下一条记录,如果到结尾则返回false

二、从结果集中将表的字段取出

其他:取行数,列数,从哪行开始取

*/

$cols = mysql_num_fields($result);
$rows = mysql_num_rows($result);
echo '<table align="center" width="800" border="1">';
echo '<caption><h1>演示表</h1></caption>';
/*while(list($id,$name,$price,$num,$desn)=mysql_fetch_row($result)){
echo '<tr>';
echo '<td>'.$id.'</td>';
echo '<td>'.$name.'</td>';
echo '<td>'.$price.'</td>';
echo '<td>'.$num.'</td>';
echo '<td>'.$desn.'</td>';
echo '</tr>';
}*/
echo '<tr>';
for($i=0;$i<$cols;$i++){
echo '<th>'.mysql_field_name($result,$i).'</th>';
}
echo '</tr>';
while($row = mysql_fetch_assoc($result)){
echo '<tr>';
foreach($row as $col){
echo '<td>'.$col.'</td>';
}
echo '</tr>';
}
echo '</table>';
echo "表[列{$cols},行{$rows}]<br />";
//mysql_data_seek($result,3);//移动指针
/*while($data = mysql_fetch_assoc($result)){
print_r($data);
echo '<br />';
}*/
mysql_free_result($result);//释放结果集
mysql_close();//释放数据库的资源
原创粉丝点击