所以最初,我知道使用MySQL
扩展程序不利于安全性并且它没有更新但我只是用它来学习但现在我想转移到MySQLi而我不是确定我如何转换它。我有两个问题,我不知道去哪里,你可以在下面看到第一组代码。
我想要做的是检查服务器是否处于活动状态,并且这是在数据库中定义的,其中表格如下所示
因此,如果有效等于 1 ,则为真,如果不是,那么它应该 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;
}
答案 0 :(得分:0)
您需要坚持使用OO mysqli调用,而您正在寻找的是$ result-> num_rows,它返回SELECT查询返回的行数。
使用 - > query()会返回一个mysqli_result
对象,并且无法像mysql_ extensions那样返回第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;
}
或者使用更好的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;
}