I was working with really old PHP I learned years ago and decided to finally update it, so I changed all the mysql
to mysqli
. I noticed some MySQLi functions require you to pass the connection in the parameters. I ended doing something like this:
$con = getCon();
$result = mysqli_query($con, "SELECT * FROM sometable WHERE deleted=0");
getCon()
is a return like return Database::getConnection();
that uses the next class:
class Database {
private static $db;
private $connection;
private function __construct() {
$servername = "localhost";
$username = "...";
$password = "...";
$dbname = "...";
$this->connection = new mysqli($servername, $username, $password, $dbname);
}
function __destruct() {
$this->connection->close();
}
public static function getConnection() {
if(self::$db == null) {
self::$db=new Database();
}
return self::$db->connection;
}
}
I don't like adding the line $con = getCon();
to the top of every function that uses mysqli_query
. Is there a way to avoid this? (it is one extra line multiplied by every function that uses mysqli
calls)
1 Answer 1
Use object-oriented style:
$con = getCon();
$result = $con->query("SELECT * FROM sometable WHERE deleted=0");
Refer to Example #1 on the PHP documentation for mysqli_query(), as well as the Dual interface quick start page for more information.
Looking back at the functions like deprecated mysql_query() it appears that it used the "last link opened by mysql_connect() ". If you really wanted to replicate that, you could define a wrapper function (potentially using call_user_func()):
function mysqli_query_con($query, $resultmode = MYSQLI_STORE_RESULT)
$con = getCon();
return mysqli_query($con, $query, $resultmode);
}
-
\$\begingroup\$ hey sorry for all the trouble, I myself wasn't sure what I wanted, but I fixed this way pastebin.com/H9KxEANr \$\endgroup\$ajax333221– ajax3332212017年10月02日 20:58:12 +00:00Commented Oct 2, 2017 at 20:58
-
\$\begingroup\$ alright- cool. I guess
call_user_func()
isn't required, but it is usable \$\endgroup\$2017年10月02日 20:59:34 +00:00Commented Oct 2, 2017 at 20:59