PHP从MySQL中选择

时间:2011-10-09 07:47:39

标签: php mysql select

我想知道如何执行以下操作我想创建一个允许我从MYSQL中选择的公共函数

这是我到目前为止的代码,但它会出现if错误。

public 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);

    }

解析错误:语法错误,第23行/home/realcas/public_html/eshop/ecms/system/classes/database.php中的意外T_IF

3 个答案:

答案 0 :(得分:2)

函数调用中不能包含if语句。在外部构建SQL,然后将其直接传递给mysql_query。例如:

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

$query = mysql_query($sql);

我还假设你在mysql_error()之前错过了exit。就像现在一样,你不会得到任何输出。将其更改为:

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

第三,由于您只调用一次mysql_fetch_assoc,因此您只能获取一行。只要有结果,你应该继续迭代它:

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

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

答案 1 :(得分:2)

尝试

$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); 

答案 2 :(得分:0)

增强方式:

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);

}