I am looking for some experienced advice when it comes to functions and query statements.
I am writing code that I am constantly having to query a db, does it make sense to create a function that I call every time and return result or is it better to just make the calls in the main body of the code. It just seems that I am forever just typing the same six or so lines over and over.
I have attached a sample of what I currently have and a proposed function. I know the idea of functions it reuse what you have already done but I am not sure if this also applies to db queries as it may cause confusion??
I guess part of my question also lies in the fact that I really do not understand what is being returned in the result, is is a pointer to the db or an array of values. In which case, is it better to open the db, query and close the db all in a very neat package.
Looking for some worldly advice?
Quote:
<?php
// start session
session_start();
// set up some global variables
@include 'salutations.php';
@include 'globalcfg.php';
@include 'db_connect.php';
$sql='SELECT quote, image, quoted FROM tbl_list_quotes ORDER BY RAND() LIMIT 1';
$result = mysql_query($sql, $link);
if (!$result) {
echo 'DB Error, could not query the database MySQL Error: '.mysql_error();
exit;
}
$row = mysql_fetch_assoc($result);
$quote=$row['quote'].'<br /><br />-- '.$row['quoted'].' --';
echo $_GET["project_id"];
if(isset($_GET["project_id"])) $_SESSION["project_id"]=$_GET["project_id"];
if(isset($_GET["tab"])) $_SESSION["tab"]=$_GET["tab"];
if(empty($_SESSION["tab"])) $_SESSION["tab"]=2;
echo $_SESSION["tab"].'PID'.$_SESSION["project_id"];
?>
|
or should I just call a function like
Quote:
function query($sql){
@include 'globalcfg.php';
@include 'db_connect.php';
$result=mysql_query($sql, $link);
if (!$result) {
echo 'DB Error, could not query the database MySQL Error: '.mysql_error();
exit;
}
return $result;
// dispose of result set
mysql_free_result($result);
// close connection to database server
mysql_close($link);
}
|
Last edited by dgkindy; 08-02-2010 at 10:36 PM..
Reason: grammatical error
|