">
赞
踩
首先封装好mysql类
mysql.php
- <?php
- class Mysql{
- private static $host="localhost";
- private static $user="root";
- private static $password="123456";
- private static $dbName="test"; //数据库名
- private static $charset="utf8"; //字符编码
- private static $port="3306"; //端口号
- private $conn=null;
- function __construct(){
- $this->conn=new mysqli(self::$host,self::$user,self::$password,self::$dbName,self::$port);
- if(!$this->conn)
- {
- die("数据库连接失败!".$this->conn->connect_error);
- }else{
- echo "连接成功!";
- }
- $this->conn->query("set names ".self::$charset);
- }
-
- //执行sql语句
- function sql($sql){
- $res=$this->conn->query($sql);
- if(!$res)
- {
- echo "数据操作失败";
- }
- else
- {
- if($this->conn->affected_rows>0)
- {
- return $res;
- }
- else
- {
- echo "0行数据受影响!";
- }
- }
-
- }
-
- //返回受影响数据行数
- function getResultNum($sql){
- $res=$this->conn->query($sql);
- return mysqli_num_rows($res);
- }
-
- //关闭数据库
- public function close()
- {
- @mysqli_close($this->conn);
- }
- }
- ?>
index.php
- <?php
- require_once "mysql.php";
- $conn=new Mysql();
- $sql="select * from user";
-
- //执行查询并获取查询结果
- $result=$conn->sql($sql);
-
- //输出受影响数据行数
- $num=$conn->getResultNum($sql);
- echo "影响的行数:".$num;
-
- //读取并输出记录
- while ($row = mysqli_fetch_assoc($result))
- {
- echo "{$row['name']} ";
- echo "{$row['password']}";
- }
-
- //关闭数据库
- $conn->close();
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。