標籤:隨機 動作 使用者名稱 使用者 建庫 ima host serve val
<?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【面向過程】操作資料庫【 串連、建庫、建表、增、刪、改、查、關閉】