Dockerized PHP&SQL instance; could not find driver - php

I've been stuck on this problem for the last four hours and I've tried everything I could find on stackoverflow but nothing seems to work.
when visiting the appache server in my container I get greeted with an error: driver not found
I supsect this is an issue with PDO since the tut I followed used sqlite
In my Dockerfile i did add the PDO extension but to no result?
This is my docker-compose.yml
services:
php-apache-environment:
container_name: php-apache
build:
context: .
dockerfile: Dockerfile
depends_on:
- db
volumes:
- ./src:/var/www/html/
ports:
- 8000:80
db:
container_name: db
image: mysql
restart: always
environment:
MYSQL_ROOT_PASSWORD: root
MYSQL_DATABASE: bitchan
MYSQL_USER: bit_academy
MYSQL_PASSWORD: bit_academy
ports:
- "9906:3306"
phpmyadmin:
image: phpmyadmin/phpmyadmin
ports:
- '8080:80'
restart: always
environment:
PMA_HOST: db
depends_on:
- db
and this is my Dockerfile
FROM php:8.0-apache
RUN apt-get update && apt-get upgrade -y
RUN docker-php-ext-install pdo pdo_mysql && docker-php-ext-enable pdo pdo_mysql
RUN docker-php-ext-install mysqli && docker-php-ext-enable mysqli
How I connect to the DB on my index.php:
$conn = (require "./db/connectdb.php")();
try {
$stmt = $conn->prepare("SELECT * FROM boards");
$stmt->execute();
$boards = $stmt->fetchAll();
$stmt = $conn->prepare("SELECT posts.*, b.board_name, b.shorthand FROM posts JOIN boards b on b.id = posts.board_id ORDER BY modified_at DESC LIMIT 5;");
$stmt->execute();
$posts = $stmt->fetchAll();
} catch (PDOException $e) {
echo $e->getMessage();
}
and lastely my connectdb.php:
<?php
return function () {
$servername = "db:3306";
$username = "bit_academy";
$password = "bit_academy";
try {
$conn = new PDO("mysql:host=$servername;dbname=bitchan", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo $e->getMessage();
}
return $conn;
}
?>
Also my project dir:
If anyone knows what I'm doing wrong you'd make my day! thanks in advance!

In my case, installing php8-pdo_mysql instead of php-pdo_mysql module was enough.
I'm using alpine image, so I added following line to my Dockerfile:
RUN apk add php8-pdo_myql#php

Related

Trying to access a database in docker containers and php

So I have the following docker-compose file and Dockerfile for php which I am using. These files are in a folder called cca4 and my php files are in a subdirectory of this called src. I am trying to access my mysql database that I am creating however I cannot select anything from it or insert anything. No matter what I do the queries will not work. Any idea on what is wrong? When I go into phpmyadmin I can see that my database is there however it is just not updating or being selected from. I am using nginx as the web server and php-fpm to communicate. I am doing this all from a Linux VM on GCP (Google Cloud Platform) so could be an issue with that maybe too. My php just cannot seem to pick up that there are any tables in the db or rows even after inserting them into phpmyadmin
version: '3.3'
services:
db:
image: mysql:latest
volumes:
- database:/var/lib/mysql
restart: always
environment:
MYSQL_ROOT_PASSWORD: MyDBRoot123
MYSQL_DATABASE: assignment_four_data
MYSQL_USER: php
MYSQL_PASSWORD: php
container_name: db
networks:
- mynet
myphp:
build:
context: .
dockerfile: Dockerfile
depends_on:
- db
expose:
- 9000
restart: always
volumes:
- $PWD/src:/var/www/html
container_name: myphp
networks:
- mynet
mynginx:
depends_on:
- myphp
image: nginx:latest
ports:
- "8080:80"
restart: always
volumes:
- $PWD/src:/var/www/html
- $PWD/src/nginx.ini:/etc/nginx/conf.d/default.conf
container_name: mynginx
networks:
- mynet
phpMyAdmin:
depends_on:
- db
image: phpmyadmin:latest
restart: always
environment:
PMA_HOST: mysql
ports:
- "8082:80"
container_name: phpMyAdmin
networks:
- mynet
volumes:
database: {}
networks:
mynet:
driver: bridge
Here is the dockerfile.
FROM php:7.4-fpm
RUN pecl install igbinary \
&& pecl install redis \
&& docker-php-ext-install mysqli \
&& docker-php-ext-enable redis \
&& echo "extension=redis.so" > /usr/local/etc/php/conf.d/redis.ini
my php code.
<?php
$servername = "db";
$username = "php";
$password = "php";
$databse = "assignment_four_data";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $database);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = 'SELECT * FROM Users';
$result = $mysqli_query($conn, $sql);
if (!$result) {
printf("false");
}
printf("Selected returned %d rows. \n", mysqli_num_rows($result));
?>
The error I keep receiving in my db.php file
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, bool given in /var/www/html/db.php on line 18
Selected returned 0 rows
Is this a docker problem or a mysqli problem? My database is definitely there in phpmyadmin but I just can't get my db.php to communicate with it. Since the mysqli_query is returning false then my query obviously isn't able to work correctly with the mysql database. Even after creating tables and inserting values in phpmyadmin it still cannot detect anything.

