Mysqli操作数据库

$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();

 

posted @ 2017-11-28 15:24  温柔的风  阅读(502)  评论(0编辑  收藏  举报