PDO connection with err check

Here is my DB connection:

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

When it comes to error and connection check, or I start at the other end…:
I know the error check works. I print both to screen. Checked it by entering both correct and incorrect passwords. So I’m sure it works, but does it only work on the user details, or will it work on other errors as well? For example, if there is no connection with the DB server, if it is on a separate server, for example?

It will work for anything that prevents a connection.

You should only catch and handle user recoverable database errors in your code, such as when inserting/updating duplicate or out of range data values. All other errors are either due to programming mistakes or a failed database connection. The user on your site doesn’t need to know anything about these other types of errors and you don’t want to give hackers useful information (the connection error, which a hacker can trigger by flooding your site with requests that consume all the database connections, contains the host name or ip address, the username, if you are using a password or not, and web server path information.) For these other types of errors, simply let php catch and handle them, where php will use its error related settings to control what happens with the actual error information (database statement errors will ‘automatically’ get displayed/logged the same as php errors.) This will let you remove unnecessary try/catch logic, simplifying your code.

Your connection code should ALSO -

  1. set the character set to match your database tables, so that no character conversion occurs over the connection. this is also important when using emulated prepared queries, so that sql special characters in a value won’t be able to break the sql query syntax, which is how sql injection is accomplished.
  2. set the error mode to exceptions, so that exceptions will be used for all the other database statements (this is actually the default for php8+, but it doesn’t hurt to set it in your code.)
  3. set emulated prepared queries to false, you want to run true prepared queries whenever possible.
  4. set the default fetch mode to assoc, so you don’t need to specify it in each fetch statement.
  1. set the character set to match your database tables, so that no character conversion occurs over the connection. this is also important when using emulated prepared queries, so that sql special characters in a value won’t be able to break the sql query syntax, which is how sql injection is accomplished.

Yes, I have put it in here now because of a script block Strider put together for me . Is it this you meant?

  1. set the error mode to exceptions, so that exceptions will be used for all the other database statements (this is actually the default for php8+, but it doesn’t hurt to set it in your code.)

I am running PHP 7,4. If i am running 8 or 8,1 i get a totally white site. I bet that is a PHP version problem. So i have to re-write the code later.

  1. set emulated prepared queries to false, you want to run true prepared queries whenever possible.

Done. Strider helped me to with this.

  1. set the default fetch mode to assoc, so you don’t need to specify it in each fetch statement.

Done that to. Strider helped me there to. I didn’t see it before you and another forum user opened my eyes. Thanks to both of you :smiley:

Here is some of what Strider put together for me:

$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;

By no means an expert, but, due to the virus situation here in China I had to make online classwork. Of course, I got some help from here. Like phdr said,I don’t think you want to echo any and all errors to the user

After registering, the student, or user, logs in with an email and a password.

so first check the email:

$stmt = $pdo->prepare('SELECT * FROM allstudents21BE2 WHERE email = :email');
$stmt->execute(['email' => $email]);
if($stmt->rowCount() == 0){
	$_SESSION['loginerror'] = 'No account associated with the email: ' . $email;
	header('location: index.php');				
	exit();}

If the email checks out, check the password:

//check the password now
if($stmt->rowCount() > 0){
   //get the row
   $user = $stmt->fetch();
   $studentnr = $user['studentnr'];
   $weeknr = 'Week16';
	// first check the password. If incorrect, bale out
	//validate the password with $user password
	if(!password_verify($password, $user['password'])){
	$_SESSION['loginerror'] = '密码不对的 Incorrect password!!';					
	header('location: index.php');
	exit();
	}

I had a lot of complicated stuff to check and record the time of login for attendance, but then, if the email and password are ok, just put the address you want the user to go to:

header('location: this_week_class_page.php');
exit();

echo the $_SESSION[‘loginerror’] on the login webpage, or any other $_SESSION errors you want:

<div>
If there is a problem, you will see a message here: <br>
<?php echo $_SESSION['loginerror']; ?>
</div><br>

Thank God the virus situation is over!

Sponsor our Newsletter | Privacy Policy | Terms of Service