在PHP上关闭MySQL连接的位置

时间:2014-04-19 18:05:19

标签: php mysql mysql-connect

我在PHP& MySQL和我有关于mysql_connect和mysql_close

的问题

这是我的代码(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

我从page.php调用此函数。但我不确定在何处关闭此连接。我应该在功能内关闭吗?我应该在功能下关闭吗?我应该在功能顶部连接并关闭功能的底部吗?

BTW可以随意改进我的代码。

2 个答案:

答案 0 :(得分:0)

您可以更改此部分

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

$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);
和@ fred-ii一样说,没有必要关闭mysql连接

答案 1 :(得分:0)

请记住,当您需要关闭数据库连接时,请首先确保在关闭函数上面编写所有脚本,在这种情况下将其写入函数中,假设您在此之后不需要连接。

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

        //close connection here ......
       mysqli_close($link);


}