与Mysqli相关的四种数据库取值


<!--取值方案一:通过数字数组 fetch_row()-->
<meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2015/8/27
* Time: 11:00
*/

//数据库连接
$_mysqli=new mysqli('localhost','root','******','testguest');

//设置编码
$_mysqli->set_charset('utf8');

//创建SQL语句
$_sql="SELECT * FROM tg_user";

//执行SQL语句,并将结果集赋值给$_result
$_result=$_mysqli->query($_sql);

//索引数组(第一行的信息)
$_row=$_result->fetch_row();
echo $_row[3];

//索引整个表的信息
while(!!$_row=$_result->fetch_row()){
echo $_row[3].'<br/>';
}

//销毁结果集
$_result->free();

//数据库断开
$_mysqli->close();

?>



<!--取值方案二:通过关联数组 fetch_assoc()-->
<meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2015/8/27
* Time: 11:18
*/
//数据库连接
$_mysqli=new mysqli('localhost','root','******','testguest');

//设置编码
$_mysqli->set_charset('utf8');

//创建SQL语句
$_sql="SELECT * FROM tg_user";

//执行SQL语句,并将结果集赋值给$_result
$_result=$_mysqli->query($_sql);

//索引数组(第一行的信息)
$_assoc=$_result->fetch_assoc();
echo $_assoc['tg_username'].'<br/><br/>';

//索引整个表的信息
while(!!$_assoc=$_result->fetch_assoc()){
echo $_assoc['tg_username'].'<br/>';
}

//销毁结果集
$_result->free();

//数据库断开
$_mysqli->close();
?>


<!--取值方案三:通过 关联+数字数组 fetch_array()-->
<meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2015/8/27
* Time: 11:39
*/
$_mysqli=new mysqli('localhost','root','******','testguest');

if(mysqli_connect_errno()){
echo '数据库连接错误,错误信息:'.mysqli_connect_error();
exit();
}

//设置编码
$_mysqli->set_charset('utf8');

$_sql='SELECT * FROM tg_user';

$_result=$_mysqli->query($_sql);

//打印第一条信息
//print_r($_result);
$_array=$_result->fetch_array();
echo $_array[3].'<br/>';
echo $_array['tg_username'].'<br/>';

//遍历
while(!!$_array=$_result->fetch_array()){
echo $_array[3].'<br/>';
echo $_array['tg_username'].'<br/>';
}

$_result->free();
$_mysqli->close();
?>


<!--取值方案四:通过面向对象(OOP) fetch_object()-->
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2015/8/27
* Time: 11:54
*/
$_mysqli=new mysqli('localhost','root','******','testguest');

if(mysqli_connect_errno()){
echo '数据库连接错误,错误信息是:'.mysqli_connect_error();
exit();
}

//设置数据库编码
$_mysqli->set_charset('utf8');

$_sql='SELECT * FROM tg_user';

$_result=$_mysqli->query($_sql);

$_object=$_result->fetch_object();
echo $_object->tg_username.'<br/>';

//遍历
while(!!$_object=$_result->fetch_object()){
echo $_object->tg_username.'<br/>';
}

$_result->free();
$_mysqli->close();
?>

 

posted on 2015-08-27 12:23  小明在线  阅读(386)  评论(0编辑  收藏  举报

导航