I have two table: word(id,word,meaning) and userword(id,wordid,userid) in both of them id is auto increment. In a form I get word and the meaning from user and then I want to insert this word into these to table. Insertion to words works well but for insertion to userword I have to get wordid from words and then insert into userword but it doesn't work here is my form:
<form action="InsertWord.php" method="post">
<input name="word" id="word" type="text" maxlength="255" />
<label for="user">:word</label></br></br>
<input name="meaning" id="mean" type="text" maxlength="255" />
<label for="pass">:meaning</label></br></br>
<input type="submit" value="insert" /></br></br>
</form>
and InsertWord.php:
<?php
session_start();
$con = mysql_connect("localhost", "root", "")
or die(mysql_error());
if (!$con) {
die('Could not connect to MySQL: ' . mysql_error());
}
mysql_select_db("project", $con)
or die(mysql_error());
if(isset($_POST["word"]) && isset($_POST["meaning"]))
{
$word = $_POST["word"];
$meaning = $_POST['meaning'];
$user= $_SESSION['userid'];
mysql_query("INSERT INTO words (word,meaning) values ('".$word."','".$meaning."')") or die(mysql_error());
$qwordid = mysql_query("SELECT id FROM words WHERE word='$word'") or die(mysql_error());
$fwordid = mysql_fetch_array($qwordid);
$wordid= $fwordid['id'];
mysql_query("INSERT INTO userword (user_id,word_id) values ('".$user."','".$wordid."')") or die(mysql_error());
//HEADER('LOCATION: InsertIntoUserword.php');
}
else
die('wrong!');
?>
because I insert into words and then database not refreshed it doesn't work for userword what can I do?
The function mysql_insert_id()
returns the id of the last inserted row:
$wordid = mysql_insert_id();
You can use mysql_insert_id()
but I recomend change to mysqli or PDO extension, because mysql extension will be deprecated and remove in a future, you can see this in http://www.php.net/manual/en/function.mysql-insert-id.php