Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use throw exception in mysql database connect [duplicate]

I come across this:-

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

and understood that throw exception is better

How can i replace die and use 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"); 
?>
like image 988
Django Anonymous Avatar asked Mar 23 '12 09:03

Django Anonymous


People also ask

How do I ignore duplicate entries in MySQL?

Use the INSERT IGNORE command rather than the INSERT command. If a record doesn't duplicate an existing record, then MySQL inserts it as usual. If the record is a duplicate, then the IGNORE keyword tells MySQL to discard it silently without generating an error.


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();
}
like image 56
slash197 Avatar answered Nov 15 '22 19:11

slash197


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

if (mysqli_connect_errno()) {
    throw new RuntimeException("Connect failed: %s\n", mysqli_connect_error());
}
like image 22
floriank Avatar answered Nov 15 '22 18:11

floriank