我在从MySQL切换到MySQLi时遇到问题。我使用MySQL尝试了以下代码,它工作正常。当我切换到MySQLi时,它返回一个空值。
MySQL(工作正常)
public function Login_User($username, $password)
{
$md5_password = md5($password);
$query = mysql_query("SELECT uid FROM users WHERE username='$username' and password='$md5_password'");
if(mysql_num_rows($query) == 1)
{
$row=mysql_fetch_array($query);
return $row['uid'];
}
}
MySQLi($ numrows为空)
public function Login_User($username, $password)
{
$md5_password = md5($password);
$query = mysqli_query($connection, "SELECT uid FROM users WHERE username='$username' and password='$md5_password'");
$numrows = mysqli_num_rows($query);
echo "username: " . $username . ", Password: " . $password . "<br/>";
echo "rows: " . $numrows;
if($numrows == 1)
{
$row = mysqli_fetch_array($query, MYSQLI_ASSOC);
return $row['uid'];
}
}
数据库连接(MySQL)
$dbc = @mysql_connect ('localhost','root','')
or die ('Could not connect to MySQL: ' . mysql_error() );
mysql_select_db ('socialhouse')
or die ('problems with selecting database: ' . mysql_error() );
数据库连接(MySQLi)
$connection = mysqli_connect('localhost', 'root', '', 'socialhouse');
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();}
有人知道我的MySQLi代码有什么问题吗? 提前致谢
答案 0 :(得分:1)
因为您必须使用MySQLi扩展将$connection
变量传递到脚本中,所以您现在正尝试访问此函数范围之外的变量。将它作为参数传递给你的函数,你应该好好去。
答案 1 :(得分:-2)
这是基本的想法:
$mysqli = new mysqli(.......);
$stmt = $mysqli->prepare("SELECT ...");
$stmt->bind_param('isi..', ...);
$stmt->execute();
$stmt->store_result();
$numrows=$stmt->num_rows;
print "query returned " . $numrows;