传递get_insert_id的值

时间:2012-07-24 07:57:14

标签: php

你能帮我吗? 我试图保存插入的最后一个id,但它继续保存0,我不明白为什么。抱歉noob在这里:( 这是我的代码

索引

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

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");

聊天

    <?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>

和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")

3 个答案:

答案 0 :(得分:1)

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

因为0 aster插入查询

的结果,你必须得到mysql_insert_id

如果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])."')");

答案 1 :(得分:1)

来自php.net

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

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

另外,使用PDO或mysqli。不推荐使用mysql_ *。

答案 2 :(得分:-1)

您可能希望在浏览器不支持NAME标记的情况下添加ID标记 试试这个

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