PHP mysqli 扩展连接代码

PHP 使用了 mysqli 扩展,连接 MySQL 数据库可以有两种方式:全局函数方式 和 对象方式

函数方式:

//创建连接
if (!$myconn = mysqli_connect('localhost','user','password','world')) {
    echo "error:" . mysqli_connect_error(); 
    exit;
}

//创建记录集
if (!$result = mysqli_query($myconn , 'select id from mytable') ) {
    echo "sql error";
    exit;
}

while( $row = mysqli_fetch_assoc($result) ){ 
    echo $row['id'] . "
"
}

//关闭记录集
mysqli_free_result($result); 

//关闭连接
mysqli_close($myconn);


对象方式:

//创建实例
$mysqli = new mysqli('localhost', 'user', 'password', 'world');

if (mysqli_connect_errno()) {
    echo "error:" . mysqli_connect_error();
    exit;
}

//查询
if (!$result = $mysqli->query('select id from mytable)) { 
    echo "sql error";
}

while( $row = $result->fetch_assoc() ){ 
   echo $row['id'] . "
";


//关闭
$result->close(); 
$mysqli->close();

posted on 2012-04-08 11:25  风清扬令狐冲  阅读(256)  评论(0编辑  收藏  举报

导航