相关推荐recommended
PHP之 连接MySql数据库
作者:mmseoamin日期:2023-12-25

上一节已经成功配置了php+mysql开发环境(https://mp.csdn.net/mp_blog/creation/editor/129432310),下面将进行实战连接数据库

一,打开sublime3编辑器,配置php开发环境

1.1 在网站根目录下新建php项目文件夹,存放php文件

PHP之 连接MySql数据库,第1张

PHP之 连接MySql数据库,第2张

1.2 安装Package Control,按下ctrl+shift+p,调出输入框输入Package Control,并安装

PHP之 连接MySql数据库,第3张

PHP之 连接MySql数据库,第4张

 安装成功后可以用package control添加其它支持插件

PHP之 连接MySql数据库,第5张

 二,php连接数据库相关源码

PHP之 连接MySql数据库,第6张

2.1 数据库配置

 

2.2 连接数据库和用户的增删改查

connect();
    }
    // destructor
    function __destruct()
    {
    }
    // Connecting to database
    public function connect() {
       // 创建连接
        $this->conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD);
        // 检测连接
        if ($this->conn->connect_error) {
            $this->isNext=false;
        }else{
            //检查是否创建数据库
            // 创建数据库
            $sql = "show DATABASES LIKE '".DB_DATABASE."'";
            $row = $this->conn->query($sql)->fetch_object();
            if ($row) {
                $this->isNext=true;
            } else {
                // 创建数据库
                $sql = "CREATE DATABASE ".DB_DATABASE;
                if ($this->conn->query($sql) === TRUE) {
                    $this->isNext=true;
                } else {
                    $this->isNext=false;
                }
            }
        }
        if($this->isNext){
            $this->conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
            if ($this->conn->connect_error) {
                $response["code"] = "0";
                $response["msg"] = "连接失败";
                die(json_encode($response,JSON_UNESCAPED_UNICODE));
            }
            // else{
            //     $response["code"] = "0";
            //     $response["msg"] = "连接成功";
            //     die(json_encode($response,JSON_UNESCAPED_UNICODE));
            // }
        }else{
            $response["code"] = "0";
            $response["msg"] = "创建数据库失败";
            die(json_encode($response,JSON_UNESCAPED_UNICODE));
        }
        // return database handler
        return $this->conn;
    }
    public function checkTablesUsers()
    {
        $sql = "SHOW TABLES LIKE 'users'";
        $row = $this->conn->query($sql)->fetch_object();
        if (!$row) {
            // 使用 sql 创建数据表
            $sql = "CREATE TABLE users (
                  uid INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, 
                  username VARCHAR(50),
                  password VARCHAR(50),
                  avatar VARCHAR(50),
                  sign VARCHAR(50),
                  createtime DATETIME 
                  )";
            if ($this->conn->query($sql) === TRUE) {
                return true;
            } else {
                $response["code"] = "0";
                $response["msg"] = "创建数据表错误: " .$this->conn->error;
                die(json_encode($response,JSON_UNESCAPED_UNICODE));
                return false;
            }
        } else {
            return true;
        }
    }
    /**
     * Storing new user
     * returns user details
     */
    public function storeUser($username, $password)
    {
        if ($this->checkTablesUsers()) {
            $stmt = $this->conn->prepare("INSERT INTO users(username, password,createtime) VALUES(?, ?, NOW())");
            //该函数绑定了 SQL 的参数,且告诉数据库参数的值。 "sss" 参数列处理其余参数的数据类型。s 字符告诉数据库该参数为字符串
            $stmt->bind_param("ss", $username, $password);
            $result = $stmt->execute();
            $stmt->close();
            // check for successful store
            if ($result) {
                $stmt = $this->conn->prepare("SELECT * FROM users WHERE username = ?");
                $stmt->bind_param("s", $username);
                $stmt->execute();
                $user = $stmt->get_result()->fetch_assoc();
                $stmt->close();
                return $user;
            } else {
                return false;
            }
        }
    }
    /**
     * Get user by username and password
     */
    public function getUserByUsernameAndPassword($username, $password)
    {
        if ($this->checkTablesUsers()) {
            $stmt = $this->conn->prepare("SELECT * FROM users WHERE username = ?");
            $stmt->bind_param("s", $username);
            if ($stmt->execute()) {
                $user = $stmt->get_result()->fetch_assoc();
                $stmt->close();
                // verifying user password
                $passwordss = $user['password'];
                // check for password equality
                if ($passwordss == $password) {
                    // user authentication details are correct
                    return $user;
                }
            } else {
                return NULL;
            }
        }
    }
     /**
     * Get user by uid
     */
    public function getUserByUid($uid)
    {
        if ($this->checkTablesUsers()) {
            $stmt = $this->conn->prepare("SELECT * FROM users WHERE uid = ?");
            $stmt->bind_param("s", $uid);
            if ($stmt->execute()) {
                $user = $stmt->get_result()->fetch_assoc();
                $stmt->close();
                return $user;
            } else {
                return NULL;
            }
        }
    }
    /**
     * Check user is existed or not
     */
    public function isUserExisted($username)
    {
        if ($this->checkTablesUsers()) {
            $stmt = $this->conn->prepare("SELECT username from users WHERE username = ?");
            $stmt->bind_param("s", $username);
            $stmt->execute();
            $stmt->store_result();
            if ($stmt->num_rows > 0) {
                // user existed
                $stmt->close();
                return true;
            } else {
                // user not existed
                $stmt->close();
                return false;
            }
        }
    }
}

2.3 POST JSON数据请求接口格式注册实战

