簡體   English   中英

如何從 MySQL 中獲取特定列的數據?

[英]How to fetch data of specific column from MySQL?

當我想從流派表中顯示名稱時遇到問題...如何調用此函數以及如何從流派中獲取名稱...當我使用 echo 時,我得到未定義的 $data...

public function getGenreName(){
    $query = mysqli_query($this->con, "SELECT * FROM genres WHERE id='$this->genre'");
    $data = mysqli_fetch_array($query);
    return $data['name'];
  }

您沒有檢查錯誤,我認為您在查詢行中有一個

public function getGenreName(){
    $query = mysqli_query($this->con, "SELECT * FROM genres WHERE id='{$this->genre}'");

    if ( ! $query ) {
        echo $this->con->error;
        return false;
    }
    $data = mysqli_fetch_array($query);
    return $data['name'];
}

您可能會更有效率,只需選擇name因為這就是您似乎感興趣的全部內容。

public function getGenreName(){
    $query = mysqli_query($this->con, "SELECT name FROM genres WHERE id='{$this->genre}'");

    if ( ! $query ) {
        echo $this->con->error;
        return false;
    }
    $data = mysqli_fetch_array($query);
    return $data['name'];
}

盡管這仍然包含SQL 注入攻擊的可能性 即使您正在逃避輸入,它也不安全! MYSQLI_PDO API 中使用准備好的參數化語句

所以你真的應該做

public function getGenreName(){
    $stmt = $this->con->prepare("SELECT name 
                                FROM genres 
                                WHERE id=?");
    $stmt->bind_param('s', $this->genre );
    $query = $stmt->execute();

    if ( ! $query ) {
        echo $this->con->error;
        return false;
    }
    $result = $stmt->get_result();
    $result->fetch_array(MYSQLI_NUM);
    return $result[0];
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM