简体   繁体   中英

How to fetch data of specific column from MySQL?

I have a problem when I want to display name from genres table...How to call this function and how to get name from genres...When I use echo I get undefined $data...

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

You are not checking for error and I think you have one in the query line

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'];
}

You could be a bit more efficient and just select name as thats all you appear to be interested in.

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'];
}

Althought this still contains the possibility of an SQL Injection Attack Even if you are escaping inputs, its not safe! Use prepared parameterized statements in either the MYSQLI_ or PDO API's

So you should really be be doing

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];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM