Question

I have this script which connects to my database, and has a catch case for creating the database if one does not exist, currently the error in the sql connect doesnt seem to trigger the try catch

$host = "localhost";
$username = "root";
$password = "";
$database = "webscrp";

try {

    $con = mysqli_connect(
            $host,
            $username,
            $password,
            $database
        );

  }

  catch (Exception $e) { 
    $conE = mysqli_connect(
            $host,
            $username,
            $password
        );

    $q1 = "CREATE DATABASE webscrp";
    $q2 = "CREATE TABLE product
            (
                ProductID int NOT NULL AUTO_INCREMENT,
                ProductName varchar(500),
                ProductDescription varchar(2000),
                ProductPhotoLink varchar(200) NULL,
                ProductPrice decimal(10,2),
                ProductCategory varchar(300),
                ProductStock int(100),
                ProductDatePosted timestamp DEFAULT CURRENT_TIMESTAMP,
                PRIMARY KEY (ProductID)
                )";

    mysqli_query($conE, $q1);
    mysqli_query($conE, $q2);

    $con = mysqli_connect(
        $host,
        $username,
        $password,
        $database
    );

  }

I tried the SQL in my database and it executes fine.

Was it helpful?

Solution

When you are not able to connect to a database, it generates a warning and not a exception. So the execution does not go to catch statement as there is no exception occuring here. You should do it this way:

<?php
    $con = mysqli_connect(
            $host,
            $username,
            $password,
            $database
        );

    if(!$con) {
        $con = mysqli_connect(
            $host,
            $username,
            $password
        );
        $q1 = "CREATE DATABASE $database";
        mysqli_query($conE, $q1);
        $con = mysqli_connect(
        $host,
        $username,
        $password,
        $database
        );
    }

    $q2 = "CREATE TABLE product
        (
            ProductID int NOT NULL AUTO_INCREMENT,
            ProductName varchar(500),
            ProductDescription varchar(2000),
            ProductPhotoLink varchar(200) NULL,
            ProductPrice decimal(10,2),
            ProductCategory varchar(300),
            ProductStock int(100),
            ProductDatePosted timestamp DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (ProductID)
            )";

    mysqli_query($con, $q2);

?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top