$db_host = '127.0.0.1'; //数据库主机名称,一般都为localhost
$db_user = 'root'; //数据库用户帐号,根据个人情况而定
$db_passw = 'root'; //数据库用户密码,根据个人情况而定
$db_name = 'mydb'; //数据库具体名称,以刚才创建的数据库为准
// 创建连接
//$conn = new mysqli($servername, $username, $password);
$conn = new mysqli($db_host, $db_user, $db_passw, $db_name); //创建对象
// 检测连接
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
//echo "连接成功";
创建数据库
/**
* 创建数据库
* */
//$sql = "CREATE DATABASE myDB";
//if ($conn->query($sql) === TRUE) {
// echo "数据库创建成功";
//} else {
// echo "数据库创建失败:" . $conn->error;
//}
创建数据表
/**
* 使用sql创建数据表
*/
$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL ,
lastname VARCHAR(30) NOT NULL ,
email VARCHAR(50),
reg_date TIMESTAMP )";
if ($conn->query($sql) === TRUE) {
echo "数据表创建成功";
} else {
echo "创建数据表错误:" . $conn->error;
}
插入数据
$sql = "INSERT INTO MyGuests(firstname,lastname,email)
VALUES ('Johdn','Dode','john@qq.com')";
if ($conn->query($sql) === true) {
echo "新纪录插入成功";
} else {
echo "Error:" . $sql . "<br>" . $conn->error;
}
批量插入数据
$sql = "INSERT INTO MyGuests (firstname,lastname,email)
VALUES ('Johdn','Dode','john@qq.com'),('Jhn','aoe','aoe@qq.com'),('ihn','iDoe','john@qq.com')";
if ($conn->query($sql) === true) {
echo "新纪录插入成功";
} else {
echo "Error:" . $sql . "<br>" . $conn->error;
}
预处理插入数据
/**
* 预处理,及绑定
* 参数有以下四种类型:
* i - integer(整型)
* d - double(双精度浮点型)
* s - string(字符串)
* b - BLOB(binary large object:二进制大对象)
* 每个参数都需要指定类型。
* */
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname,lastname,email) VALUES (?,?,?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);
//设置参数并执行
$firstname = "Jonl";
$lastname = "Lat";
$email = "1163534699@qq.com";
$stmt->execute();
$firstname = "Mary";
$lastname = "Dooley";
$email = "98564@qq.com";
$stmt->execute();
$firstname = "ljlj";
$lastname = "asdfa";
$email = "asdfa@qq.com";
$stmt->execute();
echo "新纪录插入成功!!";
$stmt->close();
读取数据,及生成json数据
/**
* 读取数据
*/
mysql_query("set names 'utf8'");
$sql = "SELECT id,name,content,reg_date FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
//输出每行的数据
$users = array();
$i = 0;
while ($row = $result->fetch_assoc()) {
header('Content-type:text/html;charset=utf-8');
echo "<br>id:" . $row["id"] . "- Name:" . $row["name"] . "-内容"
. $row["content"] . "时间" . $row["reg_date"];
$users[$i] = $row;
$i++;
}
$json_string = json_encode(array('events' => $users), JSON_UNESCAPED_UNICODE);
// 写入文件
file_put_contents('test.json', $json_string);
echo "<br>写入成功";
} else {
echo "0个结果";
}