Search code examples
phpmysqlmysql-connect

Where to Close MySQL Connection on PHP


I'm newbie at PHP & MySQL and I've a question about mysql_connect and mysql_close

Here is my code (functions.php):

$link = mysql_connect("localhost","root","") or die("error");
mysql_select_db("dbName",$link) or die("error 2");
mysql_query("SET NAMES UTF8");

function get_title($param)
{
        //top of the function
    $sql = sprintf("SELECT title FROM pages WHERE id='%s'",
    mysql_real_escape_string($param));
    $result = mysql_query($sql);
    $title = mysql_result($result, 0,0);
    echo trim($title);
        //inside the function
        //bottom of the function
}
//under the function

I'm calling this function from page.php. But I'm not sure where to close this connection. Should I close it inside the function? Should I close it under the function? Should I connect at top of the function and close bottom of the function?

BTW feel free to make better my code.


Solution

  • You could change this part

    $result = mysql_query($sql);
    $title = mysql_result($result, 0,0);
    echo trim($title);
    

    to

    $result = mysql_query($sql) or some_exception_function("ERROR IN QUERY:".$sql."<br>".mysql_error()); // here you can send an email with error, or whatever you want, if some error occurs
    $row = mysql_fetch_array($result);
    $title = $row['title']; // so you always fetch desired column by it's name
    echo trim($title);
    

    and like @fred-ii said, there is no need to close mysql connection