0

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.

Degauser
  • 120
  • 1
  • 2
  • 9

2 Answers2

0

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

Ivica Hrg
  • 26
  • 4
  • always close it at the end... so to be sure that all sql queries are executed before you close the connection. long time a go I head a practice to have `include "mysql_close.php"` ( and closed connection inside it ) on bottom of every script where I had connection to database. – Ivica Hrg Apr 19 '14 at 18:15
0

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


}
Datta
  • 150
  • 1
  • 1
  • 9
  • thanks for your answer. first of all, when I do this, $link is not in this function so I can't close it inside the function because of the variable scope. second, I may have to use this connection again and again. still, thanks for your help. maybe you can tell me more about "mysqli" – Degauser Apr 20 '14 at 13:29