rammanoj
rammanoj

Reputation: 497

PHP file_get_contents(): No Such file or directory

I have a class that create databases and tables in it automatically(if no database exist). The class is working fine whenever I run it directly in my localhost but if I call it from another file it is returning an error. The database creation class

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;
}
}
}

I am calling this function in the following manner

public function create_db() {
  $rv = DbSetup::setup_db();
  return $rv;
}

This is returning the folliwing error

file_get_contents(database.sql): failed to open stream: No such file or >directory in /var/www/html/portal/dbsetup/DbSetup.php on line >14
0PDOException: SQLSTATE[42000]: Syntax error or access violation: 1065

Upvotes: 1

Views: 1448

Answers (1)

rammanoj
rammanoj

Reputation: 497

I used

 $_SERVER['DOCUMENT_ROOT'] . '/path to my file/'

and this solved the problem thanks @aynber

Using the normal relative path is creating issues when the instance of the same class is being created from the other file or class. But absolute paths helped in solving it.

Upvotes: 3

Related Questions