[英]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...当我想从流派表中显示名称时遇到问题...如何调用此函数以及如何从流派中获取名称...当我使用 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'];
}
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.您可能会更有效率,只需选择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'];
}
Althought this still contains the possibility of an SQL Injection Attack Even if you are escaping inputs, its not safe!尽管这仍然包含SQL 注入攻击的可能性 即使您正在逃避输入,它也不安全! Use prepared parameterized statements in either the
MYSQLI_
orPDO
API's在MYSQLI_
或PDO
API 中使用准备好的参数化语句
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];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.