gpt4 book ai didi

php - 如何显示表中的列

转载 作者:行者123 更新时间:2023-11-30 00:07:06 26 4
gpt4 key购买 nike

我正在学习 PHP,并试图在我一直在观看的教程之外创建一些代码,以更好地理解它,但我似乎无法弄清楚下面的代码哪里出了问题。我还有很多其他功能都工作得很好,只是这个功能不行。有人能指出我正确的方向吗?谢谢。

我得到的结果是 Catchable fatal error: Object of class User Could not be Converted to string on line 20, which is echo $user . "<br /><br />";

这是我的index.php

<? 
$users = User::db_fields();
foreach($users as $user) {
echo $user . "<br /><br />";
}
?>

这是我在 user.php 中的 User 类

<?php 
class User extends OtherStuff {

public static function db_fields() {
global $db;
return static::find_by_sql("SHOW COLUMNS FROM my_table");
}
}
<?

这是 other_stuff.php 中我的一些 OtherStuff 类

class OtherStuff {

public static function find_by_sql($sql="") {
global $db;
$result_set = $db->query($sql);
$object_array = array();
while($row = $db->fetch_array($result_set)) {
$object_array[] = static::instantiate($row);
}
return $object_array;
}

public static function instantiate($record) {
$class_name = get_called_class();
$object = new $class_name;
foreach($record as $attribute => $value){
if($object->has_attribute($attribute)) {
$object->$attribute = $value;
}
}
return $object;
}
}
?>

最佳答案

嗯....您静态调用 db_fileds()。

User::db_fields();

所以它需要是一个静态函数..

public static function db_fields() {

编辑

您可以将此作为解决方法...

更改您的查询

return static::find_by_sql("SELECT * FROM mytable LIMIT 1");

然后这样做...

$fields = User::db_fields(); 
foreach($fields as $key=>$value ) {
echo $key; // This will give the field name
}

编辑2

保留链接到字段的列名称。

尽管这可能是错误的,因为现在它实例化了多次,并且在对象找不到属性并且没有被写入的情况下会发生什么,然后你会错过一列。

但是这个想法是存在的......

while($row = $db->fetch_array($result_set)) {

foreach($row as $k=>$v){
$object_array[$k] = static::instantiate($row);
}

}

关于php - 如何显示表中的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24440545/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com