0

I've been researching and trying to figure out what's stopping the connection for 2 days.. Can't seem to figure it out.

I've got my config.php:

<?php 

$host           = 'localhost';
$dbname         = 'test';
$username       = 'root';
$password       = 'root';
$charset        = 'utf8mb4';

$options        = [
    PDO::ATTR_ERRMODE               => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MDOE    => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES      => false,
];

$dsn            = "mysql:host=$host;dbname=$dbname";

?>

Then I have an install.php which allows for my database and table to be created on the server:

<?php 

require 'config.php';

try {
    $connection = new PDO("mysql:host=$host", $username, $password, $options);
    $sql = file_get_contents("data/init.sql");
    $connection->exec($sql);

    echo "Database and table has been created successfully.";
} catch (PDOException $error) {
    echo $sql . "<br>" . $error->getMessage();
}

?>

And lastly I have the actual init.sql that creates the database:

CREATE DATABASE test;

USE test; 

CREATE TABLE users (
    id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY, 
    firstName VARCHAR(30) NOT NULL, 
    lastName VARCHAR(30) NOT NULL,
);

I go into localhost and click the install.php in the directory, which should install the database, but it just gives me HTTP Error 500, I assume because it's not connecting properly.

Is there anything you guys are noticing that I've missed?

  • 1
    Error 500 is just a generic error meant for site users. As a developer, you should turn on [error reporting](https://stackoverflow.com/questions/1053424/how-do-i-get-php-errors-to-display). – El_Vanja Feb 26 '21 at 13:42
  • 2
    You probably should be using `$dsn` in your construction of the PDO object. – Nigel Ren Feb 26 '21 at 13:44
  • And here's also a handy guide for [PDO errors](https://stackoverflow.com/questions/32648371/my-pdo-statement-doesnt-work/32648423#32648423). – El_Vanja Feb 26 '21 at 13:45
  • Thanks @El_Vanja. On that 'error reporting' link you shared, it says I should set display_errors to on in my php.ini; that would go into my config.php file for my case, correct? – Christopher Ansbaugh Feb 26 '21 at 13:46
  • @NigelRen I though that may have caused a problem since the database doesn't technically exist yet, is that incorrect? – Christopher Ansbaugh Feb 26 '21 at 13:49
  • You have to connect to a database, it's the only way (AFAIK) to issue any SQL statements. It doesn't have to be the final database you use, but it needs something. – Nigel Ren Feb 26 '21 at 13:51
  • You could place it in whichever of the two files. As long as those commands get executed, you will see the errors displayed. – El_Vanja Feb 26 '21 at 14:02

0 Answers0