Forum Moderators: coopster

Message Too Old, No Replies

to pear or not to pear that is my question

         

bkeep

11:25 pm on Feb 3, 2008 (gmt 0)

10+ Year Member



I have been looking around and have found PEAR for a database abstraction layer. I have been told that my script should be more portable. What I am curious about, is there still going to be a lot of recoding to move from say mysql to postgresql if I have this function which is mySQL centric.


function checkIfAdmin($user,$pass)
{
$user = mysql_real_escape_string((get_magic_quotes_gpc())? stripslashes($user): $user);
$pass = mysql_real_escape_string((get_magic_quotes_gpc())? stripslashes($pass): $pass);

$sql = "SELECT user FROM users WHERE user = '" . $user ."' AND pass = '" . $pass . "' AND user_level = '9' ";
$res = mysql_query($sql);
$num = mysql_num_rows($res);

if ($num > 0)
return true;
return false;
}

and change it to this for PEAR MDB2.php


function checkIfAdmin($user,$pass)
{
$user = mysql_real_escape_string((get_magic_quotes_gpc())? stripslashes($user): $user);
$pass = mysql_real_escape_string((get_magic_quotes_gpc())? stripslashes($pass): $pass);

$sql = "SELECT user FROM users WHERE user = '" . $user ."' AND pass = '" . $pass . "' AND user_level = '9' ";
$res = $db->query($sql);

if ($res->numRows() > 0)
return true;
return false;
}

What do I do about the mysql_real_escape_string()?

Best Regards,
Brandon

cameraman

6:27 pm on Feb 4, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



If you have mysql function calls scattered about your code then you'll have recoding to do no matter what sort of abstraction you want to apply. You don't necessarily have to use PEAR; you could write your own easily enough. Personally I think that's better because you can write it "the way it ought to work" as defined by your own brain ;) . Further, it's by definition more portable since it doesn't require 3rd party - in this case, PEAR.

You can also take the opportunity to write your own shortcut functions. For example, my db class has a function called insary() that takes a table name and associative array as parameters and takes care of constructing the insert statement, along with escaping strings & surrounding them with single quotes - it looks at the table structure to determine which array elements are numeric and which aren't.

The most efficient way to do it would be to write yourself a couple of database classes, one for each db you want to support and with identically named member functions. Then you only have to have one if statement:
if($dbmethod == 'mysql')
$db = new mysql_class();
elseif($dbmethod == 'postgresql')
$db = new postgresql_class();
elseif(. . .)

$db->query($sql);

If you did it as separate generically-named functions each one would have to test for the method.

If you look at the description for mysql_real_escape_string() [php.net] you can duplicate its functionality with regular expressions or str_replace() calls.