username;
    $password=$data->password;
}
if($username&&$password){
	// check if user already existed
	if ($db->isUserExisted($username)) {
		// exists already
        $response["code"] = "0";
        $response["msg"] = "用户已存在";
		echo json_encode($response,JSON_UNESCAPED_UNICODE);
	} else {
		// create a new user
		$user = $db->storeUser($username, $password);
		if ($user) {
            $response["code"] = "1";
            $response["msg"] = "注册成功";
            $response["data"]["uid"] = $user["uid"];
            $response["data"]["username"] = $user["username"];
			echo json_encode($response,JSON_UNESCAPED_UNICODE);
		} else {
			//failed
            $response["code"] = "0";
            $response["msg"] = "注册失败";
			echo json_encode($response,JSON_UNESCAPED_UNICODE);
		}
	}
	
} else {
    $response["code"] = "0";
   $response["msg"] = "请输入用户名或密码";
	echo json_encode($response,JSON_UNESCAPED_UNICODE);
}

2.4 POST JSON数据请求接口格式登录实战

username;
    $password=$data->password;
}
if($username&&$password){
	$user = $db->getUserByUsernameAndPassword($username, $password);
	if ($user) {
		//user found
		$response["code"] = "1";
        $response["msg"] = "登录成功";
        $response["data"]["uid"] = $user["uid"];
		$response["data"]["username"] = $user["username"];
		echo json_encode($response,JSON_UNESCAPED_UNICODE);
	} else {
		// user not found
        $response["code"] = "0";
        $response["msg"] = "用户名或密不正确";
		echo json_encode($response,JSON_UNESCAPED_UNICODE);
	}
} else {
	// params missing
    $response["code"] = "0";
    $response["msg"] = "请输入用户名或密码";
	echo json_encode($response,JSON_UNESCAPED_UNICODE);
}

2.5 GET方式接口获取用户信息实战

getUserByUid($uid);
	if ($user) {
		//user found
		$response["code"] = "1";
        $response["msg"] = "获取用户信息成功";
        $response["data"]["uid"] = $user["uid"];
		$response["data"]["username"] = $user["username"];
		echo json_encode($response,JSON_UNESCAPED_UNICODE);
	} else {
		// user not found
        $response["code"] = "0";
        $response["msg"] = "获取用户信息失败";
		echo json_encode($response,JSON_UNESCAPED_UNICODE);
	}
} else {
	// params missing
    $response["code"] = "0";
    $response["msg"] = "请传入用户ID";
	echo json_encode($response,JSON_UNESCAPED_UNICODE);
}

三,运行

打开静态页面,输入用户名密码,登录成功会返回首页

PHP之 连接MySql数据库,第7张

PHP之 连接MySql数据库,第8张

PHP之 连接MySql数据库,第9张

四,编辑器

4.1 当然除了sublime,还有phpstorm和EclipseForPHP也是很强大的编辑器可供选择,sublime轻量级一些

4.2 sublime插件

1.Package Control (https://sublime.wbond.net)

这个就不多说了,装sublime插件必备,如果你还没有装,看这里。

2.Sub­lime­CodeIn­tel (https://github.com/SublimeCodeIntel/SublimeCodeIntel)

提供代码提示,函数、对象或变量名称等。还可以提示对象或类中哪些方法和变量。基于komodo codeintel开发,虽然有时会有一些问题,但是大多时候是没问题的。

3.Sub­limeLin­ter (https://sublime.wbond.net/packages/SublimeLinter)

代码提错工具。但是从sublime 3开始,SublimeLineter编程模块化,所以安装完主安装包之后,还需要安装你需要支持的对应的语言的插件。对于PHP+js的开发,可以安装如下插件:

SublimeLinter-php

SublimeLinter-jshint

SublimeLinter-json

and SublimeLinter-csslint

4.Side­BarEn­hance­ments (https://sublime.wbond.net/packages/SideBarEnhancements)

提供强大的边栏右键选项,非常方便。

5.VCS Gut­ter (https://sublime.wbond.net/packages/VCS%20Gutter)

编码的时候避免不了使用Git或SVN,VCS Gutter可以很方便的在代码中显示代码改动,支持Git、 Mercurial和 Subversion,如下图:screenshot

6.SFTP, paid (http://wbond.net/sublime_packages/sftp)

这个插件可以让Sublime很方便的支持SFTP、FTP和FTPS。支持远程文件浏览编辑和远程与本地的同步,还可以方便的上传下载,不过要钱,我就呵呵呵了~~~。

7.Tor­toise (on Win­dows only) (http://wbond.net/sublime_packages/tortoise)

如果在Windows环境下编程,这个工具可以完全替代Side­Bar­Git,它没有很多的特点,但是提供的功能都很实用。

8.sublime-github (https://github.com/bgreenlee/sublime-github)

支持github的插件。

9.PHPcs (http://soulbroken.co.uk/code/sublimephpcs)

检查php代码是否满足某种标准,比如Zend,PEAR等。

10.Trail­ing­Spaces (https://github.com/SublimeText/TrailingSpaces)

自动删除高亮行末、文件尾的空格。

11.Brack­etHigh­lighter (https://github.com/facelessuser/BracketHighlighter)

和Tag插件的情形一样,ST3对代码高亮已经支持的足够好了,但是不得不说,这仍然是一个很好的插件。

12.Sub­lime Func­tion Name Display (https://github.com/akrabat/SublimeFunctionNameDisplay)

在底部状态栏显示当前文件、类和函数或方法的名称。简单实用。

13.Ter­mi­nal (http://wbond.net/sublime_packages/terminal)

使用Git或者一些PEAR包的时候,你或许需要不断地转换到命令行。这就是这个插件的作用。

14.DocBlockr (https://github.com/spadgos/sublime-jsdocs)