php使用mysqli连接数据库

    * 新建mysqli对象 $mysqli = new mysqli ( $host, $username, $password, $database );
    * 判断是否连接成功if (mysqli_connect_errno ()) {

      echo "连接数据库失败:" . mysqli_connect_error ();
     $mysqli = null;
      exit ();
}

    *      定义sql语句 $query = "select * from db_name where condition


    *   准备查询$stmt = $mysqli->prepare ( $query );


    * 
if ($stmt) {
     $stmt->execute (); // 执行sql语句
 $stmt->bind_result ( $id,$other);  $result = $stmt->store_result ();
if ($result) {
           if ($stmt-> num_rows > 0) {
// 显示字段名称
              $metdata = $stmt->result_metadata ();
while ( $field = $metdata-> fetch_field () ) {
echo $field-> name;}
// 定位到第一条记录
              $stmt->data_seek ( 0 );
while ( $row = $stmt->fetch () ) {
echo $id.'<br />';
echo $other;
}
}
else {
           echo '对不起,' . trans_time ( $start_date ) . '至' . trans_time ( $end_date ) . '此段时间内无数据' ;
     }
} else {
      echo '数据库查询语句错误,错误号为' . $mysqli->errno . '</br>错误信息为' . $mysqli->error ;
}
// 释放资源
if ($stmt != "") {
     $stmt->free_result ();
      // 关闭连接
}

$mysqli->close ();

posted @ 2013-10-21 18:04  jayxhj  阅读(386)  评论(0编辑  收藏  举报