[英]Moving from MySQL to MySQLi with mysql_result PHP
So initially, I know that using the MySQL
extension is not good for security and it's not updated but I only had used it for learning but now I want to move to MySQLi and I am not sure how I can convert it. 因此,最初,我知道使用
MySQL
扩展对安全性没有好处,并且没有进行更新,但我只是将其用于学习,但是现在我想转到MySQLi,但不确定如何转换。 I have two problems and I am not sure where to go as you can see below for the first set of code. 我有两个问题,我不确定去哪儿,如下面第一组代码所示。
What I want to do is check if a server is active and this is defined in a database where the table looks like this 我想做的是检查服务器是否处于活动状态,并且在数据库中定义了该服务器,该表如下所示
So if active is equal to 1 then that is true , if not then it should be false . 因此,如果active等于1则为true ,否则为false 。
function server_active_query($data) {
$server = sanitize($data);
$query = mysql_query("SELECT COUNT(`server_id`) FROM `servers` WHERE `servername` = '$server' AND `active` = 1");
return (mysql_result($query, 0) == 1) ? true: false;
}
//This is the new function so don't worry about the name
function server_active_query($data) {
$dbc = new mysqli('db_host', 'db_user', 'db_pass', 'db_db');
$server = sanitize($data, $dbc);
$query = $dbc->query("SELECT COUNT(`s_id`) FROM `servers` WHERE `servername` = '$server' AND `active` = 1");
//Not sure where to go from here as It does not work.
return (mysqli_result($query, 0) == 1) ? true: false;
}
You need to stick with the OO mysqli calls and the one you are looking for is $result->num_rows which returns the number of rows returned by the SELECT query. 您需要坚持使用OO mysqli调用,而您正在寻找的是$ result-> num_rows,它返回SELECT查询返回的行数。
Using ->query() returns a mysqli_result
object and that does not have the ability to return you the data from column 0 like the the mysql_ extensions does, so change the query to select a field, so it only returns a row if it find a server in the active state, then you can use the ->num_rows
property 使用-> query()返回一个
mysqli_result
对象,它不能像mysql_扩展那样从第0列返回数据,因此请更改查询以选择一个字段,因此仅在找到时返回一行处于活动状态的服务器,则可以使用->num_rows
属性
function server_active_query($data) {
$dbc = new mysqli('db_host', 'db_user', 'db_pass', 'db_db');
$server = sanitize($data, $dbc);
$result = $dbc->query("SELECT `s_id`
FROM `servers`
WHERE `servername` = '$server' AND `active` = 1");
return $result->num_rows == 1 ? true: false;
}
Or to use the better prepare() style 还是使用更好的prepare()样式
function server_active_query($data) {
$dbc = new mysqli('db_host', 'db_user', 'db_pass', 'db_db');
$server = sanitize($data, $dbc);
$stmt = $dbc->prepare("SELECT s_id
FROM servers
WHERE servername = ?
AND active = 1");
$stmt->bind_param("s", $server);
if ( $stmt->execute() ) {
$return = $stmt->num_rows == 1 ? true: false;
} else {
// error processing code or just default to false?
$return = false
}
// as we have not actually processed the returned row
// we had better clean up the statement handle
$stmt->close();
return $return;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.