我有以下sql,我需要运行来创建数据库并为它分配用户等...
我最好只使用 PHP 创建所有这些,还是我实际上可以运行这个.sql文件来创建这一切?
CREATE DATABASE 'ppa'
CREATE USER 'ppa_user'@'localhost' IDENTIFIED BY 'fSMthSGKVpDtcxDv';
GRANT SELECT, INSERT, UPDATE ON 'ppa'.* TO 'ppa_user'@'localhost';
CREATE TABLE 'ppa'.'users' (
'id' INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
'email' VARCHAR(30) NOT NULL,
'password' CHAR(32) NOT NULL,
'perms' VARCHAR(30) NOT NULL,
'salt' CHAR(32) NOT NULL
) ENGINE = InnoDB;
CREATE TABLE 'ppa'.'login_attepts' (
'user_id' INT(11) NOT NULL,
'time' VARCHAR(30) NOT NULL
) ENGINE = InnoDB;
INSERT INTO 'ppa'.'users' VALUES(1, 'admin', 'af453d19feb2520c8c0d30fb39ebd211', 'admin', '8269ebbf4c9cf901170ad58238deabb1');
密码只是随机生成的,所以目前并不重要。
这是执行.sql文件并运行.sql文件中写入的所有查询的函数
<?php
//Import (executes) the SQL passed as parameter making some proper adaptations.
function dbImportSQL($sql, $needle = '')
{
$sql = str_replace('/*TABLE_PREFIX*/', DB_TABLE_PREFIX, $sql);
$sentences = explode( $needle . ';', $sql);
// PREPARE THE QUERIES
$var_l = count($sentences);
$s_temp = '';
for($var_k=0;$var_k<$var_l;$var_k++) {
$s = $s_temp.$sentences[$var_k];
if(!empty($s) && trim($s)!='') {
$s .= $needle;
$simple_comma = substr_count($s, "'");
$scaped_simple_comma = substr_count($s, "''");
if(($simple_comma-$scaped_simple_comma)%2==0) {
$sentences[$var_k] = $s;
$s_temp = '';
//echo "[OK] ".$s." <br />";
} else {
unset($sentences[$var_k]);
$s_temp = $s.";";
//echo "[FAIL] ".$s." <br />";
}
} else {
unset($sentences[$var_k]);
}
}
foreach($sentences as $s) {
$s = trim($s);
if( !empty($s) ) {
$s = trim($s);// . $needle;
if( $this->db->query($s) ) {
$this->debug($s);
} else {
$this->debug($s . ' | ' . $this->db->error . ' (' . $this->db->errno . ')', false);
}
}
}
$this->db_errno = $this->db->errno;
if ($this->db_errno != 0) return false;
return true;
}
?>
注意:请将$this->db
替换为您的数据库对象
然后在创建函数后,现在使用以下代码调用它
$path = 'struct.sql';// define the path for the .sql file
$sql = file_get_contents($path);
dbImportSQL($sql);//this will read all the queries from the sql file and execute them
下面是示例sql(struct.sql)文件,如果需要,您可以根据需要在函数中进行更改
CREATE TABLE IF NOT EXISTS /*TABLE_PREFIX*/t_cpviewer_plan_headers (
`sid` int(11) NOT NULL AUTO_INCREMENT,
`cp` text NOT NULL,
`name` text NOT NULL,
`address` text NOT NULL,
`pages` int(11) NOT NULL DEFAULT '0',
`uploaded` date NOT NULL,
`status` varchar(255) NOT NULL,
PRIMARY KEY (`sid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS /*TABLE_PREFIX*/t_cpviewer_plan_levels (
`sid` int(10) unsigned NOT NULL AUTO_INCREMENT,
`CP` text NOT NULL,
`image` varchar(255) NOT NULL,
`page` int(4) NOT NULL,
`level` int(3) NOT NULL,
`label` text NOT NULL,
PRIMARY KEY (`sid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
ALTER TABLE /*TABLE_PREFIX*/t_item ADD cp_number VARCHAR( 255 ) NOT NULL AFTER dt_expiration ,
ADD cp_level INT( 11 ) NOT NULL AFTER cp_number;
您可以将文件读入字符串并使用标准方法进行插入。
像phpMyAdmin这样的工具具有.sql导入功能。