函数中的Mysqli查询-PHP [英] Mysqli query in function - PHP

查看:70
本文介绍了函数中的Mysqli查询-PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 functions.php 中有函数列表.我正在从 Mysql 升级到 Mysqli ,因为我刚刚学习的 Mysql 现已贬值.

I have a list of functions in functions.php. I'm upgrading from Mysql to Mysqli because I just learning Mysql is now depreciated.

我在顶层connect.php文件中声明我的连接.需要第一个文件.

无论如何,我所有的函数都使用mysql_query("QUERY"),并且始终可以正常工作.现在,我将它们全部更改为:

Anyway back to the point all my functions use mysql_query("QUERY") and that always worked fine. Now I changed all the them to:

$con->query("QUERY") // ($con is my connection variable)

现在我遇到一个 致命错误:第241行,在C:\ wamp \ www \ PHP \ functions.php中的非对象上调用成员函数query() > .



所以我不明白为什么要查询我是否在整个文件中声明了变量.我不确定它在任何地方都可以访问.这使我的网站处于暂停状态,直到我可以解决此问题为止.这是 functions.php

function getSiteName()
{
    $row = $con->query("SELECT * FROM siteinfo")->fetch_array();
    return $row["siteName"];
}

我的联系:

global $con ;
$con = new mysqli("localhost", "itunes89", "XXXX","projectanvil") or die("Sorry, were having server connection issues. Please try again later.");



谢谢你们! :D 我的网站出现此错误



Thanks guys! :D My site where I'm having this error

推荐答案

这是范围可变问题.您需要将$conn传递给getSiteName():

That's a variable scope problem. You need to pass $conn to getSiteName():

function getSiteName($con) {
    $row = $con->query("SELECT * FROM siteinfo")->fetch_array();
    return $row["siteName"];
}

$name = getSiteName($con);

或使用带有构造函数注入的类:

Or using a class with constructor injection:

class MyThing
{
    protected $con;

    public function __construct($con) {
        $this->con = $con;
    }

    public function getSiteName() {
        $row = $this->con->query("SELECT * FROM siteinfo")->fetch_array();
        return $row["siteName"];
    }
}

$obj = new MyThing($con);
$name = $obj->getSiteName();

在整个类中,您可以使用$this->con来访问连接.

Throughout the class you can use $this->con to access the connection.

这篇关于函数中的Mysqli查询-PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