上一节已经成功配置了php+mysql开发环境(https://mp.csdn.net/mp_blog/creation/editor/129432310),下面将进行实战连接数据库
一,打开sublime3编辑器,配置php开发环境
1.1 在网站根目录下新建php项目文件夹,存放php文件
1.2 安装Package Control,按下ctrl+shift+p,调出输入框输入Package Control,并安装
安装成功后可以用package control添加其它支持插件
二,php连接数据库相关源码
2.1 数据库配置
<?php
/**
* Database config variables
*/
//本地数据库配置
define("DB_HOST", "localhost");
define("DB_USER", "root");
define("DB_PASSWORD", "Aa123456..");
define("DB_DATABASE", "bdm817514261_db");
2.2 连接数据库和用户的增删改查
<?php
require_once 'Config.php';
class DB_Functions
{
private $conn;
private $isNext;
// constructor
function __construct()
{
$this->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数据请求接口格式注册实战
<?php
require_once 'DBFunctions.php';
$db = new DB_Functions();
// 从请求中获取原始数据
$json = file_get_contents('php://input');
// 将其转换为 PHP 对象
$data = json_decode($json);
$username=null;
$password=null;
if($data){
//json格式
$username=$data->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数据请求接口格式登录实战
<?php
require_once 'DBFunctions.php';
$db = new DB_Functions();
// 从请求中获取原始数据
$json = file_get_contents('php://input');
// 将其转换为 PHP 对象
$data = json_decode($json);
$username=null;
$password=null;
if($data){
//json格式
$username=$data->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方式接口获取用户信息实战
<?php
require_once 'DBFunctions.php';
$db = new DB_Functions();
$uid=$_GET['uid'];
if($uid){
$user = $db->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);
}
三,运行
打开静态页面,输入用户名密码,登录成功会返回首页
四,编辑器
4.1 当然除了sublime,还有phpstorm和EclipseForPHP也是很强大的编辑器可供选择,sublime轻量级一些
4.2 sublime插件
1.Package Control (https://sublime.wbond.net)
这个就不多说了,装sublime插件必备,如果你还没有装,看这里。
2.SublimeCodeIntel (https://github.com/SublimeCodeIntel/SublimeCodeIntel)
提供代码提示,函数、对象或变量名称等。还可以提示对象或类中哪些方法和变量。基于komodo codeintel开发,虽然有时会有一些问题,但是大多时候是没问题的。
3.SublimeLinter (https://sublime.wbond.net/packages/SublimeLinter)
代码提错工具。但是从sublime 3开始,SublimeLineter编程模块化,所以安装完主安装包之后,还需要安装你需要支持的对应的语言的插件。对于PHP+js的开发,可以安装如下插件:
SublimeLinter-php
SublimeLinter-jshint
SublimeLinter-json
and SublimeLinter-csslint
4.SideBarEnhancements (https://sublime.wbond.net/packages/SideBarEnhancements)提供强大的边栏右键选项,非常方便。
5.VCS Gutter (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.Tortoise (on Windows only) (http://wbond.net/sublime_packages/tortoise)
如果在Windows环境下编程,这个工具可以完全替代SideBarGit,它没有很多的特点,但是提供的功能都很实用。
8.sublime-github (https://github.com/bgreenlee/sublime-github)
支持github的插件。
9.PHPcs (http://soulbroken.co.uk/code/sublimephpcs)
检查php代码是否满足某种标准,比如Zend,PEAR等。
10.TrailingSpaces (https://github.com/SublimeText/TrailingSpaces)
自动删除高亮行末、文件尾的空格。
11.BracketHighlighter (https://github.com/facelessuser/BracketHighlighter)
和Tag插件的情形一样,ST3对代码高亮已经支持的足够好了,但是不得不说,这仍然是一个很好的插件。
12.Sublime Function Name Display (https://github.com/akrabat/SublimeFunctionNameDisplay)
在底部状态栏显示当前文件、类和函数或方法的名称。简单实用。
13.Terminal (http://wbond.net/sublime_packages/terminal)
使用Git或者一些PEAR包的时候,你或许需要不断地转换到命令行。这就是这个插件的作用。文章来源:https://www.toymoban.com/news/detail-782404.html
14.DocBlockr (https://github.com/spadgos/sublime-jsdocs)文章来源地址https://www.toymoban.com/news/detail-782404.html
到了这里,关于PHP之 连接MySql数据库的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!