3

以下脚本工作正常:

$host="localhost"; // Host name 
$username=""; // Mysql username 
$password=""; // Mysql password 
$db_name="test"; // Database name 
$tbl_name="members"; // Table name 

// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
mysql_select_db("$db_name")or die("cannot select DB");

// username and password sent from form 
$myusername=$_POST['myusername']; 
$mypassword=$_POST['mypassword']; 

// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);

// Mysql_num_row is counting table row
$count=mysql_num_rows($result);

// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){

// Register $myusername, $mypassword and redirect to file "login_success.php"
session_register("myusername");
session_register("mypassword"); 
header("location:login_success.php");
}
else {
echo "Wrong Username or Password";
}

为什么,当我只用以下内容替换 mysql_connect 和 mysql_select_db 语句(保持其他所有内容,包括所有密码相同)时,我会得到“错误的用户名或密码”回声吗?

mysqli_connect($host,$username,$password,$db_name) or die("cannot connect");
4

1 回答 1

3

这是因为 MySQL 和 MySQLi 数据库连接没有链接。当您使用 MySQLi 连接到数据库时,您必须使用该连接。

例子:

$mysqli = new mysqli('localhost', 'user', 'password', 'database');
$result = $mysqli->query("SELECT * FROM users");
于 2013-09-14T14:59:46.070 回答