我刚刚开始了一个旧项目,我需要做的第一件事就是从mysql_*
扩展名迁移到mysqli_*
扩展名。我以前没有使用过很多PHP ...大多数新代码都可以工作但是在下面的例子中我似乎搞砸了......
旧功能:
function user_id_from_username($username) {
$username = sanitize($username);
return mysql_result(mysql_query("SELECT `user_id` FROM `users` WHERE `username` = '$username'"), 0, 'user_id');
}
新功能(无功能):
function user_id_from_username($username) {
$username = sanitize($username);
$id = mysqli_query(connect(),"SELECT `user_id` FROM `users` WHERE `username` = '$username'");
return $id;
}
另一个旧的:
function login($username, $password) {
$user_id = user_id_from_username($username);
$username = sanitize($username);
$password = md5($password);
return (mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username' AND `password` = '$password'"), 0) ==1) ? $user_id : FALSE;
}
新的:
function login($username, $password) {
$user_id = user_id_from_username($username);
$username = sanitize($username);
$password = md5($password);
$check = mysqli_query(connect(),"SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username' AND `password` = '$password'");
return $check == $user_id ? TRUE : FALSE;
}
我的消毒功能:
function sanitize($data) {
return htmlentities(strip_tags(mysqli_real_escape_string(connect(), $data)));
}
答案 0 :(得分:5)
好的,所以在你试图替换的第一个功能中
return mysql_result(mysql_query("SELECT `user_id` FROM `users` WHERE `username` = '$username'"), 0, 'user_id');
让我们先说清楚它的作用:
user_id
现在使用mysqli_
//specify query
$result = mysqli_query(connect(),"SELECT `user_id` FROM `users` WHERE `username` = '$username'");
//fetch result
$row = mysqli_fetch_assoc($result);
//get column
return $row['user_id'];
您无需指定行,因为fetch_assoc
只返回一行。
现在是第二个功能
return (mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username' AND `password` = '$password'"), 0) ==1) ? $user_id : FALSE;
user_id
,否则FALSE
现在使用mysqli_
:
//specify query
$result = mysqli_query(connect(),"SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username' AND `password` = '$password'");
//fetch result
$row = mysqli_fetch_row($result);
//if first returned column is equal to 1 return $user_id
//otherwise FALSE
return ($row[0]==1) ? $user_id : FALSE;
但是等等 - 为什么我在这里使用mysqli_fetch_row
,而上面使用了mysqli_fetch_assoc
? RTM;)
我们今天学到了什么?只是因为你可以尽可能地编写代码并不意味着你应该这样做。如果原始代码被拆分了一些,那么转换到MySQLi应该很容易,因为你可以轻松地调试较小的部分而不是复杂的表达式。