【问题标题】:PHP undefined function [closed]PHP未定义函数[关闭]
【发布时间】:2015-05-25 20:28:48
【问题描述】:

我目前正在处理 PHP 和 MySQL 中的消息显示。
我总是在第 22 行收到此错误:

致命错误:在 ... 中调用未定义函数 query()

但我在这个特定的行中定义了 $query....
我的代码如下所示:

    <?php

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "dbmitarbeiter";

// Create connection
$db = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($db->connect_error) {
    die("Connection failed: " . $db->connect_error);
}

$useremp = $_SESSION['username'];    

$query = "
SELECT *
FROM `tbabonnenten` s
WHERE dest = " . $db->real_escape_string($useremp);

$result = $db-query($query);

if (!$result) {
    echo 'SQL error ' . mysql_error();
    exit;
}

$user = $result->fetch_assoc();

/*
 * Run this query, and fetch the entire userrow, and put into $user
 * An alternative could be to just store the entire user array into
 * $_SESSION, as you wont have to query the database twice.
 */

$tofetch = array();

for ( $i=1; $i<=3; $i++ )
{
    //Let's check msg1, msg2, msg3
    if ( $user['abo' . $i] )
    {
        $tofetch[] = "name = 'Forum" . $i . "'";
    }
}

/*
 * If tbsubscribers has a '1' in msg1, and a '1' in msg2 then the array
 * will look like this:
 * array(
 * 0 => "name = 'msg1'"
 * 1 => "name = 'msg2'"
 * )
 */

//Throw an exception if all 'msg1', 'msg2', and 'msg3' are all 0 (Otherwise the query will fail)
if ( empty($tofetch) ) {
    echo "no subscriptions to show";
    //Don't continue here, otherwise the query will fail.
    exit;
}

/*
 * Now it's a simple query. $tofetch will be imploded, to form a nice
 * where statement. Using the example above, it will look like:
 * name = 'msg1' OR name = 'msg2'
 */

$query = "
SELECT *
FROM `tbmitteilung`
WHERE " . implode(' OR ', $tofetch);

$result = $db->query($query);

if (!$result) {
    echo 'SQL error ' . mysql_error();
    exit;
}

$messages = $result->fetch_all(MYSQLI_ASSOC);

print_r($messages);



?>

有什么想法吗? 提前感谢您的帮助

【问题讨论】:

  • 错字:$db-query($query); 应该是$db-&gt;query($query);
  • 阅读错误信息。它没有说 variable $query 有问题,它说问题在于未定义的 function query()
  • 这对你也没有帮助 mysql_error() => php.net/manual/en/mysqli.error.php

标签: php mysql function object call


【解决方案1】:

错别字:

$result = $db-query($query);
             ^---- mathematical subtraction

(例如“$db 的内容减去未定义函数 query() 的结果”)

你想要

$result = $db->query($query);
             ^^----object member operator

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-30
    • 2014-06-20
    • 2023-01-28
    • 2021-04-29
    • 2013-10-08
    • 1970-01-01
    相关资源
    最近更新 更多