首先选择数据库。通过 mysql_select_db() 函数选取数据库。使用 mysql_query()函数用于向 MySQL 连接发送查询或命令,向 mysql_query() 函数添加语句。
(一)创建数据库
CREATE DATABASE 语句用于在 MySQL 中创建数据库。
语法:
CREATE DATABASE database_name
(二)创建表
CREATE TABLE 用于在 MySQL 中创建数据库表。
语法:
CREATE TABLE table_name
(
column_name1 data_type,
column_name2 data_type,
column_name3 data_type,
.......
)
例子:
<?php
$conn = mysql_connect("localhost","root", "");
if (!$conn){
die('无法连接--MYSQL: ' . mysql_error());
}else{
mysql_query("drop database if exists datasafe",$conn);
if (mysql_query("create database datasafe",$conn)){
echo "数据库创建OK<br/>";
}else{
echo "数据库创建失败: " . mysql_error();
}
}
if (mysql_select_db("datasafe", $conn)){
$sql1 = "create table config
(
ckey varchar(64),
value int
)";
$sql2 = "create table filter_rules
(
type int,
value varchar(32)
)";
$sql3 = "create table password
(
type int,
pw varchar(64),
user int
)";
$sql4 = "create table policy
(
app varchar(512),
md5 varchar(32),
r bool,
w bool
)";
$sql5 = "create table status
(
alive timestamp,
cmd varchar(32)
)";
$sql6 = "create table log
(
time timestamp,
user int,
level int,
msg text
)";
$sql=array("$sql1","$sql2","$sql3","$sql4","$sql5", "$sql6");
for($i=0;$i<count($sql);$i++){
if( mysql_query($sql[$i],$conn)){
echo '数据表创建OK'.'<br/>';
}else{
echo '数据表创建ERROR'.'<br/>';
}
}
$sqlstr = "insert into policy(app,md5,r,w) values('/usr/bin/brnvim', 'e446aae508408d1dfea7264fd26292ef', true, true)";
mysql_query($sqlstr, $conn);
$sqlstr = "insert into config(ckey,value) values('password_type', '1')";
mysql_query($sqlstr, $conn);
$sqlstr = "insert into config(ckey,value) values('log_level', '1')";
mysql_query($sqlstr, $conn);
$sqlstr = "insert into password(type, pw, user) values('1', '124567', '0')";
mysql_query($sqlstr, $conn);
$sqlstr = "insert into filter_rules(type, value) values('1', '*.java')";
mysql_query($sqlstr, $conn);
}else{
echo '数据库选择发生异常';
}
mysql_close($conn);
?>