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