If you're not interested in PHP coding please stop reading.
I'm open to correction on this, but I thought I'd put it out there in case it's helpful to anyone OR in case someone can point me to a simpler solution.
I've been developing the simple content management that powers the strangeday site news and gigs. The key points here are:
- I was using object oriented programming
- I used the PDO (PHP Data Objects) class for the database connections etc.
When it came to uploading, I quickly realised that my hosting provider, A Small Orange, has PDO disabled. So far so bad. However since I'd separated out what I was doing with the Object Oriented approach it was simply a matter of changing the database connection class and everything else would be hunky-dory.
Not so much.
My actual page was using the PDO Statement which gets returned as an array. Here's the final output code:
<?php
$i = 1;
foreach ($results as $newsitem)
{
?>
<p class='line<?=$i?>'><span class='newsitem'>..</span><?=$newsitem['title']?></p>
<?php
$i++;
}
?>
And here's the PDO code that was returning the query:
try
{
if ($squery = $this->dbh->query($query)) return $squery;
}
catch (PDOException $e)
{
die ("Database error @select: " . $e->getMessage() . "<br />\n");
}
My troubles began when I stopped using PDO::Query and changed to using mysql_query and mysql_fetch_assoc so that it would work on A Small Orange.
I ended up with an error in the foreach. What I wanted to do was change the connection side of things so that I could switch it depending on whether the hosting environment supported PDO or not.
What I needed to do was output an array that was functionally the same as the PDO Statement array. Here's what I came up with:
$result = mysql_query($query);
$squery = array();
while ($row = mysql_fetch_assoc($result))
{
$keys = array();
$values = array();
foreach ($row as $key=>$value)
{
$keys[]=$key;
$values[]=$value;
}
$squery[] = array_combine($keys, $values);
}
return $squery;
Obviously this needs error handling and I also wrote functionality into the class that would switch based on a PDO = true or false flag type arrangement but that's essentially my solution.
Comments/suggestions?
Labels: content management, PDO, PHP, web design