I know this type of question as probably been asked a couple of times, but they all have something to do with laravel, in my case this is vanilla php with no framework.
I have a form that that will collect form from users and save it into the database as it should, but i keep getting this error about MYSQL Error: SQLSTATE[HY000] [2002] No such file or directory
. Here is my database config file and the file that includes it:
// Database config
<?php
$host = 'localhost';
$user = 'admin';
$password = '123456';
$db_name = 'nairobi';
$dsn = 'mysql:host='.$host.';dbname='.$db_name;
$options = [
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
];
// Create a new PDO instance
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
print "Error: " . $e->getMessage() . "</br>";
die();
}
?>
<?php
require "./library/Database.php";
if (isset($_POST['submit'])) {
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email = $_POST['email'];
$sql = 'INSERT INTO TABLE members(first_name, last_name, email)
VALUES (:first_name, :last_name, :email)';
$stmt = $dbh->prepare($sql);
$stmt_value = [
':first_name' => $first_name,
':last_name' => $last_name,
':email'=>$email
];
$stmt->execute($stmt_value);
}
?>
Yes, I know the script that process the form is not secure.
Also, I get the following error when I access the page
Fatal error: Uncaught PDOException: SQLSTATE[HY000] [2002] No such file or directory in /var/www/html/library/Database.php:19 Stack trace: #0 /var/www/html/index.php(2): require() #1 {main} thrown in /var/www/html/library/Database.php on line 19
If needed, this is the sql I have gone with
CREATE TABLE IF NOT EXISTS members(
member_id INT AUTO_INCREMENT NOT NULL PRIMARY KEY,
first_name VARCHAR(255) NOT NULL,
last_name VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL UNIQUE,
reference_code INT NOT NULL
);
This entire project is also inside a docker container, here is the docker-compose.yml
file
version: '3.7'
services:
php:
container_name: nairobi_php
build:
context: ./
volumes:
- './src:/var/www/html'
depends_on:
- mysql
ports:
- 80:80
mysql:
container_name: nairobi_mysql
image: mysql:8.0
environment:
MYSQL_ROOT_PASSWORD: CUeHpADRmZCtnTFGctxp
MYSQL_DATABASE: nairobi
MYSQL_USER: admin
MYSQL_PASSWORD: 123456
restart: always
command: --default-authentication-plugin=mysql_native_password
ports:
- 3306:3306
adminer:
image: adminer
restart: always
ports:
- 8080:8080