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();
}
?>
Post Reply