Domanda

I'm newbie at PHP & MySQL and I've a question about mysql_connect and mysql_close

Here is my code (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

I'm calling this function from page.php. But I'm not sure where to close this connection. Should I close it inside the function? Should I close it under the function? Should I connect at top of the function and close bottom of the function?

BTW feel free to make better my code.

È stato utile?

Soluzione

You could change this part

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

to

$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);

and like @fred-ii said, there is no need to close mysql connection

Altri suggerimenti

Remember when ever you need to close a db connection first make sure that you write all the scripts above the close function in this case write it in the function assuming that you will not need the connection after this.

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);


}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top