NameSilo

One MYSQL connection per function or big no no?

Spaceship Spaceship
Watch
Impact
4
I'm currently learning how to make PHP and MYSQL be buddies. So far I've created a connection function and I use it in every other function in order to shorten the code.

Since I'm connecting to the MYSQL server (service on the apache server?) every single relevant function call, and I making huge overhead? Or is this normal behavior for talking with MYSQL?

Should I just call the connect function, run my other functions, and then close?

Thanks.
 
0
•••
The views expressed on this page by users and staff are their own, not those of NamePros.
Theres no need to open up the connection for every function if you use them one after another.
Usually you can connect per script or if you use classes in PHP The Singleton Design Pattern for PHP
 
0
•••
Adamo answered it well man, too many connections causes an overload on the mysql server. it is better to use just one connection per session.
 
0
•••
Theres no need to open up the connection for every function if you use them one after another.
Usually you can connect per script or if you use classes in PHP The Singleton Design Pattern for PHP
I do something like that :)
PHP:
class db
{
	private static $instance;

	private function __construct(...)
	{
		//
	}

	public static function getInstance()
	{
		if (!self::$instance)
		{
			self::$instance = new self();
		}
		return self::$instance;
	}
}

$db = db::getInstance();
Of course there's a lot more to it than that.
 
0
•••
  • The sidebar remains visible by scrolling at a speed relative to the page’s height.
Back