【问题标题】:creating connection class to use over code base创建连接类以在代码库上使用
【发布时间】:2014-09-06 13:35:02
【问题描述】:

我有 2 个文件。 Connect.php 和 AddUser.php。

我正在尝试使用在 connect 中建立的 mysqli 连接从 AddUser 中将数据插入我的数据库。我觉得我的所有部件都放在了正确的位置,但它不起作用......任何帮助都会很棒!

这是我的代码:

Connect.php

<?php
class Connection
{
    public function connect()
    {
        $conn = "localhost";
        $un = "user";
        $pw = "password";
        $db = "db";
        $mysqli = new mysqli($conn, $un, $pw, $db);

        return $mysqli;
    }
}

AddUser.php

<?php
class addUser{
    public function add() {
        $conn = new Connection();
        $conn->connect();
        $sql = "INSERT INTO tbl_users (user_name) VALUES ('test')";
        $insert = $conn->query($sql);
    }
}

连接脚本包含在我的 index.php 路由器顶部的 require_once 语句中。

<?php
require_once "configs/Toro.php"; //ToroPHP router
require_once "configs/db.cnfg.php"; //db config (where class Connection is written)
require_once "handlers/addUser.php"; //adduser file

【问题讨论】:

  • 试试这个 include_once("connect.php");在 adduser.php
  • 让我修改我的问题,连接脚本在添加用户脚本之前包含在树的更上方。对不起!
  • 更新了问题!
  • 好的,它显示任何错误吗?你能解释一下查询($sql)函数吗
  • 实际上,在进行了一些挖掘之后,由于 ->query 功能,我得到了一个 500 服务器错误。这背后的想法是因为我有来自 Connection->connect() 的 mysqli 连接,那么我应该能够从中运行任何可用的 mysqli 函数。

标签: php mysql mysqli database-connection


【解决方案1】:

临时解决方案是将 Connect() 从类 Connection 中取出,并将其作为一个独立的函数...

<?php
    function connect()
    {
        $conn = ($_SERVER['SERVER_NAME'] === "vagrantup") ? "50.87.147.177" : "localhost";
        $un = "tbremer_bitters";
        $pw = "4t:7*4334S";
        $db = "tbremer_bittersyndrome";
        $mysqli = new mysqli($conn, $un, $pw, $db);

        return $mysqli;
    }

这允许我使用 mysqli 作为对象而不是 PDO 版本。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-06
    • 1970-01-01
    • 2012-03-16
    • 2011-02-19
    相关资源
    最近更新 更多