我有这个OOP选择我正在使用,我想将JOIN添加到功能中。我的新代码虽然没有生成数组。有人可以帮忙吗?
这是我最初的简单选择,它就像一个梦想
public function select($table, $rows = '*', $where = null, $order = null)
{
$q = 'SELECT '.$rows.' FROM '.$table;
if($where != null)
$q .= ' WHERE '.$where;
if($order != null)
$q .= ' ORDER BY '.$order;
$query = @mysql_query($q);
if($query)
{
$this->numResults = mysql_num_rows($query);
for($i = 0; $i < $this->numResults; $i++)
{
$r = mysql_fetch_array($query);
$key = array_keys($r);
for($x = 0; $x < count($key); $x++)
{
// Sanitizes keys so only alphavalues are allowed
if(!is_int($key[$x]))
{
if(mysql_num_rows($query) > 1)
$this->result[$i][$key[$x]] = $r[$key[$x]];
else if(mysql_num_rows($query) < 1)
$this->result = null;
else
$this->result[$key[$x]] = $r[$key[$x]];
}
}
}
return true;
}
else
{
return false;
}
}
这是我尝试添加一种使用连接的方法,但它没有返回任何数组。
public function select($table, $rows = '*', $join = null, $where = null, $order = null){
// Create query from the variables passed to the function
$q = 'SELECT '.$rows.' FROM '.$table;
if($join != null){
$q .= ' JOIN '.$join;
}
if($where != null){
$q .= ' WHERE '.$where;
}
if($order != null){
$q .= ' ORDER BY '.$order;
}
// Check to see if the table exists
if($this->tableExists($table)){
// The table exists, run the query
$query = @mysql_query($q);
if($query){
// If the query returns >= 1 assign the number of rows to numResults
$this->numResults = mysql_num_rows($query);
// Loop through the query results by the number of rows returned
for($i = 0; $i < $this->numResults; $i++){
$r = mysql_fetch_array($query);
$key = array_keys($r);
for($x = 0; $x < count($key); $x++){
// Sanitizes keys so only alphavalues are allowed
if(!is_int($key[$x])){
if(mysql_num_rows($query) > 1){
$this->result[$i][$key[$x]] = $r[$key[$x]];
}else if(mysql_num_rows($query) < 1){
$this->result = null;
}else{
$this->result[$key[$x]] = $r[$key[$x]];
}
}
}
}
return true; // Query was successful
}else{
array_push($this->result,mysql_error());
return false; // No rows where returned
}
}else{
return false; // Table does not exist
}
}
答案 0 :(得分:4)
如果你正在调用这个函数,你应该这样声明:
public function select($table, $rows, $where, $order)
{
// your statements
}
然后这样称呼:
select('your_table','rows_you_want_select','where_conditions','column_you_want_to_sort');
另一方面,如果您尝试放入join语句,请将其声明为:
public function select($table, $rows, $join, $where, $order)
{
// your statements
}
然后这样称呼:
select('your_table','rows_you_want_select','join_conditions','where_conditions','column_you_want_to_sort');
示例:
select('table1','id',' table2 on table1.id = table2.id','id = 1','id');
您仍然需要了解FUNCTIONAL PROGRAMMING,但请避免使用mysql_
。而是使用mysqli_
或PDO
。如果你真的在追求OOP,那么我强烈建议PDO。