mysql_insert_id无效

时间:2012-01-13 00:03:15

标签: php mysql

对于模糊标题的道歉,这是我的问题:

我的代码的目标是在具有自动增量字段的表中插入新行。插入后,我想获得刚刚生成的自动增量字段的值。

这是我的表格定义:

CREATE TABLE `EventComments` (
  `CommentID` int(11) NOT NULL AUTO_INCREMENT,
  `EventID` int(11) NOT NULL,
  `OwnerID` int(11) NOT NULL,
  `Comment` varchar(512) NOT NULL,
  `DateTime` datetime NOT NULL,
  PRIMARY KEY (`CommentID`)
) ENGINE=MyISAM AUTO_INCREMENT=68 DEFAULT CHARSET=latin1;

我正在尝试获取CommentID字段的值。

因此,这是发出插入查询然后尝试获取CommentID值的php代码。

<?php
session_start();
ob_start();
include_once 'lib/functions.php';

if(isset($_SESSION['uid'])) {
    $eventID = $_GET['evid'];
    $ownerID = $_SESSION['uid'];
    $comment = $_GET['comment'];
    $comment = trim($comment);
    $dateTime = date('Y-m-d H:i:s');

    $db_connection = database_connect();

    if($eventID != null && !empty($comment)) {
        $query = "INSERT INTO meetup.EventComments (EventID, OwnerID, Comment,     DateTime) 
        VALUES (" . $eventID . ", " . $ownerID .", '" . $comment . "', '". $dateTime ."')";

        mysqli_query($db_connection, $query) or die(mysqli_error($db_connection));  

        $id = mysql_insert_id();
        $commentHtml = generateCommentFromData($db_connection, $ownerID, $comment, $dateTime,  $id);
        echo $commentHtml;
    }
}

ob_end_flush();
?>

此代码在php日志中发出以下错误:

mysql_insert_id() [<a href='function.mysql-insert-id'>function.mysql-insert-id</a>]: A link to the server could not be established...

我也试过显式传递数据库链接。但是这会产生以下错误:

mysql_insert_id(): supplied argument is not a valid MySQL-Link resource...

最后一点,插入查询有效。它肯定会插入一个包含预期数据的新行!

任何见解都将不胜感激! 感谢

3 个答案:

答案 0 :(得分:5)

您正在使用mysqli扩展程序来连接和运行您的查询,但是您使用mysql(注意最后没有i)扩展来获取您插入的ID,这可以'工作。虽然它们都是提供对mysql的访问的扩展,但它们也是两个非常不同的库,并且不能彼此共享连接。

为了记录,mysqli是你应该使用的,mysql是“旧”版本,不支持mysql的新功能&gt; = 4.1

换句话说,解决方案是使用mysqli_insert_id()

另外,正确地转义你的参数,你不能将$ _GET和$ _POST变量的内容放在你的查询中,不安全。至少使用mysqli_real_escape_string()

 $query = "INSERT INTO meetup.EventComments (EventID, OwnerID, Comment,     DateTime) 
        VALUES (" . mysqli_real_escape_string($eventID)." [...]

有关此内容的更多信息,请查看有关此主题的众多问题,例如:How to properly escape a string via PHP and mysql

答案 1 :(得分:2)

您可能希望使用等效的mysqli扩展名:mysqli_insert_id()

可能通过传递连接资源来工作,但即使这样做,也不好混合两个独立连接类的方法:

    $id = mysql_insert_id($db_connection);

答案 2 :(得分:0)

DATETIME是MySQL中的Data Type,这就是为什么INSERT查询不起作用的原因。请改用反叛`

$query = "INSERT INTO meetup.EventComments (`EventID`, `OwnerID`, `Comment`, `DateTime`) 
VALUES (" . $eventID . ", " . $ownerID .", '" . $comment . "', '". $dateTime ."')";