2
\$\begingroup\$

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)

asked Sep 30, 2017 at 18:23
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

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);
}
answered Sep 30, 2017 at 18:31
\$\endgroup\$
2
  • \$\begingroup\$ hey sorry for all the trouble, I myself wasn't sure what I wanted, but I fixed this way pastebin.com/H9KxEANr \$\endgroup\$ Commented Oct 2, 2017 at 20:58
  • \$\begingroup\$ alright- cool. I guess call_user_func() isn't required, but it is usable \$\endgroup\$ Commented Oct 2, 2017 at 20:59

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.