0

Can you please help me here. I am trying to save the last id inserted, but it keeps on saving 0, which I don't understand why. Sorry noob here :( Here are my codes

the index

<form action="save_member.php" method="POST">
            Enter your username: <input type="text" name="member"/>
            <input type="submit" value="Submit"/>
        </form>

the save_member

include 'connect.php';
session_start();
$_SESSION['member_id'] = $_POST[member];
$sql = mysql_query("insert into users (idusers, member) values ('', '$_POST[member]')");
$_SESSION['last_id'] = mysql_insert_id();
header("Location: chat.php");

the chat

    <?php
    session_start();
    echo "hello" . " " . $_SESSION['member_id'];
    echo "<br/>";
    ?>
    <?php
    include 'connect.php';
    $q = mysql_query("select * from messages order by time_sent desc");
    while ($w = mysql_fetch_array($q)) {
        ?>
        <div id="show_messages" style="">
            <span id="wrap_messages" style="">
                <span id="message" style=""><?php echo $w['message']; ?> </span> :
                <span id="member_id" style=""><?php echo $w['member_id']; ?></span>
            </span>
        </div>
    <?php } ?>
    <br/>
    <div style="margin-right: 450px !important; width: 300px; float: right;">
        <form action="sent_chat_message.php" method="POST">
            <input type="hidden" name="member_id"/>
            <input type="text" name="chat"/>
            <input type="submit" value="Submit"/>
        </form>
    </div>

and the sent_chat_message

include 'connect.php';
session_start();
$_SESSION['last_id'] = $last_id;
$r = mysql_query("insert into messages (idmessages, message, member_id) values ('', '$_POST[chat]', '.$last_id.')");
header("Location: chat.php")
4

4 回答 4

1

您确定插入查询已成功执行吗?

因为'这一定是你得到0作为mysql_insert_idaster 插入查询结果的原因

如果 idusers 是主键,我建议传递 NULL 值而不是空字符串

$sql = mysql_query("insert into users (idusers, member) values ('', '$_POST[member]')");

您的查询应该是

$sql = mysql_query("insert into users (idusers, member) values (NULL, '".mysql_real_escape_string($_POST[member])."')");
于 2012-07-24T08:02:19.823 回答
1

来自php.net

检索上一个查询(通常是 INSERT)为 AUTO_INCREMENT 列生成的 ID。

您的 id 字段是否设置为 AUTO_INCREMENT?

另外,使用 PDO 或 mysqli。mysql_* 已弃用。

于 2012-07-24T08:06:46.610 回答
0

这个线程解决了。我所做的是

if (isset($_SESSION['last_id']))
    $_SESSION['last_id'] = $_SESSION['last_id'];
else
    $_SESSION['last_id'];
于 2012-07-27T09:26:37.307 回答
-1

You might want to add the ID tag just in-case your browser does not support the NAME tag Try this

<form action="save_member.php" method="POST">
            Enter your username: <input type="text" name="member" id="member"/>
            <input type="submit" value="Submit"/>
        </form>
于 2012-07-24T08:00:44.307 回答