尝试从 PHP 函数中执行 SQL 查询


trying to execute a SQL query from within a PHP function

我正在尝试从PHP函数中执行SQL查询,但不断收到以下错误:

致命错误:在非对象上调用成员函数 prepare() /homepages/23/d363590707/htdocs/bNames.php5 在第 14 行

第 14 行是以下方法中具有准备方法的行:

function testing()
{
    $query = "SELECT `no` FROM `brandNames` WHERE `id` = $index";
    $stmt = $dbc->prepare($query);   <--- line 14 -----------------<<<
    $stmt->execute();
    $stmt->store_result();
    $stmt->bind_result($no);
    $stmt->fetch(); 
}

注意:当我将代码块粘贴在页面中(不使用函数)时,查询可以工作,我没有任何问题。

此外,我打算向此函数添加参数以替换表名、列名和值。 这只是一个版本,可能出错的东西最少,但仍然说明了我的问题。

提前致谢

编辑:这是文件的样子:

<?php
    require_once('connectvars.php'); //contains the info used in mysqli_connect
    $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);

    function testing($dbc)
    {
        $query = "SELECT `no` FROM `brandNames` WHERE `id` = $index";
        $stmt = $dbc->prepare($query);
        $stmt->execute();
        $stmt->store_result();
        $stmt->bind_result($no);
        $stmt->fetch(); 
    }
//more code
?>

虽然你可以$dbc定义为global,但我建议简单地将$dbc传递到函数中:

function testing($dbc)
{
    $query = "SELECT `no` FROM `brandNames` WHERE `id` = $index";
    $stmt = $dbc->prepare($query);   <--- line 14 -----------------<<<
    $stmt->execute();
    $stmt->store_result();
    $stmt->bind_result($no);
    $stmt->fetch(); 
}

现在,当你调用testing()时,你需要传入$dbctesting($dbc);

问题是$dbc对象(PDO,可能?)不在函数的范围内。您可以在此处阅读有关此内容的更多信息:http://php.net/manual/en/language.variables.scope.php

要解决此问题,您可以尝试在函数顶部添加以下行:

global $dbc;
您可能需要

在函数开始时有一个global $dbc;才能将其纳入函数的作用域。