PHP : MySQLi【面向過程】操作數據庫【 連接、建庫、建表、增、刪、改、查、關閉】
阿新 • • 發佈:2018-08-24
錯誤 result mys char _array fun 數據庫名 arr per
<?php /** *數據庫操作關鍵函數 *mysql_connect:連接數據 *mysql_error:最後一次sql動作錯誤信息 *mysqli_query:執行sql語句,增刪該查 *mysql_select_db:選擇數據庫 *mysql_fetch_array:從查詢結果取1條查詢記錄 *mysql_close:關閉數據庫連接 */ function println($msg) { echo "<br>"; echo $msg; } /**數據庫配置*/ $mysql_server_name = "localhost"; //改成自己的mysql數據庫服務器 $mysql_username = "root"; //改成自己的mysql數據庫用戶名 $mysql_password = ""; //改成自己的mysql數據庫密碼 $mysql_database = "db2"; //改成自己的mysql數據庫名 $mysql_table = "person"; //改成自己的表名 /** * 連接數據庫 */ $con = mysqli_connect($mysql_server_name, $mysql_username, $mysql_password); //連接數據庫 if (!$con) { die(‘Could not connect: ‘ . mysqli_error($con)); } /** * 刪除數據庫:db2 */ $sql_delete_db = "drop database $mysql_database"; if (mysqli_query($con, $sql_delete_db)) { println("$sql_delete_db ok"); } else { println("$sql_delete_db failed:" . mysqli_error($con)); } /** * 創建數據庫:db2 */ $sql_create_db = "create database $mysql_database"; if (mysqli_query($con, $sql_create_db)) { println("create ok"); } else { println("create failed:" . mysqli_error($con)); } /** * 選擇數據庫;db2 */ mysqli_select_db($con, $mysql_database); /** * 創建數據表;person */ $sql_create_table = "create table $mysql_table(id int NOT NULL AUTO_INCREMENT,PRIMARY KEY(id),name varchar(15),age int)"; if (mysqli_query($con, $sql_create_table)) { println("create table ok"); } else { println("create table failed:" . mysqli_error($con)); } /** * 從表(person)中刪除數據; */ $sql_delete = "delete from $mysql_table where age = 200"; if (mysqli_query($con, $sql_delete)) { println("delete table ok"); } else { println("delete table failed:" . mysqli_error($con)); } /** * 在表(person)中插入新數據; */ $age = rand(12, 80);//隨機生成年齡 $sql_inset = "insert into $mysql_table (name,age) value (‘flying_$age‘,$age)"; if (mysqli_query($con, $sql_inset)) { println("insert table ok"); } else { println("insert table failed:" . mysqli_error($con)); } /** * 從表(person)中查詢數據; */ $sql_select = "select * from $mysql_table order by age"; $result = mysqli_query($con, $sql_select); /** 輸出查詢結果 */ while ($row = mysqli_fetch_array($result)) { println($row[‘id‘] . " " . $row[‘name‘] . " " . $row[‘age‘]); } $result->close(); /** * 更新表(person)中數據; */ $sql_update = "update $mysql_table set age = 200 where age < 67"; $result = mysqli_query($con, $sql_update); println($result); if ($result) { println("sql_update table ok"); } else { println("sql_update table failed:" . mysqli_error($con)); } /** * 關閉數據庫連接 */ mysqli_close($con);
PHP : MySQLi【面向過程】操作數據庫【 連接、建庫、建表、增、刪、改、查、關閉】