Hi everyone,
Quick question. I have used and know that the following code works
[code=php]
<?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
[code=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
[code=php]
<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