我正在学习PHP和MySQL。我有一个数据库,正在进行一些检索,但当我使用fetchObject()时,我返回了2个实例。第一次尝试:
class Food {
// Properties
public $id;
public $version;
public $name;
public $solid;
public $servingtext;
public $servingmeasure;
public $servingamount;
private function __construct__() {}
public static function get_with_id ($dbconn,$id, $version) {
$stmt = $dbconn->prepare('SELECT * FROM Foods WHERE Id = :Id and Version = :Version;');
$stmt->execute([':Id' => $id, ':Version' => $version]);
return $stmt->fetchObject(__CLASS__);
// return $answer;
}
// Methods
function set_id($id){
$this->id = $id;
}
etc. with sets and gets
打电话给
require "./templates/header.php";
try
{
include __DIR__ . '../../connection.php';
$conobj = new Connection();
$dbconn = $conobj->get_connection();
} catch (Throwable $t) {
error_log(__FILE__ . ':' . $t->getMessage());
echo 'Connection Error ' . $t->getMessage();
}
require "./models/food.php";
$food = Food::get_with_id ($dbconn,2,0);
var_dump($food);
结果:
object(Food)#4 (14) { ["id"]=> NULL ["version"]=> NULL ["name"]=> NULL ["solid"]=> NULL ["servingtext"]=> NULL ["servingmeasure"]=> NULL ["servingamount"]=> NULL ["Id"]=> int(2) ["Version"]=> int(0) ["Name"]=> string(35) "Sanitarium Weet-Bix Blends Hi-Bran+" ["Solid"]=> int(1) ["ServingText"]=> string(28) "1 serving = 40g (2 biscuits)" ["ServingMeasure"]=> string(1) "g" ["ServingAmount"]=> int(40) }
应该只有7个字段,但第一组都是NULL,然后就是我想要的对象。
我试过了。。
<?php
class Food {
// Properties
public $id;
public $version;
public $name;
public $solid;
public $servingtext;
public $servingmeasure;
public $servingamount;
private function __construct__() {}
// Methods
function set_id($id){
$this->id = $id;
}
具有
<?php
require "./templates/header.php";
try
{
include __DIR__ . '../../connection.php';
$conobj = new Connection();
$dbconn = $conobj->get_connection();
} catch (Throwable $t) {
error_log(__FILE__ . ':' . $t->getMessage());
echo 'Connection Error ' . $t->getMessage();
}
require "./models/food2.php";
$id = 2;
$version = 0;
$stmt = $dbconn->prepare('SELECT * FROM Foods WHERE Id = :Id and Version = :Version;');
$stmt->execute([':Id' => $id, ':Version' => $version]);
$food = $stmt->fetchObject('Food');
var_dump($food);
同样的结果。然后用同样的食物类尝试:
<?php
require "./templates/header.php";
try
{
include __DIR__ . '../../connection.php';
$conobj = new Connection();
$dbconn = $conobj->get_connection();
} catch (Throwable $t) {
error_log(__FILE__ . ':' . $t->getMessage());
echo 'Connection Error ' . $t->getMessage();
}
require "./models/food2.php";
$id = 2;
$version = 0;
$food = $dbconn->query('SELECT * FROM Foods WHERE Id = ' . $id . ' AND Version = ' . $version . ';')->fetchObject('Food');
var_dump($food);
再次,结果有2个条目。
有人能帮我解释一下为什么我要先得到NULLs版本吗。我不想要也不需要它。很高兴被告知这是一个新手错误!我在检索数组方面取得了很多成功,但我想走OO的道路。
谢谢你,保罗
Docker容器中的PHP 8.1.30、MySQL 9.1.0和NGINX 1.27.2