我创建类数据库:
class Database
{
private $db_host = "localhost";
private $db_user = "root";
private $db_pass = "";
private $db_name = "test";
private $con = false;
private $result = array();
}
还有更多功能,但并不重要。
我有这个功能:
public function sql($sql){
$query = @mysql_query($sql);
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
}
}
问题是当我在我的主脚本中使用时,例如一个简单的选择工作正常:
$db = new Database();
$db->connect();
$db->sql("Select * FROM crudclass");
$res = $db->getResult();
print_r($res);
echo "<br>";
foreach($res as $output){
echo $output["id"]." ";
echo $output["name"]." ";
echo $output["email"]."<br />";
}
?>
我得到所有结果:
Array ( [0] => Array ( [id] => 1 [name] => Name 1 [email] => name1@email.com ) [1] => Array ( [id] => 2 [name] => Name 2 [email] => name2@email.com ) [2] => Array ( [id] => 3 [name] => Name 3 [email] => name3@email.com ) )
1 Name 1 name1@email.com
2 Name 2 name2@email.com
3 Name 3 name3@email.com
但是如果我想使用例如 WHERe 这样的:
$db->sql("Select * FROM crudclass where id=1");
我得到这个错误
Array ( [id] => 1 [name] => Name 1 [email] => name1@email.com )
Warning: Illegal string offset 'id' in C:\xampp\htdocs\index.php on line 14
1
Warning: Illegal string offset 'name' in C:\xampp\htdocs\index.php on line 15
1
Warning: Illegal string offset 'email' in C:\xampp\htdocs\index.php on line 16
1
Warning: Illegal string offset 'id' in C:\xampp\htdocs\index.php on line 14
N
Warning: Illegal string offset 'name' in C:\xampp\htdocs\index.php on line 15
N
Warning: Illegal string offset 'email' in C:\xampp\htdocs\index.php on line 16
N
Warning: Illegal string offset 'id' in C:\xampp\htdocs\index.php on line 14
n
Warning: Illegal string offset 'name' in C:\xampp\htdocs\index.php on line 15
n
Warning: Illegal string offset 'email' in C:\xampp\htdocs\index.php on line 16
n