【问题标题】:Mysql: connect to db is lost after Include()Mysql:在 Include() 之后连接到数据库丢失
【发布时间】:2012-02-27 17:06:14
【问题描述】:

我的日历脚本工作得非常好,直到我将它包含到我的模板中。 events.php 中的 html 格式正确,但未处理与数据库的连接,导致您在下面看到错误。为什么会发生这种情况,连接丢失/未处理?

<?php include ROOT . '/files/cal/events.php';?>

错误:

警告:mysql_connect() [function.mysql-connect]: 在线 /home/social/public_html/files/cal/smoothcalendar.php 中的用户 'nobody'@'localhost' 访问被拒绝(使用密码:NO) 19

警告:mysql_select_db() 期望参数 2 是资源,布尔值在 /home/social/public_html/files/cal/smoothcalendar.php 第 21 行给出

警告:mysql_query() 期望参数 2 是资源,布尔值在 /home/social/public_html/files/cal/smoothcalendar.php 第 195 行给出

无法运行查询: 警告:mysql_close() 期望参数 1 是资源,布尔值在第 38 行的 /home/social/public_html/files/cal/smoothcalendar.php 中给出

smoothcalendar.php

<?php
$server   = "localhost";
$username = "****"; 
$password = "****";
$dbname   = "***_socialdb";

class SmoothCalendar {

    private $options = null,
            $get,
            $post;

    private $connection;

    function __construct($options) 
    {
        $this->connection = mysql_connect($GLOBALS["server"  ],
                                          $GLOBALS["username"],
                                          $GLOBALS["password"]);

        mysql_select_db($GLOBALS["dbname"],$this->connection);

【问题讨论】:

  • 我建议不要使用 $GLOBALS
  • @J.Bruni 我将 $GLOBALS 变量切换到 $conn 仍然是同样的错误
  • @acctan:您是否在使用变量的同一范围内定义了它?请阅读本手册页的介绍:php.net/manual/en/language.variables.scope.php
  • 志愿编辑,请不要将错误消息格式化为代码,使它们更难阅读。谢谢

标签: php mysql


【解决方案1】:

你可能有你的 include 在一个函数或其他东西中,即 not 在全局上下文中。这就是使用 $GLOBALS 数组无法访问您的变量的原因......它们不是全局的。

这应该可行:

<?php

class SmoothCalendar {

    private $options = null,
            $get,
            $post;

    private $connection;

    private $server   = "localhost";
    private $username = "****"; 
    private $password = "****";
    private $dbname   = "***_socialdb";

    function __construct($options) 
    {
        $this->connection = mysql_connect($this->server,
                                          $this->username,
                                          $this->password);

        mysql_select_db($this->dbname, $this->connection);

【讨论】:

    猜你喜欢
    • 2013-04-27
    • 2014-07-30
    • 1970-01-01
    • 2013-10-17
    • 2018-02-13
    • 2015-01-31
    • 1970-01-01
    • 2012-04-06
    • 1970-01-01
    相关资源
    最近更新 更多