致命错误:在字符串上调用成员函数....

Ken*_*ius 6 php mysql

连接在这里

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;
}
?>
Run Code Online (Sandbox Code Playgroud)

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

其次,包括都在这里

    <?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());
    ?>
Run Code Online (Sandbox Code Playgroud)

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

<?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;
    }
?>
Run Code Online (Sandbox Code Playgroud)

现在最后这是我在主页上调用的功能!

<?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!";
              }
            }
          ?>
Run Code Online (Sandbox Code Playgroud)

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

Gab*_*ocq 11

你在做 :

$idea = mysql_real_escape_string($_POST['idea']);
Run Code Online (Sandbox Code Playgroud)

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

$check = $idea->checkIdea($title);
Run Code Online (Sandbox Code Playgroud)

字符串上没有checkIdea方法.

  • 我从与另一个问题相关的 Google 搜索中偶然发现了这个问答。OP 代码的另一个问题是它们使用 `mysqli_` api 连接,但使用了不混合的 `mysql_` 函数。“技术上正确”的用法应该是`$idea = mysqli_real_escape_string($connection, $_POST['idea']);`,其他的也一样。 (2认同)