How to use throw exception in mysql connect database

I come across this: -

PHP Error Handling: die () Vs trigger_error () Vs throw Exception

and realized that throw exception is better

How can I replace die and use the throw exception here in this code: -

<?php # FileName="Connection_php_mysql.htm" # Type="MYSQL" # HTTP="true" $hostname_db = "localhost"; $database_db = "database"; $username_db = "root"; $password_db = "password"; $db = mysqli_connect($hostname_db, $username_db, $password_db) or die("Unable to connect with Database"); ?> 
+6
source share
2 answers
 try { if ($db = mysqli_connect($hostname_db, $username_db, $password_db)) { //do something } else { throw new Exception('Unable to connect'); } } catch(Exception $e) { echo $e->getMessage(); } 
+9
source

Described here is http://ie2.php.net/manual/en/mysqli.error.php

 if (mysqli_connect_errno()) { throw new RuntimeException("Connect failed: %s\n", mysqli_connect_error()); } 
+3
source

Source: https://habr.com/ru/post/911482/


All Articles