Click to See Complete Forum and Search --> : A modular php connection to myqsl db


DJRobThaMan
09-07-2007, 09:44 PM
Hi everyone,

Quick question. I have used and know that the following code works


<?php



$con = mysql_connect("localhost","root","password");



if(!$con)

{

die('Could not connect: ' . mysql_error());

}

else

{

mysql_select_db("bits", $con);

$ans = mysql_query("SELECT * FROM `snippets` ORDER BY `Date`, `Time` DESC LIMIT 0, 15");



while($result = mysql_fetch_array($ans))

{

?>

<h2><a title="<?php echo $result["Title"]; ?>" href="<?php echo $result["Link"]; ?>"><?php echo $result["Title"]; ?></a></h2>

<p><?php echo $result["Text"] ?></p>

<?php

}



mysql_close($con);

}



?>


But, it's a pain and a increases filesize to keep rewriting it everytime I need to access the db. So I tried to write the bulk of the connection and mysql query code in one file and then call that code from another.

My code now looks like this

dbConnect.php

<?php

function connect()
{

$con = mysql_connect("localhost","root","password");



if(!$con)

{

die('Could not connect: ' . mysql_error());

}

else

{

mysql_select_db("bits", $con);
return true;

}

}



function get($db, $title)

{

$request = mysql_query("SELECT * FROM `bits`." . $db . "` WHERE `Title` = '" . $title . "'");

$ans = mysql_fetch_array($request);

return $ans;

}



function getAll($db, $dbcon)

{

$request = mysql_query("SELECT * FROM `bits`." . $db . "` ORDER BY `Date`, `Time` DESC LIMIT 0, 15");

$ans = mysql_fetch_array($request);

return $ans;

}

?>


snippet from other file

<div class="ubuntu">

<?php



include($_SERVER[DOCUMENT_ROOT] . "/dbConnect.php");

if(connect())
{
$articles = getAll("ubuntu");



while($articles)

{

?>

<h2><a title="<?php echo $articles["Title"]; ?>" href="<?php echo $articles["Link"]; ?>"><?php echo $articles["Title"]; ?></a></h2>

<?php

}

echo $articles["Title"];



?>

</div>


So far I've not been able to get it to work. Does anyone know how I could alter it so it's all good?

Thanks a million

Declan1991
09-08-2007, 08:50 AM
I don't know, but this works

<?php // db.php

$dbhost = 'server';
$dbuser = 'username';
$dbpass = 'password';

function dbConnect($db='') {
global $dbhost, $dbuser, $dbpass;

$dbcnx = @mysql_connect($dbhost, $dbuser, $dbpass)
or die('The site database appears to be down.');

if ($db!='' and !@mysql_select_db($db,$dbcnx))
die('The site database is unavailable.');

return $dbcnx;
}
?>

DJRobThaMan
09-08-2007, 02:44 PM
Okay Declan,

Will give it a try.

Thanks