shell
#!/bin/bash
host=${DB_HOST}
dbname=${DB_NAME}
user=${DB_USER}
pwd=${DB_PWD}
# 只能通过单字母传参数
create_res=`php ${cur_dir}/init/createdb.php -h $host -u $user -p $pwd -d $dbname`
if [[ "$create_res" = 1 ]];
then
Echo_Green "create database $dbname ok."
else
Echo_Red "create database $dbname fail."
fi
php
<?php
header("Content-Type: text/html;charset=utf-8");
error_reporting(E_ALL | E_STRICT);
$param_arr = getopt(‘h:u:p:d:‘);
$host = $param_arr[‘h‘] ?: ‘127.0.0.1‘;
$user = $param_arr[‘u‘];
$pwd = $param_arr[‘p‘];
$dbname = $param_arr[‘d‘];
if (!$user || !$pwd || !$dbname) {
echo 2;
return;
}
// 创建数据库
try {
$conn = new PDO("mysql:host=$host", $user, $pwd);
// 设置 PDO 错误模式为异常
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "CREATE DATABASE IF NOT EXISTS " . $dbname . " DEFAULT CHARSET utf8 COLLATE utf8_general_ci;";
// 使用 exec() ,因为没有结果返回
$conn->exec($sql);
echo 1;
$conn = null;
return;
} catch (PDOException $e) {
// echo $sql . "<br>" . $e->getMessage();
echo 0;
$conn = null;
return;
}