note 116243 added to mysqli.construct
| From: | linguafranca2003 at yahoo dot com | Date: | Fri, 28 Nov 2014 17:21:38 +0000 |
| Subject: | note 116243 added to mysqli.construct | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-201037@lists.php.net to get a copy of this message | ||
mysqli can succeed in surprising ways, depending on the privileges granted to the user. For example,
GRANT USAGE ON *.* TO 'myuser'@'localhost' IDENTIFIED BY PASSWORD
'mypassword';
GRANT ALL PRIVILEGES ON
database_a.* TO 'myuser'@'localhost';
CREATE DATABASE database_b;
<?php
$db = new mysqli('localhost', 'myuser', 'mypassword',
'database_b');
if ($db->connect_error) {
die('Connect Error (' . $db->connect_errno . ') '
. $mysqli->connect_error);
}
printf("SQLSTATE: %s\n", $this->db->sqlstate);
printf("Warning Count: %s\n", $db->warning_count);
$db->close();
?>
Will output:
SQLSTATE: 00000
Warning Count: 0
So, life is good â you're connected to the database and executing mysqli methods. Except,
life isn't good, because you aren't actually using database_b because myuser doesn't
have any privileges on it. You won't catch this until you try to perform a later operation,
when you'll get an error, "MYSQL Error: No database selected", and find yourself
scratching your head and thinking "what do you mean, of course I have a database selected; I
selected one when I called the constructor".
As a result, you may want to perform an additional check after connecting to mysql, to confirm that
you're actually connected not just to the mysql server, but to the actual database:
<?php
$db = new mysqli('localhost', 'myuser', 'mypassword',
'database_b');
if ($db->connect_error) {
die('Connect Error (' . $db->connect_errno . ') '
. $mysqli->connect_error);
} elseif ($result = $db->query("SELECT DATABASE()")) {
$row = $result->fetch_row();
if ($row[0] != 'database_b') {
//oops! We're connected to mysql, but not to database_b
}
}
?>
----
Server IP: 72.52.91.14
Probable Submitter: 2a00:1028:9195:ded2:3963:2813:5ab0:7b36
----
Manual Page -- http://php.net/manual/en/mysqli.construct.php
Edit -- https://master.php.net/note/edit/116243
Del: integrated -- https://master.php.net/note/delete/116243/integrated
Del: useless -- https://master.php.net/note/delete/116243/useless
Del: bad code -- https://master.php.net/note/delete/116243/bad+code
Del: spam -- https://master.php.net/note/delete/116243/spam
Del: non-english -- https://master.php.net/note/delete/116243/non-english
Del: in docs -- https://master.php.net/note/delete/116243/in+docs
Del: other reasons-- https://master.php.net/note/delete/116243
Reject -- https://master.php.net/note/reject/116243
Search -- https://master.php.net/manage/user-notes.php