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 に答える