简体   繁体   中英

PHP and MySQL - Inserting values into table using identifier

I've been trying to insert values into a table using PHP.

This is the code for form

...<table>...
<?php
    $query2=("SELECT * FROM test WHERE id=$id");
    $result2=mysql_query($query2);
    while($row2=mysql_fetch_array($result2))
    {
?>
    <tr>
        <td><?php echo $row2[3]; ?></td>
        <td><?php echo $row2[4]; ?></td>
        <td><?php echo $row2[5]; ?></td>
    </tr>
<?php
}
?>
</table>
---
<form name="reply" method="post" action="reply.php?id=<?php echo $row2['id']; ?>">
    <textarea name="reply" placeholder="Reply"></textarea>
    <input type="submit" value="Submit" />
</form>
---

As you can see, I'm using a query to figure out id value and try forcing that value into form action.

And this is the code to submit form

<?php
session_start();
include("connect.php");

$nametemp=$_SESSION['name'];
$hour=date('H:i');
$idtemp=$_GET['id'];
$reply=($_POST['reply']);

mysql_query("INSERT into testtab2 (id, nama, content, time) VALUES ('$idtemp', '$nametemp', '$reply', '$hour')");
header("location:discussion.php"); die();
?>

The code works well, but the id (not primary key) value when inserted into table is always 0 instead of whatever the real id is, the other values inserted properly. What am I doing wrong? Help is appreciated.

Thanks for posting. After many hours of trial and errors, I have successfully inserted the id into my table by using $_SESSION['idtemp'] first then declaring said session into variable $idtemp.

$idtemp=$_SESSION['idtemp'];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM