当我要显示流派表中的名称时出现问题...如何调用 此功能以及如何从类型中获取名称...当我使用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'];
}
答案 0 :(得分:1)
您不是要检查错误,我认为您在查询行中有一个
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 Injection Attack甚至if you are escaping inputs, its not safe!的可能性 在
MYSQLI_
或PDO
API中使用prepared parameterized statements
所以您应该确实在做
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];
}