I am a beginner in PHP programming and would like help with a little question. Please take a look at the code below:
PHP Code
<?php
class Account
{
public function register()
{
$db_link = mysql_connect("localhost","root",""); // Create Connection
if (!$db_link) // Check connection
{
die(mysql_error());
}
mysql_close($db_link); // Close Connection
}
public function login()
{
$con = mysql_connect("localhost","root","") // create connection
if (!$con) // create connection
{
die(mysql_error());
}
mysql_close($con); //close connection
}
}
?>
My question is if creating individual db links for every single one of the object's methods is the best way to go? Is there a better or alternative way to do this? Hopefully I've explained well enough.
Would the following be correct?
$x = new Account("localhost", "root", "");
-and x would have its own connection...and then close when its done?
mysql_connect()andmysql_close()at the beginning and at the end of your whole program. There is no need to instantiate a connection at every method.mysql_at all, particularly for somebody just coming into the language and is starting a new project.__constructand implement__destructmethod to destroy connection when object is destroyed.