准备好的语句及其如何影响查询
为了使我的脚本更加安全,我开始使用准备好的语句来防止 mysql 注入。该脚本可以很好地插入数据,但是当它应该返回正确的 id 编号时,获取最后插入的 id(基于数据库中的自动增量)现在会返回 0。
这部分插入得很好。
$stmt = $conn->prepare("INSERT INTO users (userName) VALUES (?)");
$stmt->bind_param("s", $_SESSION['username']);
$stmt->execute();
这就是我遇到问题的地方。我试图获取用户最后插入的 ID,它返回 0。
// Get the last inserted ID for the users ID
$query = "SELECT LAST_INSERT_ID()";
$result = mysql_query($query);
if ($result) {
$nrows = mysql_num_rows($result);
$row = mysql_fetch_row($result);
$userId = $row[0];
}
当我在开始准备语句之前编写脚本时,这是有效的。我唯一改变的是添加准备好的语句来插入数据,我的数据库连接如下:
$conn = new mysqli($server, $user, $password, $database) or die('Could not connect: ' . mysql_error());
我是 php 菜鸟,所以任何帮助将不胜感激。
In an effort to make my scripts more secure, I have started using prepared statements to prevent mysql injection. This script inserts the data just fine, but getting the last inserted id (based on auto incrementation in the database) now returns 0 when it should return the correct id number.
This part inserts just fine.
$stmt = $conn->prepare("INSERT INTO users (userName) VALUES (?)");
$stmt->bind_param("s", $_SESSION['username']);
$stmt->execute();
This is where I am having problems. I am trying to get the last inserted ID of the user and it is returning 0.
// Get the last inserted ID for the users ID
$query = "SELECT LAST_INSERT_ID()";
$result = mysql_query($query);
if ($result) {
$nrows = mysql_num_rows($result);
$row = mysql_fetch_row($result);
$userId = $row[0];
}
This was working when I had my script before starting on Prepared Statements. The only thing I changed was adding the Prepared Statement to insert the data and my db connection is as follows:
$conn = new mysqli($server, $user, $password, $database) or die('Could not connect: ' . mysql_error());
I am a noob with php so any help would be greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可能有一个根本性的误解:当您切换到 mysqli 时,您的 mysql_* 函数将不再使用相同的连接。
LAST_INSERT_ID()
在每个连接的基础上工作。您必须使用与主查询相同的库/连接来进行该查询,或者正如 @zerkms 指出的那样,使用
$conn->insert_id
。You may have a fundamental misunderstanding: When you switch to
mysqli
, yourmysql_*
functions will no longer use the same connection.LAST_INSERT_ID()
works on a per-connection basis.You will have to make that query using the same library/connection as the main query, or as @zerkms points out, use
$conn->insert_id
.mysqli_insert_id()。
mysqli_insert_id().