Mysqli運算元據庫

OldBoy~發表於2017-11-28
$mysql_server_name  = "localhost";
$mysql_username   = "root"; 
$mysql_password   = "root"; 
$mysql_database   = "db_name"; 
$mysql_table     = "table_name"; 

// 新建連線
$mysqli = new mysqli($mysql_server_name, $mysql_username, $mysql_password);
/** 除錯連線是否正常 */ if ($mysqli->connect_errno) { die($mysqli->connect_error); exit(); } //刪除資料庫 $sql_delete_db = "drop database $mysql_database"; if ($mysqli->query($sql_delete_db) === true) { die("ok"); } else { die($mysqli->connect_error); } //建立資料庫 $sql_create_db = "create database $mysql_database"; if ($mysqli->query($sql_create_db) === true) { die("ok"); } else { die($mysqli->error); } //選擇資料庫 $mysqli->select_db($mysql_database); //建立資料表 $sql_create_table = "create table $mysql_table(id int NOT NULL AUTO_INCREMENT,PRIMARY KEY(id),name varchar(15),age int)"; if ($mysqli->query($sql_create_table) === true) { die("ok"); } else { die($mysqli->error); } //刪除資料; $sql_delete = "delete from $mysql_table where age = 200"; if ($mysqli->query($sql_delete) === true) { die("ok"); } else { die($mysqli->error); } //插入新資料; $age = rand(12, 80); $sql_inset = "insert into $mysql_table (name,age) value ('flying_$age',$age)"; if ($mysqli->query($sql_inset) === true) { die("ok"); } else { die($mysqli->error); } //查詢資料; $sql_select = "select * from $mysql_table order by age"; if ($result = $mysqli->query($sql_select)) { printf("Select returned %d rows.\n", $result->num_rows); while ($row = $result->fetch_row()) { println("$row[0] $row[1] $row[2]"); } $result->close(); } // 更新表中資料 $sql_update = "update $mysql_table set age = 200 where age < 67"; if ($mysqli->query($sql_update) === true) { die("ok"); } else { die($mysqli->error); } //關閉連線 $mysqli->close();

 

相關文章