【问题标题】:Fatal error: Call to a member function ...on string [duplicate]致命错误:调用成员函数...在字符串上 [重复]
【发布时间】:2015-07-27 03:47:45
【问题描述】:

连接在这里

class connection{

private $hostname = "localhost";
private $username = "root";
private $password = "";
private $database = "idea";
private $conn;

public function __construct(){
    $this->conn = new mysqli($this->hostname, $this->username, $this->password, $this->database)or die("Error Connection To MySQL");
}

public function getConn(){
    return $this->conn;
}
?>

我怀疑它的连接,但只是以防万一......它一直在为所有其他查询工作,但谁知道呢。

其次,包含都在这里,就像这样

    <?php 
session_start();

  if ($_SESSION['loggedin'] != 1) {
    header('location: index.php');
  }

    include 'connection.php';
    include 'users.php';
    include 'ideas.php';
    $conn = new connection();
    $user = new users($conn->getConn());
    $idea = new ideas($conn->getConn());
    ?>

倒数第二个是我在一个类中的查询

<?php 

class ideas{

    private $conn;

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

    public function checkIdea($title){
        $result = $this->conn->query("SELECT * FROM ideas WHERE title = '$title'");
        return $result;
    }
?>

现在最后是我在主页上调用的函数!

<?php 
            if (isset($_POST['addidea'])) {
              $title = mysql_real_escape_string($_POST['title']);
              $idea = mysql_real_escape_string($_POST['idea']);

              $check = $idea->checkIdea($title); // <-- sais this is the error here...

              if ($check->num_rows == 0) {
                echo $idea->getUserId($_SESSION['username']);
              }else{
                echo "Sorry that iDea title is already taken, please use another!";
              }
            }
          ?>

我不知道它为什么这样做,这个错误是什么我以前从未遇到过(调用字符串上的成员函数)我使用与登录时相同的查询/布局等不知道它为什么这样做对此任何答案表示赞赏。

【问题讨论】:

    标签: php mysql


    【解决方案1】:

    你在做:

    $idea = mysql_real_escape_string($_POST['idea']);
    

    所以 $idea 现在是一个字符串。 然后你做:

    $check = $idea->checkIdea($title);
    

    字符串上没有 checkIdea 方法。

    【讨论】:

    • 我在与另一个问题相关的谷歌搜索中偶然发现了这个问答。 OP 的代码还发生了什么是他们使用mysqli_ api 连接但使用不混合的mysql_ 函数。 “技术上正确”的用法应该是 $idea = mysqli_real_escape_string($connection, $_POST['idea']); 和其他用法一样。
    猜你喜欢
    • 2019-02-11
    • 1970-01-01
    • 2018-03-17
    • 2017-02-27
    • 1970-01-01
    • 2017-03-16
    • 2021-05-16
    • 2019-11-23
    相关资源
    最近更新 更多