PHP 将 mysql 转换为 mysqli

时间:2023-03-06
本文介绍了PHP 将 mysql 转换为 mysqli的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

以下脚本工作正常:

$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 语句(保持其他所有内容,包括所有密码相同)时,是否会收到错误的用户名或密码"回声?

Why, when I replace only the mysql_connect and mysql_select_db statements (keeping everything else including all passwords the same) with the following, do i get the "Wrong Username or Password" echo?

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

推荐答案

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

It is because the MySQL and MySQLi database connections are not linked. When you make a connection to database with MySQLi, you have to use that connectio.

示例:

$mysqli = new mysqli('localhost', 'user', 'password', 'database');
$result = $mysqli->query("SELECT * FROM users");

这篇关于PHP 将 mysql 转换为 mysqli的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:mysqli 图像 blob 插入不起作用 下一篇:在非对象上调用成员函数 query()

相关文章