21 MySQL from beginner to proficient - PHP operates mysql database

初识PHP
	PHP:是一种服务器端跨平台html的嵌入式语言,它独特的语法混合了C、java和peal语言的特点,是一种被广泛应用的开源的多用途脚本语言
	优势:
		部署快:lnmp、lamp
		开发快:有众多开源项目
	应用领域广泛
PHP管理MySQL数据
	通过MySQLi扩展来管理数据库,此扩展下有好多类,既有面向过程的可以通过函数调用来实现,也有面向对象的可以通过调用方法来实现
	MySQLi官方文档:https://www.php.net/manual/zh/book.mysqli.php
	
PHP操作MySQL数据库:
	连接MySQL服务器:
		调用 mysqli_connect()函数
		示例:
			$link = mysqli_connect("localhost", "root", "root", "db_database21") or die("连接数据库服务器失败!".mysqli_error());	
				#参数依次为主机、mysql登录用户、密码、数据库,如果失败则退出并且调用mysqli_error()函数输出错误信息
	选择数据库:
		调用 mysqli_select_db()函数
		示例:if(mysqli_select_db($link,'db_users'))(echo "选择成功";)
	执行SQL语句
		调用 mysqli_query函数
		这里可以进行增删改查,其中增删改只会输出布尔型数据,查会输出具体值
		示例:
			$result = mysqli_query($link,"select * from books");
	获取结果集
		调用 mysqli_fetch_array($result [,$ruslt_type])
			#$result_type取值类型:
				MYSQLI_ASSOC:关联数组
				MYSQLI_NUM:索引数组
				MYSQLI_BOTH:关联数组+索引数组(默认)
		示例:
			$rows = mysqli_fetch_array($result);	#相同的函数可以根据数据库列表依次往下执行
			print_r($rows)	#打印最后一个值
		示例2:循环语句显示所有
			while($rows = mysqli_fetch_array($result,MYSQLI_ASSOC))
			{echo "<pre>";	#设置显示格式
			print_r($rows)	;
			}

补充:
	Bootstrap前端框架:https://v3.bootcss.com/components/#panels

Example 1: Set front-end static page display:
1. Directory results
Insert image description here
2. PHP file

