0

我是 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 调用这个函数。但我不确定在哪里关闭此连接。我应该在函数内部关闭它吗?我应该在功能下关闭它吗?我应该在函数顶部连接并关闭函数底部吗?

顺便说一句,可以随意改进我的代码。

4

2 回答 2

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 连接

于 2014-04-19T18:11:31.460 回答
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);


}
于 2014-04-19T19:39:07.997 回答