php - PHP 上哪里关闭 MySQL 连接

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

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

最佳答案

您可以更改这部分

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

关于php - PHP 上哪里关闭 MySQL 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23173616/

相关文章:

php - mysql_connect 第二次不起作用

php - 在 PHP 中从没有 ffmpeg 的视频创建缩略图

javascript - 如果返回的数据是 javascript,$.ajax 会自动执行脚本吗?

php - WordPress中如何根据坐标显示用户?

mysql - SQL连接具有一些重叠值的2个表

php - 如何使用php中的textarea向数据库中插入数据?

php - 如何正确地将此 mySQL 查询执行到 PHP 文件中并显示结果?

php - 使用 OpenID 而不要求用户知道他们的 OpenID url?

mysql - 更新分配在不同表中的发票 ID 的代码

php - centos 6.5连接mysql失败