开发者

OOPHP select from MySQL

I am wondering how to do the following I want to create a public function that allows me to do selects from MYSQL

Here is the code I have so far but it brings up a if error.

public开发者_Python百科 function select($table,$options,$where,$orderby)
    {

        $sql = mysql_query("SELECT ". 
        if($options)
        {
        $options
        }
        ." FROM ".
        $table
        if($where)
        {
        ." WHERE ".$where.
        }
        if ($orderby)
        {
        ." ORDER BY ".$orderby.
        }
        ."") or mysql_error() ;

        $row = mysql_fetch_assoc($sql);
        $rows[] = $row;
        print json_encode($rows);

    }

Parse error: syntax error, unexpected T_IF in /home/realcas/public_html/eshop/ecms/system/classes/database.php on line 23


Try

$sql = mysql_query("SELECT ". $options ." FROM ". $table .
                   ($where ? "WHERE " . $where : "") .
                   ($orderby? "ORDER BY ".$orderby  : "")) or mysql_error() ; 

$row = mysql_fetch_assoc($sql); 
$rows[] = $row; 
print json_encode($rows); 


You cannot have if-statements inside a function call. Build your SQL outside and then pass it directly to mysql_query. Example:

$sql = "SELECT ";
if($options)
    $sql .= "FROM " . $table;
if($where)
    $sql .= " WHERE " . $where;
if($orderby)
    $sql .= " ORDER BY " . $orderby;

$query = mysql_query($sql);

I also assume that you're missing an exit before mysql_error(). As it is now, you wont get any output. Change it to:

mysql_query($sql) or die(mysql_error());

Third, you will only be able to fetch a single row since you only invoke mysql_fetch_assoc once. You should continue iterating over it as long as there are results:

$rows = array();
while($row = mysql_fetch_assoc($query))
    $rows[] = $row;

// $rows will now contain all rows returned from your select statement


enhanced way:

public function select($table,$options,$where,$orderby)
{
    $options = empty($options) ? "*"   : $options;
    $where  =  empty($where)   ? "1=1" : $where;
    $orderby = empty($orderby) ? ""    : $orderby;

    $qry = "SELECT $options FROM $table WHERE $where $orderby ";
    $result= mysql_query($qry) or die(mysql_error());

    while(($resultArray[] = mysql_fetch_assoc($result));
    return json_encode($resultArray);

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