我有一个自动创建数据库和表的类(如果没有数据库)。每当我直接在我的localhost中运行它时,该类工作正常,但如果我从另一个文件调用它,则返回错误。数据库创建类
class DbSetup
{
public static function setup_db()
{
try {
$connect_server = new PDO("mysql:host=localhost", 'root', 'rammanoj888116' );
$create_default = $connect_server->prepare("CREATE DATABASE manoj");
$create_default->execute();
$connect_server = new PDO("mysql:host=localhost;dbname=manoj", 'root','rammanoj888116' );
$connect_server->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$file = file_get_contents( 'database.sql' );
$create_tables = $connect_server->prepare($file);
$create_tables->execute();
$create_tables->closeCursor();
$file_2 = file_get_contents( 'exam_tables.sql' );
$create_tables_2 = $connect_server->prepare($file_2);
$create_tables_2->execute();
echo "1";
}
catch(Exception $e) {
echo "0";
echo $e;
}
}
}
我以下列方式调用此函数
public function create_db() {
$rv = DbSetup::setup_db();
return $rv;
}
这将返回以下错误
file_get_contents(database.sql):无法打开流: /var/www/html/portal/dbsetup/DbSetup.php 在线上没有此类文件或>目录> 14
0PDOException:SQLSTATE [42000]:语法错误或访问冲突:1065
答案 0 :(得分:2)
我用过
$_SERVER['DOCUMENT_ROOT'] . '/path to my file/'
这解决了问题,谢谢@aynber
使用正常相对路径在从其他文件或类创建同一类的实例时会产生问题。但绝对路径有助于解决它。