Echoing mysqli_connect_errno not working

2019-06-10 10:28发布

问题:

Started learning PHP and after learning the basic stuff, which was easy because I learn C++ at school and most of the stuff is similar, I started with mysql. Everything works fine, but I can't get to work the connect_errno working.

Copied and pasted this http://php.net/manual/en/mysqli.connect-errno.php into my code with no success.

My few lines of code:

<?php

error_reporting(0);

$db = mysqli_connect('127.0.0.1' , 'root' , '' , 'mydb');

if ($db->connect_errno) {
    die('Connect Error: ' . $db->connect_errno);
}

?>

I've also tried an example from a tutorial, no success.

EDIT: ANSWER IS BELOW!

回答1:

You mixed the Object-oriented approach and the Procedural approach. Below is the example for the OO approach.

$db = new mysqli('127.0.0.1' , 'root' , '' , 'mydb');

if ( $db->connect_errno ) {
    die('Connect Error: ' . $db->connect_errno);
}

error_reporting( 0 ); will suppress errors, so if you're in a debugging workflow and need to see those errors, you'll need to update the error reporting directive to error_reporting( E_ALL );.

Also, I updated the db name to mydb as reflected in the code (I switched that out on my local machine to experiment with connections/errors).



回答2:

You're using a mix of OO and procedural code. mysql_connect does not return an object; it returns a db handle. You can get its error number using the following:

$db = mysqli_connect('127.0.0.1' , 'root' , '' , 'mydb');
$err = mysqli_connect_errno();


标签: php mysql mysqli