【问题标题】:simple issue database connecting using oop使用 oop 连接的简单问题数据库
【发布时间】:2012-05-02 16:19:50
【问题描述】:

这是 dbconnect.class.php:

<?php  

class Connect 
{ 
    public $error; 
    protected $db; 
    public function __construct() 
    { 
        $link = mysql_connect("localhost","root","1") or $this->error = mysql_error(); 
        $db = mysql_select_db("tarih",$link); 
        $this->db = $db; 
    } 
} 
?>

这是主要的 php 文件:

<?php
//header.class.php 
require_once 'dbconnect.class.php'; 

class Header extends Connect 
{ 
    public $headers = array(); 
    private $baglan; 
    public function __construct() 
    { 
        /* 
        * Bu sınıf sayfaların header bilgilerini işler. 
        */ 
        $baglan = $this->db; 
    } 

    public function sayfaHeader($sayfa = true) 
    { 
        $sql = "SELECT * FROM header WHERE id='" . $sayfa . "'"; 
        $query = mysql_query($sql,$this->baglan); 
    } 


} 

Header::sayfaHeader(); 
?>

当我运行主 php 文件时,我看到了这个错误:

Fatal error: Using $this when not in object context in C:\AppServ\www\ilk\class\header.class.php on line 19  

第 19 行:

$query = mysql_query($sql,$this->baglan);  

问题出在哪里?我看不到问题,因为我很久没有写 php 代码了。

【问题讨论】:

  • 请停止使用古老的mysql_* 函数编写新代码。它们不再被维护,社区已经开始deprecation process。相反,您应该了解准备好的语句并使用PDO 或MySQLi。如果你想学习,here is a quite good PDO-related tutorial.
  • @Truth 这对 mysql 来说不是问题_ 这是面向对象编程的问题
  • 我从来没有说过它会解决你的问题。如果我确实这么认为,我会发布它作为答案。我只是说你应该这样做。

标签: php mysql oop


【解决方案1】:
Header::sayfaHeader(); 

它调用方法而不创建对象。你必须这样做

Header obj = new Header();
obj->sayfaHeader();

如果要调用类的方法,则将方法声明为static。但是你不能使用$this 引用,因为静态方法和成员没有引用类对象。

更新:
mysql_select_db 返回 bool 值。您必须使用 $link 变量进行查询。

【讨论】:

  • 第一个问题:为什么?从某种意义上说,我不能使用其他方法?第二个问题:现在我看到了这个错误:警告:mysql_query():提供的参数不是第 20 行 C:\AppServ\www\ilk\class\header.class.php 中的有效 MySQL-Link 资源
  • 非静态方法是对象的属性。静态方法属于类而不是类实例。
  • 我在更新下的回答中回答了
  • 是mysql_select_db返回1。mysql_select-db需要返回什么?
  • 你必须使用 $link 变量 - MySql-link
【解决方案2】:

你没有数据库问题,

您的代码错误。

Header::sayfaHeader(); 

那是针对静态方法的。但是您需要一个实例来实际调用该方法。

尝试:

Header obj = new Header();
obj->sayfaHeader();

【讨论】:

  • 问题:现在我看到这个错误:警告:mysql_query():提供的参数不是 C:\AppServ\www\ilk\class 中的有效 MySQL-Link 资源
  • 在我看来你正在使用 java :)
【解决方案3】:

我认为你需要构造父类来实例化数据库类

public function __construct() 
{ 
    parent::__construct();
    $baglan = $this->db; 
} 

【讨论】:

  • 现在我只能看到:警告:mysql_query():提供的参数不是第 20 行 C:\AppServ\www\ilk\class\header.class.php 中的有效 MySQL-Link 资源
【解决方案4】:
public function __construct() 
{ 
    // if you do this, add a $this-> to baglan to acces it in the class
    $this->baglan = $this->db; 
} 

public function sayfaHeader($sayfa = true) 
{ 
    $sql = "SELECT * FROM header WHERE id='" . $sayfa . "'"; 

    // or, since you inherit the $this->db
    $query = mysql_query($sql,$this->db); 
} 

【讨论】:

    猜你喜欢
    • 2015-02-12
    • 1970-01-01
    • 2014-01-11
    • 1970-01-01
    • 2015-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多