php版本:PHP Version 5.5.1
环境:windows10 XMAPP
数据库:mysql
代码:
<?php function connetionDB($servername, $username, $password, $db) { // 创建连接 $conn = mysqli_connect($servername, $username, $password, $db); // 检测连接 if (!$conn) { die("Connection failed: " . mysqli_connect_error()); return FALSE; } return $conn; } //创建数据库 function create_db($dbname, $conn) { $sql = "create database ‘$dbname‘"; if(mysqli_query($conn, $sql)) { echo "DB created successfully"; }else { echo "Error: ".mysqli_error($conn); } } //新建表 function create_table($conn) { $sql = "CREATE TABLE Account ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, username VARCHAR(30) NOT NULL, password VARCHAR(30) NOT NULL )"; if(mysqli_query($conn, $sql)) { echo "table created successfully"; }else{ echo "Error: ".mysqli_error($conn); } } //插入数据 function insert($username, $password, $conn){ $sql = "insert into Account (username, password) values (‘$username‘, ‘$password‘)"; if(mysqli_query($conn, $sql)) { echo "Insert successfully<br>"; }else{ echo "Error:" . mysqli_error($conn); } } //查询数据 function get($username, $conn) { $sql = "SELECT password FROM Account WHERE username = ‘$username‘"; $result = mysqli_query($conn, $sql); if (!$result) { printf("Error: %s\n", mysqli_error($conn)); exit(); } while($row = mysqli_fetch_array($result)) { // echo "username: " . $username ." password : " . $row[‘password‘]; // echo "<br>"; return $row[‘password‘]; } } //删除数据 function delete($username, $password, $conn) { $sql = "DELETE FROM Account WHERE username = ‘$username‘ and password = ‘$password‘"; if(mysqli_query($conn, $sql)) { echo "Delete $username successfully<br>"; }else{ echo "Error:" . mysqli_error($conn); } } //更新数据 function update($username, $password, $new_username, $new_password, $conn) { $sql = ‘‘; if($new_username == ‘‘ and $new_password != ‘‘) { $sql = "UPDATE Account SET password = ‘$new_password‘ WHERE username = ‘$username‘ AND password = ‘$password‘"; }else if($new_username != ‘‘ and $new_password == ‘‘){ $sql = "UPDATE Account SET username = ‘$new_username‘ WHERE username = ‘$username‘ AND password = ‘$password‘"; }else if($new_username != ‘‘ and $new_password != ‘‘){ $sql = "UPDATE Account SET username = ‘$new_username‘, password = ‘$new_password‘ WHERE username = ‘$username‘ AND password = ‘$password‘"; } if(mysqli_query($conn, $sql)) { // echo "Update successfully"; return true; }else { // echo "Error : " . mysqli_error($conn); return false; } } //关闭连接 function closeDB($conn) { mysqli_close($conn); }
使用:直接include "db.php"就可以调用这里面的方法了。
时间: 2024-10-29 19:08:38