在SQL查询中使用对象的属性


Using the properties of an object in a SQL query

我有一个对象,其中一个属性是应该在查询中使用的数据库表。

我想把对象传递给一个函数。

在函数中,我想使用对象的属性,即数据库表。

我尝试过各种说法,但都导致

Notice: Undefined property: torrent::$get_table in C:'Users'...'functions.php on line 78 SQL query is SELECT COUNT(title) from '()' where title = 'The Zen of Recovery - Mel Ash'

$sql = "SELECT COUNT(title) from '$objMyObject->get_table()'  where title = '$title'";

我做错了还是不可能?

感谢阅读。

PHP将尝试将$objMyObject->get_table计算为属性,而不是整数方法。这就是为什么只得到括号而不是预期值的原因。可以在双引号中使用对象属性或变量,但不能使用方法或函数。

要解决你的问题,你可以用两种方法

$table = $objMyObject->get_table();
// notice {} will indicate that you intend to print variable value
// it's not mandatory but it's better practice
$sql = "SELECT COUNT(title) from '{$table}' where title = '$title'";

$sql = "SELECT COUNT(title) from '" . $objMyObject->get_table() . "' where title = '$title'";