[英]Where to Close MySQL Connection on PHP
我是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連接
請記住,無論何時需要首先關閉數據庫連接,請確保您在close函數上方編寫了所有腳本,在這種情況下,假設您在此之后不需要連接,請在函數中編寫腳本。
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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.