<?php
    //连接MySQL服务器,选择数据库
    $link = mysqli_connect("localhost", "root", "root", "db_database21") or die("连接数据库
                             服务器失败!".mysqli_error());
    mysqli_query($link,"set names utf8");                //设置数据库编码格式UTF8
    $result = mysqli_query($link,"select * from books");     //执行查询语句
    include_once('lists.html');                                //引入模板

3.html file
Insert image description here
Insert image description here
Insert image description here
4. Actual effect
Insert image description here
Example 2: The front-end page embeds PHP code to dynamically obtain database information and then displays it on the page:
Insert image description here
display results
Insert image description here

//代码示例:
<!DOCTYPE html>
<html lang="en" class="is-centered is-bold">
<head>
    <meta charset="UTF-8">
    <title>零基础</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet">
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.js"></script>
</head>
<body>
<div class="container" style="padding-top: 10px">
    <div class="col-sm-offset-2 col-sm-8">
        <div class="panel panel-default">
            <div class="panel-heading">
                图书列表
            </div>
            <div class="panel-body">
                <table class="table table-striped task-table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>图书名称</th>
                            <th>分类</th>
                            <th>价格</th>
                            <th>出版日期</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php while($rows = mysqli_fetch_array($result,MYSQLI_ASSOC)) {
    
     ?>
                        <tr>
                            <td class="table-text">
                                <?php echo $rows['id'] ?>
                            </td>
                            <td class="table-text">
                                <?php echo $rows['name'] ?>
                            </td>
                            <td class="table-text">
                                <?php echo $rows['category'] ?>
                            </td>
                            <td class="table-text">
                                <?php echo $rows['price'] ?>
                            </td>
                            <td><?php echo $rows['publish_time'] ?></td>
                            <td>
                                 <a href='editBook.php?id=<?php echo $rows['id'] ?>'>
                                    <button class="btn btn-info edit" >编辑</button>
                                 </a>
                                  <a href='deleteBook.php?id=<?php echo $rows['id'] ?>'>
                                     <button class="btn btn-danger delete">删除</button>
                                 </a>
                            </td>
                        </tr>
                        <?php } ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
</body>
</html>


				

Example 2

		从结果集中返回一行作为对象
			调用mysqli_fetch_object($result)函数

Insert image description here

		从结果集中返回一行作为枚举数组
			调用mysqli_fetch_row($result) 函数 等同于 mysqli_fetch_array($result,MYSQLI_NUM)

Example: The page display results are the same as the above example
Insert image description here

		从结果集中获取一行作为关联数组
			调用mysqli_fetch_assoc($result)函数,等同于	mysqli_fetch_array($result,MYSQLI_ASSOC)
		获取结果集中的记录数
			调用mysqli_num_rows($result)
				注意:只对select 查询有效
			获取新增、删除、修改的记录数可调用:mysqli_affected_rows($result)函数

Example
Insert image description here
Insert image description here
page display:
Insert image description here

	关闭连接
		释放内存
			调用mysqli_free_result($result)函数:会释放所有的结果与$result相关的内存,由于PHP在操作完成后会自动释放内存,所以一般不会使用这个函数,只有在返回的结果集很大的时候占用了较多内存的情况下才会调用这个函数
		关闭连接	
			调用mysqli_close($link)函数	#$link:是我们在连接数据库的时候生成的一个连接表示
			在PHP中与数据库的连接一般为非持久连接系统会自动回收一般不需要设置关闭,但是一次性返回的结果集比较大或者网站访问量比较多最好使用手动关闭连接的方式

Example:
Insert image description here
Show:
Insert image description here

	管理数据
		新增数据

Example: Add book information:
#The page provides a form. After filling in the form and submitting it, it is written into the database through PHP code.

exhibit:

Insert image description here
Show after submission
Insert image description here

Directory Structure
Insert image description here

add.html submission page:

<!DOCTYPE html>
<html lang="en" class="is-centered is-bold">
<head>
    <meta charset="utf-8">
    <title>零基础</title>
    <!-- 引入样式 -->
    <link rel="stylesheet" href="public/css/bootstrap.css">
    <link rel="stylesheet" href="public/css/bootstrap-datetimepicker.css" >
    <!-- 引入时间插件 -->
    <script src="public/js/jquery.min.js"></script>
    <script src="public/js/moment.min.js"></script>
    <script src="public/js/bootstrap.min.js"></script>
    <script src="public/js/bootstrap-datetimepicker.js"></script>
</head>
<body>
<div class="container" style="padding-top: 10px">
    <div class="col-sm-8">
        <div class="panel panel-default">
            <div class="panel-heading">
                <h3 class="panel-title">添加图书</h3>
            </div>
            <div class="panel-body">
                <form class="form-horizontal" role="form" method="POST" action="addBook.php">
                    <div class="row">
                        <div class="col-md-8">
                            <div class="form-group">
                                <label for="name" class="col-md-2 control-label">
                                    名称
                                </label>
                                <div class="col-md-10">
                                    <input type="text" class="form-control" name="name" id="name" value="">
                                </div>
                            </div>
                            <div class="form-group">
                                <label for="name" class="col-md-2 control-label">
                                    分类
                                </label>
                                <div class="col-md-10">
                                    <select class="form-control" name="category">
                                        <option value="PHP">PHP</option>
                                        <option value="Java">Java</option>
                                        <option value="C++">C++</option>
                                    </select>
                                </div>
                            </div>
                            <div class="form-group">
                                <label for="price" class="col-sm-2 control-label">
                                    价格
                                </label>
                                <div class="col-md-10">
                                    <input type="text" class="form-control" name="price" id="price" value="">
                                </div>
                            </div>

                            <div class="form-group">
                                <label class="col-sm-2 control-label">出版时间</label>
                                <div class='col-md-10' >
                                    <div class='input-group date' id='publish_time'>
                                        <input type='text' class="form-control" name="publish_time"/>
                                        <span class="input-group-addon">
                                            <span class="glyphicon glyphicon-calendar"></span>
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-8">
                        <div class="form-group">
                            <div class="col-md-10 col-md-offset-2">
                                <button type="submit" class="btn btn-primary btn-lg">
                                    <i class="fa fa-disk-o"></i>
                                    提交
                                </button>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
    //datetimepicker日期插件,获取日期
    $('#publish_time').datetimepicker({
    
    
        format: "Y-MM-DD"
    });
</script>
</body>
</html>

addBook.php connect to the database

<?php
$link = mysqli_connect('localhost', 'root', 'root', 'db_database21');
mysqli_query($link,"set names utf8");//设置数据库编码格式utf8
/* 检测连接是否成功 */
if (!$link) {
    
    
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}
/* 检测是否生成MySQLi_STMT类 */
$stmt = mysqli_prepare($link, "insert into books (name,category,price,publish_time) VALUES (?, ?, ?, ?)");
if ( !$stmt ) {
    
    
    die('mysqli error: '.mysqli_error($link));
}
/* 获取POST提交数据 */
$name     = $_POST['name'];
$category = $_POST['category'];
$price    = $_POST['price'];
$publish_time = $_POST['publish_time'];
/* 参数绑定 */
mysqli_stmt_bind_param($stmt, 'ssds', $name, $category, $price, $publish_time);
/* 执行prepare语句 */
mysqli_stmt_execute($stmt);
/* 根据执行结果,跳转页面 */
if(mysqli_stmt_affected_rows($stmt)){
    
    
    echo "<script>alert('添加成功');window.location.href='index.php';</script>";
}else{
    
    
    echo "<script>alert('添加失败');</script>";
}

?>

index.php insert update database

<?php
/* 获取POST提交数据 */
$id       = $_POST['id'];
$name     = $_POST['name'];
$category = $_POST['category'];
$price    = $_POST['price'];
$publish_time = $_POST['publish_time'];

$link = mysqli_connect('localhost', 'root', 'root', 'db_database21');
mysqli_query($link,"set names utf8");//设置数据库编码格式utf8
/* 检测连接是否成功 */
if (!$link) {
    
    
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}
/* 检测是否生成MySQLi_STMT类 */
$query = "update books set name = ?,category = ? ,price = ? ,publish_time = ? where id = ".$id;
$stmt  = mysqli_prepare($link, $query);
if ( !$stmt ) {
    
    
    die('mysqli error: '.mysqli_error($link));
}
/* 参数绑定 */
mysqli_stmt_bind_param($stmt, 'ssds', $name, $category, $price, $publish_time);
/* 执行prepare语句 */
mysqli_stmt_execute($stmt);
/* 根据执行结果,跳转页面 */
if(mysqli_stmt_affected_rows($stmt)){
    
    
    echo "<script>alert('修改成功');window.location.href='index.php';</script>";
}else{
    
    
    echo "<script>alert('修改失败');</script>";
}

?>

Lists.html display page after submission

<!DOCTYPE html>
<html lang="en" class="is-centered is-bold">
<head>
    <meta charset="UTF-8">
    <title>零基础</title>
    <link href="public/css/bootstrap.css" rel="stylesheet">
</head>
<body>
<div class="container" style="padding-top: 10px">
    <div class="col-sm-offset-2 col-sm-8">
        <div class="panel panel-default">
            <div class="panel-heading">
                图书列表
            </div>
            <div class="panel-body">
                <table class="table table-striped task-table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>图书名称</th>
                            <th>分类</th>
                            <th>价格</th>
                            <th>出版日期</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php while($rows = mysqli_fetch_array($result,MYSQLI_ASSOC)) {
    
     ?>
                        <tr>
                            <td class="table-text">
                                <?php echo $rows['id'] ?>
                            </td>
                            <td class="table-text">
                                <?php echo $rows['name'] ?>
                            </td>
                            <td class="table-text">
                                <?php echo $rows['category'] ?>
                            </td>
                            <td class="table-text">
                                <?php echo $rows['price'] ?>
                            </td>
                            <td><?php echo $rows['publish_time'] ?></td>
                            <td>
                                <a href='editBook.php?id=<?php echo $rows['id'] ?>'>
                                    <button class="btn btn-info edit">编辑</button>
                                </a>
                                <a href='deleteBook.php?id=<?php echo $rows['id'] ?>'>
                                    <button class="btn btn-danger delete">删除</button>
                                </a>
                            </td>
                        </tr>
                        <?php } ?>
                    </tbody>
                </table>
                <p class="text-primary text-center ">共计<?php echo $number ?></p>
            </div>
        </div>
    </div>
</div>
</body>
</html>
	

		编辑数据

Example:
Insert image description here

Guess you like

Origin blog.csdn.net/weixin_43812198/article/details/129537156