Home > Backend Development > PHP Tutorial > PHP mysqli 操作数据库

PHP mysqli 操作数据库

WBOY
Release: 2016-06-23 13:25:04
Original
940 people have browsed it

起步

由于mysql连接方式被废除,据说在php7中要使用mysql_connect()还需要额外下载组件。
使用mysqli有面向过程和面向对象两种方式。
mysqli提供了三个类:

  • mysqli 连接相关的

  • mysqli_result 处理结果集

  • mysqli_stmt 预处理类

  • 数据库连接

    <?php$db_host = 'localhost';$db_name = 'test';$db_user = 'root';$db_pwd = '';//面向对象方式$mysqli = new mysqli($db_host, $db_user, $db_pwd, $db_name);//面向对象的昂视屏蔽了连接产生的错误,需要通过函数来判断if(mysqli_connect_error()){    echo mysqli_connect_error();}//设置编码$mysqli->set_charset("utf8");//或者 $mysqli->query("set names 'utf8'")//关闭连接$mysqli->clise();//面向过程方式的连接方式$mysqli = mysqli_connect($db_host, $db_user, $db_pwd, $db_name);//判断是否连接成功if(!$mysqli ){    echo mysqli_connect_error();}//关闭连接mysqli_close($mysqli);?>
    Copy after login

    数据库查询

    通用:执行sql语句都可用query(sql),执行失败会返回false,select成功则返回结果集对象,其他返回true,只要不是false就说明sql语句执行成功了。

    <?php//无结果集示例$sql = "insert into table_name (`name`, `address`) values ('xiaoming', 'adddddrrreess')";$result = $mysqli->query($sql);//或者$sql = "delete from table_name where name='xiaoming'";$result = $mysqli->query($sql);if($result === false){    echo $mysqli->error;    echo $mysqli->errno;}//影响条数echo $mysqli->num_rows;//插入的idecho $mysqli->insert_id;$mysqli->close();
    Copy after login

    有结果集

    <?php$sql = "select * from table_name";$result = $mysqli->query($sql);if($result === false){//执行失败    echo $mysqli->error;    echo $mysqli->errno;}//行数echo $result->num_rows;//列数 字段数echo $result->field_count;//获取字段信息$field_info_arr = $result->fetch_fields();//移动记录指针//$result->data_seek(1);//0 为重置指针到起始//获取数据while($row = $result->fetch_assoc()){    echo $row['name'];    echo $row['address'];}//也可一次性获取所有数据//$result->data_seek(0);//如果前面有移动指针则需重置$data = $result->fetch_all(MYSQLI_ASSOC);$mysqli->close();
    Copy after login
    Related labels:
    source:php.cn
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template