我的PHP函数'mysql_fetch_assoc()'
有问题public function result ($query) {
$result = false;
if (is_resource($this->resourceHandler)) {
$result = array();
while ($tempVar = @mysql_fetch_assoc($query)) {
$result[] = $tempVar;
}
}else{
throw new Exception ('Keine Verbindung zur Datenbank vorhanden!');
}
return $result;
}
当我运行此函数时,返回的数组应如下所示:
[0] => Array
(
[id] => 1
[description] => Test
[date] => 2012-08-09
)
[1] => Array
(
[nummer] => 2
[beschreibung] => Test2
[datum] => 2012-08-09
)
[2] => Array
(
[nummer] => 3
[beschreibung] => test3
[datum] => 2012-08-10
)
但它看起来像这样:
[0] => Array
(
[id] => 1
[description] => Test
[date] => 2012-08-09
)
[1] => Array
(
[nummer] =>
[beschreibung] =>
[datum] => 1970-01-01
)
[2] => Array
(
[nummer] => 3
[beschreibung] => test3
[datum] => 2012-08-10
)
我的数组的第二个元素总是空的。无论使用哪个sql-query,都是如此。有人知道这个问题吗?
答案 0 :(得分:0)
出于测试目的,请尝试(这是您的代码,带有一些调试输出和一些样板)
<?php
$mysql = mysql_connect('localhost', 'localonly', 'localonly') or die(mysql_error());
mysql_select_db('test', $mysql) or die(mysql_error($mysql));
echo 'mysql_get_client_info: ', mysql_get_client_info(), "\n";
echo 'mysql_get_host_info: ', mysql_get_host_info($mysql), "\n";
echo 'mysql_get_server_info: ', mysql_get_server_info($mysql), "\n";
echo 'mysql_get_proto_info: ', mysql_get_proto_info($mysql), "\n";
setup($mysql);
$query = mysql_query('SELECT * FROM tmpspeisen', $mysql) or die(mysql_error($mysql));
$foo = new Foo($mysql);
var_dump ( $foo->result($query) );
class Foo {
protected $resourceHandler;
public function __construct($mysql) {
$this->resourceHandler = $mysql;
}
public function result($query) {
$result = false;
if (is_resource($this->resourceHandler)) {
$result = array();
while ($tempVar = @mysql_fetch_assoc($query)) {
$result[] = $tempVar;
}
}else{
throw new Exception ('Keine Verbindung zur Datenbank vorhanden!');
}
return $result;
}
}
function setup($mysql) {
mysql_query('
CREATE TEMPORARY TABLE tmpspeisen (
id int auto_increment,
description varchar(128),
`date` Date,
primary key(id)
)
', $mysql) or die(mysql_error($mysql));
mysql_query("
INSERT INTO tmpspeisen (description, `date`) VALUES
('Test', '2012-08-09'), ('Test2', '2012-08-09'), ('test3', '2012-08-10')
", $mysql) or die(mysql_error($mysql));
}
在我的机器上打印
mysql_get_client_info: mysqlnd 5.0.10 - 20111026 - $Id: b0b3b15c693b7f6aeb3aa66b646fee339f175e39 $
mysql_get_host_info: localhost via TCP/IP
mysql_get_server_info: 5.5.25a
mysql_get_proto_info: 10
array(3) {
[0]=>
array(3) {
["id"]=>
string(1) "1"
["description"]=>
string(4) "Test"
["date"]=>
string(10) "2012-08-09"
}
[1]=>
array(3) {
["id"]=>
string(1) "2"
["description"]=>
string(5) "Test2"
["date"]=>
string(10) "2012-08-09"
}
[2]=>
array(3) {
["id"]=>
string(1) "3"
["description"]=>
string(5) "test3"
["date"]=>
string(10) "2012-08-10"
}
}