PDO problem

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
NorseMan
Forum Newbie
Posts: 2
Joined: Wed Aug 17, 2022 2:55 pm

PDO problem

Post by NorseMan »

Hi😊 I am new here on phpDN and thank you for the membership here on phpDN.

I got a problem with my new PDO connection. I wanted to change it because I want it to print to screen the error code and an error message if there is no contact with MySQL DB, and give a message if it's connected. But what has happened is like nothing. Or, the connection script won't connect. It writes out the message on the screen.

I have used some hours trying to fix the problem but without luck. So, I ask you "gurus" to be so kind and look over it for me and fix the problem for me? I can't manage to fix it myself. Please😊

Code: Select all

<?php
define("host",'myhost'); // Default database host.
define("dbname", 'mydbname');   // Default database name.
define("username",'myusername');	// Deafault database username .
define("password",'mypassword');		    // Default database password.

function pdoConnect($dbname=database)
{
    $db = new PDO("mysql:host=".HOST.";dbname=$dbname;charset=utf8",USERNAME,PASSWORD);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
    $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    return $db;
}
try {
$pdo = new PDO('mysql:host=mysqlserver.no;mydbname=mydb', 'myusername',
'mypassword');
$output = 'Database connection established.';
}
catch (PDOException $e) {
$output = 'Unable to connect to the database server: ' . $e->getMessage();
}
?>
benanamen
Forum Newbie
Posts: 19
Joined: Sun Nov 15, 2015 11:57 am

Re: PDO problem

Post by benanamen »

I want it to print to screen the error code and an error message
This is absolutely the wrong thing to do. You never ever output internal system errors to the user. That information is useless to the user but very valuable to a hacker. DO NOT DO IT!

Log the errors instead. If you need to see the system errors for development purposes, you should have a local dev with error reporting turned on. If you are on Windows I would highly recommend using Laragon. It is much better than XAMPP.

https://laragon.org/


As for your code, the The $pdo line should be in the function and then return $pdo. Also, you created the function pdoConnect but never call it anywhere.
Take a look at my "Clean PDO" code on my Github.
https://github.com/benanamen/clean-pdo
Post Reply