-3

I am trying to connect to databse on my server by using this code:

<?php
 $username = "username";
 $servername = "localhost";
 $password = "password";
 echo "Before connection";

 // Create connection
 $conn = new mysqli($servername, $username, $password);
 // Check connection
 if ($conn->connect_error) {
     die("Connection failed: " . $conn->connect_error);
 }
 echo "Connected successfully";
?>

But code after $conn = new mysqli($servername, $username, $password); is not executing. When i try to echo anything after it I do not get output. Code before that line works as expected. I do not get any errors from php.

I am not sure what is problem. Could it be something server related? I did try to add:

ini_set('display_errors',1);
 error_reporting(E_ALL); 

but it didn't help, no errors have been displayed.

I have been trying many things from stackoverflow (and other places) but they didnt help, some examples:

Connecting to a mysql database from php, error but no error shown?

Connection of MySQL with PHP not working

guber90
  • 91
  • 1
  • 9
  • 2
    Did you add those `ini_set` / `error_reporting` lines at the very beginning of your script? You should have log files stored by your webserver in any case. – Jeto Dec 10 '19 at 20:50
  • @Jeto yes I did, and there are no errors in webservers log either... – guber90 Dec 10 '19 at 20:59
  • I just use default server error handler. But this is school webserver so it might be lacking... – guber90 Dec 10 '19 at 21:03

1 Answers1

1

There are multiple ways to handle errors

Simplest of all, use try catch while connecting

<?php
 $username = "username";
 $servername = "localhost";
 $password = "password";
 echo "Before connection";

 // Create connection
 try {
 $conn = new mysqli($servername, $username, $password); } catch(\Exception $e) { var_dump ('oopss... this is the error', $e)}
 // Check connection
 if ($conn->connect_error) {
     die("Connection failed: " . $conn->connect_error);
 }
 echo "Connected 
Radha Mata
  • 44
  • 2
  • __Who__ told you that `new mysqli` __throws exception__? – u_mulder Dec 10 '19 at 20:54
  • Well it did help thank you I got error: Fatal error: Uncaught Error: Class 'mysqli' not found in... So now is just to try to fix that :). – guber90 Dec 10 '19 at 20:57
  • This was not necessarily to catch new mysqli errors but anything that could potentially go in between, and in OP's case that seemed more likely – Radha Mata Dec 10 '19 at 20:59