Can't connect to Postgres database using PHP PDO and Docker

I am running a Docker app that is built on three images: php:7.4-fpm, nginx:stable-alpine and postgres:alpine.
I was previously attempting to use the image php:7.4-fpm-alpine, but apparently it does not come with the Postgres PDO driver, which was causing a could not find driver error. This post explains more about that, and how to fix it. I followed the steps in that post, including creating a Dockerfile for my PHP FPM service (though I did not create a PHP CLI service), and that remedied my driver issues. However, I am now getting the following error when I try to connect to my PSQL database using PDO:
SQLSTATE[08006] [7] could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 6432?
I know my database is running (on port 6432) because I can access it from my terminal and from Positco, and have created tables after my Docker app was created. I also tried to connect to a database on port 5432 (through which my Postgres desktop app is running), but that did not work either. I also tried to restart my Postgres container, but that did not help.
Here is my PHP:
class Database {
private $connection;
private static $options = array(
PDO::ATTR_EMULATE_PREPARES => FALSE,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
public function __construct() {
try {
$dsn = 'pgsql:host=localhost;port=6432;dbname=db_my_test_app';
$username = 'root';
$password = 'secret';
$connection = new PDO($dsn, $username, $password, self::$options);
$this->connection = $connection;
return $connection;
} catch (PDOException $e) {
exit($e->getMessage());
}
}
}
$database = new Database();
...and my docker-compose.yml file:
version: '3'
networks:
my_test_app:
services:
# nginx
nginx-service:
image: nginx:stable-alpine
container_name: nginx-container
ports:
- "8080:80"
volumes:
- ./app:/var/www/project
- ./nginx/default.conf:/etc/nginx/conf.d/default.conf
depends_on:
- php-fpm-service
- postgres-service
networks:
- my_test_app
# php
php-fpm-service:
build:
context: .
dockerfile: ./php-fpm/Dockerfile
container_name: php-fpm-container
ports:
- "9000:9000"
working_dir: /var/www/project
volumes:
- ./app:/var/www/project
networks:
- my_test_app
# postgres
postgres-service:
image: postgres:alpine
container_name: postgres-container
ports:
- "6432:5432"
volumes:
- ./postgres:/var/lib/postgresql/data
restart: always
environment:
POSTGRES_USER: root
POSTGRES_PASSWORD: secret
POSTGRES_DB: db_my_test_app
networks:
- my_test_app
...and the PHP service Dockerfile (from the aforementioned site):
FROM php:7.4-fpm
RUN apt-get update && apt-get install -y libpq-dev
RUN docker-php-ext-install pdo pdo_pgsql pgsql
RUN ln -s /usr/local/etc/php/php.ini-production /usr/local/etc/php/php.ini
RUN sed -i -e 's/;extension=pgsql/extension=pgsql/' /usr/local/etc/php/php.ini
RUN sed -i -e 's/;extension=pdo_pgsql/extension=pdo_pgsql/' /usr/local/etc/php/php.ini
You are configuring docker under the default network mode: bridge. In order for the php-fpm-service to be able to access the postgres-service you need to make the following modifications:
In the docker-compose.yml file you'll need to add depends_on to php-fpm-service
# php
php-fpm-service:
build:
context: .
dockerfile: ./php-fpm/Dockerfile
container_name: php-fpm-container
ports:
- "9000:9000"
working_dir: /var/www/project
volumes:
- ./app:/var/www/project
networks:
- my_test_app
depends_on:
- postgres-service
In your PHP config, you need modify localhost to postgres-service and using port 5432:
$dsn = 'pgsql:host=postgres-service;port=5432;dbname=db_my_test_app';

PHP Connection refused

I've seen several other posts with this issue. One in particular is this:
Docker MYSQL '[2002] Connection refused'
I tried to add PMA_HOST: mysql as instructed in the previous question.
Here is my docker-compose.yml file looks like:
version: "3.7"
services:
www:
build: .
ports:
- "8001:80"
volumes:
- ./www:/var/www/html/
links:
- db
networks:
- default
db:
image: mysql:8.0
ports:
- "3306:3306"
environment:
MYSQL_DATABASE: myDb
MYSQL_USER: user
MYSQL_PASSWORD: test
MYSQL_ROOT_PASSWORD: test
volumes:
- ./dump:/docker-entrypoint-initdb.d
networks:
- default
phpmyadmin:
image: phpmyadmin/phpmyadmin
links:
- db:db
ports:
- 8000:80
environment:
MYSQL_USER: user
MYSQL_PASSWORD: test
MYSQL_ROOT_PASSWORD: test
volumes:
persistent:
My dockerfile:
FROM php:7.0.30-apache
RUN docker-php-ext-install pdo pdo_mysql
Using the above, when trying to connect to the database, I get the error:
Conneciton failed: SQLSTATE[HY000] [2002] Connection refused
As stated, from the previously asked question, I updated the yml file to include PMA_HOST: mysql under the environment section of the phpmyadmin service. Problem is, when I do that, I can no longer log into the phpmyadmin.
Does anyone see what I am doing wrong and now I can fix it?
*** EDIT ***
Here is my database connection file:
<?php
$host = '127.0.0.1';
$dbname = 'myDb';
define ('DB_USER', 'user');
define ('DB_PASSWORD', 'test');
try
{
$dbc = new PDO("mysql:dbname=$dbname;host=$host", DB_USER, DB_PASSWORD);
$dbc->SetAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage() . "<br/>";
}
?>
Currently, you are trying to use 127.0.0.1 rather than actually setting the host as the service of the docker container you are running for db, to fix this you should change the files to something like so:
docker-compose.yml
version: "3.7"
services:
www:
build: .
ports:
- "8001:80"
volumes:
- www:/var/www/html/
db:
image: mysql:8.0 # also recommend using mariadb over the MySQL image.
ports:
- "3306:3306"
environment:
MYSQL_DATABASE: myDb
MYSQL_USER: user
MYSQL_PASSWORD: test
MYSQL_ROOT_PASSWORD: test
volumes:
- mysql-data:/docker-entrypoint-initdb.d
phpmyadmin:
image: phpmyadmin/phpmyadmin
ports:
- 8000:80
environment:
MYSQL_USER: user
MYSQL_PASSWORD: test
MYSQL_ROOT_PASSWORD: test
volumes:
mysql-data:
phpmyadmin:
database connection file:
<?php
$host = 'db';
$dbname = 'myDb';
define ('DB_USER', 'user');
define ('DB_PASSWORD', 'test');
try
{
$dbc = new PDO("mysql:dbname=$dbname;host=$host", DB_USER, DB_PASSWORD);
$dbc->SetAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage() . "<br/>";
}
?>
this will allow you to use the service to autofill the host, it also then defined the volumes. but this should work and fix the connection refusal as it will find the host address and values now.

Docker Container MySQL and PHP "LOAD DATA LOCAL INFILE" Permission Woes

I've got a docker container setup running on a machine, which has:
A PHP Web Server Container
A MySQL 8.0 Container
A PHPMyAdmin Container
Here's roughly what my docker-compose.yml file has:
version: '3.3'
services:
front:
build:
context: ./front
dockerfile: Dockerfile
container_name: front-end
depends_on:
- db
ports:
- 8000:80
# phpmyadmin
phpmyadmin:
container_name: phpmyadmin
depends_on:
- db
image: phpmyadmin/phpmyadmin
restart: always
ports:
- "8080:80"
environment:
PMA_HOST: db
MYSQL_ROOT_PASSWORD: derp
db:
container_name: mysql8
image: mysql:8.0
command: --default-authentication-plugin=mysql_native_password
restart: always
environment:
MYSQL_ROOT_PASSWORD: root
MYSQL_DATABASE: dev_db
MYSQL_USER: user
MYSQL_PASSWORD: pass
ports:
- 6033:3306
And, for that Front part, here's the Dockerfile
FROM php:7.3.3-apache
RUN apt-get update && apt-get upgrade -y libfreetype6-dev libjpeg62-turbo-dev libpng-dev
RUN docker-php-ext-install mysqli
RUN docker-php-ext-install pdo pdo_mysql
RUN docker-php-ext-configure gd --with-freetype-dir=/usr --with-jpeg-dir=/usr --with-png-dir=/usr
RUN docker-php-ext-install gd
RUN a2enmod rewrite
EXPOSE 80
It's nothing too fancy, right? Probably.
Anyway, I'm working on a feature that allows the upload of a .csv file, which will then get loaded into a MySQL table. I'm running into some interesting errors when I attempt to do this, and after extensive digging and research, I'm not finding a solid solution.
Basically, when I try to execute this query:
try {
$sql = "LOAD DATA LOCAL INFILE '" . $tmpName . "'
INTO TABLE psy_products_temp_sales
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '\"'
LINES TERMINATED BY '\r\n'
(#col1,#col2,#col3,#col4,#col5,#col6)
SET
product_temp_name = #col1,
product_temp_sku = #col2,
product_temp_posted_date = #col3,
product_temp_sales_period = #col4,
product_temp_qty_sold = #col5,
product_temp_total_earned = #col6;";
$sql = $pdo->prepare($sql);
$sql->execute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY);
} catch (Exception $e) {
$output .= "Error: " . $e;
}
My PDO Object is set up like this:
$dsn = "mysql:host=" . $host . ";dbname=" . $db . ";charset=" . $charset;
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::MYSQL_ATTR_LOCAL_INFILE => true,
PDO::ATTR_EMULATE_PREPARES => false
];
try {
$pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
$log->error(
"Could not establish database connection",
["message" => $e->getMessage()]);
throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
Notice the PDO::MYSQL_ATTR_LOCAL_INFILE => true flag is set, and in my php.ini, mysqli.allow_local_infile is set to ON.
So when I attempt to run this, I don't get an error, but MySQL is not reading the uploaded .csv file and loading it into the table. I'm able to actually READ that temporary .csv file directly using fopen(), but MySQL refuses to read it. And these .csv files have tens of thousands of rows, so I'm not looping through each row and running a query. No way.
When I attempt to run this in PHPMyAdmin, I get this error:
LOAD DATA LOCAL INFILE is forbidden, check mysqli.allow_local_infile
Then, when I try running that query in the MYSQL container itself in the CLI, I get this error:
ERROR 2068 (HY000): LOAD DATA LOCAL INFILE file request rejected due to restrictions on access.
The only thing that makes sense here is that the mysql8 container is being denied access to the front container's /tmp directory?
If this is the case, how do I set this up to where permissions are granted? I'm not the most saavy with CLI or docker container cross communication, but there's got to be a way for this to work.
Sorry this got long-winded. Thanks in advance!

docker-compose mysql_pdo connection fail

I have 3 running containers, all is fine (containers are running, database is setted up) except that the PDO connection does not work. There is the error report
Fatal error: Uncaught PDOException: SQLSTATE[HY000] [2002] Connection
refused in /var/www/html/lib/OCFram/PDOFactory.php:9 Stack trace: #0 /var/www
/html/lib/OCFram/PDOFactory.php(9): PDO->__construct('mysql:host=mysq...',
'root', 'root') #1 /var/www/html/lib/OCFram/BackController.php(17):
OCFram\PDOFactory::getMysqlConnexion() #2 /var/www/html/lib/OCFram
/Application.php(69): OCFram\BackController->__construct(Object(App\Frontend
\FrontendApplication), 'Welcome', 'index') #3 /var/www/html/App/Frontend
/FrontendApplication.php(17): OCFram\Application->getController() #4 /var/www
/html/bootstrap.php(30): App\Frontend\FrontendApplication->run() #5 {main}
thrown in /var/www/html/lib/OCFram/PDOFactory.php on line 9
the docker-compose.yml
version: "3.2"
services:
php:
build: './php/'
volumes:
- ./MediterPourGrandir/:/var/www/html/
apache:
build: './apache/'
depends_on:
- php
- mysql
ports:
- "8080:80"
volumes:
- ./MediterPourGrandir/:/var/www/html/
mysql:
image: mysql:5.6.40
environment:
- MYSQL_ROOT_PASSWORD=root
- MYSQL_DATABASE=monsupersite
- MYSQL_USER=root
- MYSQL_PASSWORD=root
ports:
- "3306:3306"
the php docker file
FROM php:7.2.7-fpm-alpine3.7
# RUN apk update; \
# apk upgrade;
# RUN docker-php-ext-install pdo pdo_mysql
# RUN docker-php-ext-install mysqli
RUN apk update --no-cache \
&& apk add --no-cache $PHPIZE_DEPS \
&& apk add --no-cache mysql-dev \
&& docker-php-ext-install pdo pdo_mysql
the pdo connection class
<?php
namespace OCFram;
class PDOFactory
{
public static function getMysqlConnexion()
{
$db = new \PDO('mysql:host=mysql;port=3306;dbname=monsupersite', 'root', 'root');
// $db = new \PDO('mysql:host=mysql;port=3306;charset=utf8', 'root', 'rootpassword');
$db->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
echo "Connected succesfully";
return $db;
}
}
I have done so many unsuccessful try. I'am missing something, but can not find out..... If someone got an idea, it would be great.
Thank you.
I finally can find out.
I did not notice it but after few seconds the mysql container were shutting down. The reason is: by default a mysql container name the MYSQL_USER as 'root', so who wants to use 'root' as MYSQL_USER must not declare it. See the github solved issue https://github.com/docker-library/mysql/issues/129
With these settings it works.
mysql:
image: mysql:5.6.40
environment:
- MYSQL_ROOT_PASSWORD=root
- MYSQL_DATABASE=monsupersite
- MYSQL_PASSWORD=root
ports:
- "3306:3306"
Yes. Or you can check php_info() information does php have enable extension or not.

Categories