php使用mysqli连接数据库


对于使用php连接mysqli数据库,目前有两种主要方式:

第一种是使用面向过程的连接方式:

<?php
    $connect = mysqli_connect('localhost','root','','volunteer') or die('Unale to connect');
    $sql = "select * from vol_msg";
    $result = mysqli_query($connect,$sql);
    while($row = mysqli_fetch_row($result)){
        echo $row[0];
    }
?>

第二种是使用面向对象,使用对象的方式:

<?php
    //创建对象并打开连接,最后一个参数是选择的数据库名称
    $mysqli = new mysqli('localhost','root','','volunteer');
    //检查连接是否成功
    if (mysqli_connect_errno()){
        //注意mysqli_connect_error()新特性
        die('Unable to connect!'). mysqli_connect_error();
    }
    $sql = "select * from vol_msg";
    //执行sql语句,完全面向对象的
    $result = $mysqli->query($sql);
    
    while($row = $result->fetch_array()){
        echo $row[0];
    }
?>

产生一个支持远程的mysql用户:
# mysql -uroot -p123456

CREATE USER 'jroot'@'%' IDENTIFIED BY '123456';

GRANT GRANT OPTION ON *.* TO 'jroot'@'%';

GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, RELOAD, SHUTDOWN, PROCESS, FILE, REFERENCES, INDEX, ALTER, SHOW DATABASES, SUPER, CREATE TEMPORARY TABLES, LOCK TABLES, EXECUTE, REPLICATION SLAVE, REPLICATION CLIENT, CREATE VIEW, SHOW VIEW, CREATE ROUTINE, ALTER ROUTINE, CREATE USER, EVENT, TRIGGER ON *.* TO 'jroot'@'%';

原文链接:https://blog.yongit.com/note/112776.html