How will i get the last insert id in mysql following code?
All variable are set.
Insertion works!
$Restconnection = mysqli_connect("host","user","passwd","db ");
$query3 = mysqli_query($Rconnection, $strSQL3);
$stmt = $conn->prepare("INSERT INTO table (name, email, password) VALUES(?,?,?)");
$stmt->bind_param("sss", $name, $email, $password);
$stmt->execute();
$last_id = $conn->insert_id;
echo "Last inserted ID is: " . $last_id;
print mysqli_insert_id($Restconnection);
http://php.net/manual/de/mysqli.insert-id.php
Use mysqli_insert_id($connection)
Use the following:
$last_insert_id = mysqli_insert_id($Restconnection);
Related
I am having a weird problem with a insert statment. What's happening is that if I insert into only one column, it works but anything greater than 1 column doesn't get inserted and there are no errors displayed
This works
$db = mysqli new('localhost','root','','db');
$stmt = $db->prepare("insert into test (id) values(?)");
echo $db->error;
$stmt->bind_param("s",$id);
$stmt->execute();
But not this:
$id = 1;
$name = "test";
$stmt = $db->prepare("insert into test (id,name) values(?,?)");
echo $db->error;
$stmt->bind_param("ss",$id, $name);
$stmt->execute();
Does anyone have a clue? Not sure if this is helpful but some of the columns don't have a value under collation tab and others have latin1_swedish_ci in the table
Try to bind parameters separately, Like below:
$stmt = $db->prepare("insert into test (id,name) values(:id, :name)");
echo $db->error;
$stmt->bind_param(":id", $id);
$stmt->bind_param(":name", $name);
$stmt->execute();
Problem:
I have made a simple form that uses PHP to pass information to my database via a INSERT query. However, every time I run it, it tries to put the information in twice. How can I avoid this?
Explanation:
I first insert the answers, into my answers table, save the AnswerID as a variable. Then do the save with my question table and lastly I use the two saved variables containing the ID's into my question_answers table.
My code:
if (isset($_POST['textinput1']) && !empty($_POST['textinput1'])) {
$text1 = mysqli_real_escape_string($conn, $_POST['textinput1']);
$text2 = mysqli_real_escape_string($conn, $_POST['textinput2']);
$q_text = mysqli_real_escape_string($conn, $_POST['textarea']);
$stmt = $conn->prepare("INSERT INTO answers (Answer1Text, Answer2Text) VALUES (?, ?)");
$stmt->bind_param('ss', $text1, $text2);
$stmt->execute();
$answerid = $stmt->insert_id;
$stmt = $conn->prepare("INSERT INTO question (QuestionText) VALUES (?)");
$stmt->bind_param('s', $q_text);
$stmt->execute();
$questionid = $stmt->insert_id;
if ($stmt->execute()) {
$stmt = $conn->prepare("INSERT INTO question_answers (AnswerID, QuestionID) VALUES (?, ?)");
$stmt->bind_param('ss', $answerid, $questionid);
$stmt->execute();
echo "<h2>Dit spørgsmål er nu lagt op på siden!</h2>";
echo "<h3>Tusinde tak for din interesse for SMIL - Skodfri Århus.</h3>";
}
else
{
echo "ERROR: Could not able to execute . " . mysqli_error($conn);
}
}
// close connection
mysqli_close($conn);
?>
My tables of importance:
question: QuestionID(PK), QuestionText
answers: AnswerID(PK), Answer1Text, Answer2Text
question_answers: QuestionAnswerID(PK), QuestionID(FK), AnswerID(FK)
Ps. I prefer not to use composite unique constraint as a solution.
Also a side-question, should $stmt->insert_id variables be mysqli_real_escape_string?
Your problem is that you have executed the second query TWICE
if (isset($_POST['textinput1']) && !empty($_POST['textinput1'])) {
$text1 = mysqli_real_escape_string($conn, $_POST['textinput1']);
$text2 = mysqli_real_escape_string($conn, $_POST['textinput2']);
$q_text = mysqli_real_escape_string($conn, $_POST['textarea']);
$stmt = $conn->prepare("INSERT INTO answers (Answer1Text, Answer2Text) VALUES (?, ?)");
$stmt->bind_param('ss', $text1, $text2);
$stmt->execute();
$answerid = $stmt->insert_id;
$stmt = $conn->prepare("INSERT INTO question (QuestionText) VALUES (?)");
$stmt->bind_param('s', $q_text);
$stmt->execute();
$questionid = $stmt->insert_id;
// THIS IS THE SECOND EXECUTION OF QUERY 2
if ($stmt->execute()) {
$stmt = $conn->prepare("INSERT INTO question_answers (AnswerID, QuestionID) VALUES (?, ?)");
$stmt->bind_param('ss', $answerid, $questionid);
$stmt->execute();
echo "<h2>Dit spørgsmål er nu lagt op på siden!</h2>";
echo "<h3>Tusinde tak for din interesse for SMIL - Skodfri Århus.</h3>";
}
else
{
echo "ERROR: Could not able to execute . " . mysqli_error($conn);
}
}
// close connection
mysqli_close($conn);
?>
Instead try this as the IF test
//if ($stmt->execute()) {
if ( isset($answerid,$questionid) ) {
if ($stmt->execute()) {
this runs one of your statements a second time. You should assign the return value to a variable if you need it for something later.
I have this following example query, which works - I CAN insert values into my MySQL table, which also includes an unique id column. I want to get the id from the inserted row, after I execute the query. However what I get is 0 every time ($gotId=0).
What am I doing wrong?
$stmt = $conn->prepare("INSERT INTO ....... ");
$stmt-> bind_param("ss", ....);
$stmt->execute();
$gotId = $conn->insert_id;
Full query:
$conn = $db->connect();
$stmt = $conn->prepare("INSERT INTO table(value1, value2) VALUES(?, ?)");
$stmt-> bind_param("ss", $value1, $value2);
$stmt->execute();
$gotId = $conn->insert_id;
After calling the execute() method on the PreparedStatement, the id of the insert row will be in the insert_id attribute Only read it.
$stmt->execute();
$gotId = $stmt->insert_id;
Taken from here
$query = "INSERT INTO .......";
$mysqli->query($query);
printf ("New Record has id %d.\n", $mysqli->insert_id);
More Info
I've been scratching my head over this code for a couple of hours....
Doesn't make sense to me why it doesn't work
$isCorrect =($question->correct_answer == $body->answer) ? 1:0;
// the values are all there.......
// echo $body->question . "\n"; //335
// echo $body->user . "\n"; //51324123
// echo $question->day . "\n"; //0
// echo $isCorrect . "\n"; //0
//but still the below part fails.
$db = getConnection();
$sql = "INSERT INTO `answers` (`id`, `question_id`, `user`, `day`, `is_correct`) VALUES (NULL, ':question', ':user', ':day', :is_correct)";
$stmt = $db->prepare($sql);
$stmt->bindParam(":question_id", $body->question);
$stmt->bindParam(":user", $body->user);
$stmt->bindParam(":day", $question->day, PDO::PARAM_INT);
$stmt->bindParam(":is_correct", $isCorrect, PDO::PARAM_INT);
$stmt->execute();
gives this error:
SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
I'm counting 4 tokens... what am I missing? Obviously I'm doing something wrong.
Try it like this:
$sql = "INSERT INTO `answers` (`id`, `question_id`, `user`, `day`, `is_correct`)
VALUES
--The :variable shouldn't be surrounded by ''--
(NULL, :question, :user, :day, :is_correct)";
$stmt = $db->prepare($sql);
//The values used in $sql should be the same here, so not :question_id but :question
$stmt->bindParam(":question", $body->question);
$stmt->bindParam(":user", $body->user);
$stmt->bindParam(":day", $question->day, PDO::PARAM_INT);
$stmt->bindParam(":is_correct", $isCorrect, PDO::PARAM_INT);
just don't use bindParam with PDO
as well as named parameters. it will save you a ton of headaches
$db = getConnection();
$sql = "INSERT INTO `answers` VALUES (NULL, ?,?,?,?)";
$data = [$body->question,$body->user,$question->day,$isCorrect];
$stmt = $db->prepare($sql)->execute($data);
change :
$stmt->bindParam(":question_id", $body->question);
to:
$stmt->bindParam(":question", $body->question);
You have use in query :question but binding with wrong key(:question_id).
$stmt->bindParam(":question_id", $body->question);
should be
$stmt->bindParam(":question", $body->question);
This is just a little typo.
mysql_insert_id does not return the last inserted id when i place it inside a function.
im kinda confused why it does not.
here is my code:
function addAlbum($artist,$album,$year,$genre) {
$connection = mysql_connect(HOST,USER,PASS);
$sql = 'INSERT INTO `'.TABLE_ARTIST.'` (artistName) VALUES ("'.$artist.'")';
$resultArtist = mysql_query($sql);
$sql = 'INSERT INTO `'.TABLE_ALBUMS.'` (albumName) VALUES ("'.$album.'")';
$resultAlbums = mysql_query($sql);
$sql = 'INSERT INTO `'.TABLE_GENRE.'` (musicGenre) VALUES ("'.$genre.'")';
$resultGenre = mysql_query($sql);
$sql = 'INSERT INTO `'.TABLE_YEAR.'` (albumYear) VALUES ("'.$year.'")';
$resultYear = mysql_query($sql);
$lastId = mysql_insert_id();
$sql = 'INSERT INTO `'.TABLE_LINK.'` (albumsId,artistId,genreId,yearId) VALUES ("'.$lastId.'","'.$lastId.'","'.$lastId.'","'.$lastId.'")';
$resultLink = mysql_query($sql);
if(!$resultArtist && $resultAlbums && $resultGenre && $resultYear && $resultLink){
echo mysql_error();
}
}
thanks in advance
adam
You are calling mysql_insert_id() once after four separate INSERTs, and using that ID four times for albumsId, artistId, genreId and yearId. That doesn't seem right.
You should also check that your tables are using AUTO_INCREMENT fields. If not, mysql_insert_id() will not return the insert ID. See the docs:
http://www.php.net/manual/en/function.mysql-insert-id.php
I highly recommend that you use prepared statements with mysqli::prepare, perhaps via PDO. It's ultimately simpler and safer. Here's an untested example:
$dsn = 'mysql:dbname=test;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
$dbh = new PDO($dsn, $user, $password);
$stmt_artist = $dbh->prepare(
'INSERT INTO `table_artist` (artistName) VALUES (?)'
);
$stmt_albums = $dbh->prepare(
'INSERT INTO `table_albums` (albumName) VALUES (?)'
);
$stmt_genre = $dbh->prepare(
'INSERT INTO `table_genre` (musicGenre) VALUES (?)'
);
$stmt_year = $dbh->prepare(
'INSERT INTO `table_year` (albumYear) VALUES (?)'
);
$stmt_link = $dbh->prepare(
'INSERT INTO `table_link` (albumsId, artistId, genreId, yearId) '.
'VALUES (?, ?, ?, ?)'
);
$stmt_albums->execute(array( $artist ));
$artist_id = $dbh->lastInsertId();
$stmt_albums->execute(array( $album ));
$album_id = $dbh->lastInsertId();
$stmt_genre->execute(array( $genre ));
$genre_id = $dbh->lastInsertId();
$stmt_year->execute(array( $year ));
$year_id = $dbh->lastInsertId();
$stmt_link->execute(array( $artist_id, $album_id, $genre_id, $year_id ));
You need to call it separately for each insert, and store the result of each call separately. Like this:
$sql = 'INSERT INTO `'.TABLE_ARTIST.'` (artistName) VALUES ("'.$artist.'")';
$resultArtist = mysql_query($sql);
$lastArtistId = mysql_insert_id();
$sql = 'INSERT INTO `'.TABLE_ALBUMS.'` (albumName) VALUES ("'.$album.'")';
$resultAlbums = mysql_query($sql);
$lastAlbumId = mysql_insert_id();
$sql = 'INSERT INTO `'.TABLE_GENRE.'` (musicGenre) VALUES ("'.$genre.'")';
$resultGenre = mysql_query($sql);
$lastGenreId = mysql_insert_id();
$sql = 'INSERT INTO `'.TABLE_YEAR.'` (albumYear) VALUES ("'.$year.'")';
$resultYear = mysql_query($sql);
$lastYearId = mysql_insert_id();
$sql = 'INSERT INTO `'.TABLE_LINK.'` (albumsId,artistId,genreId,yearId) VALUES ("'.$lastAlbumId.'","'.$lastArtistId.'","'.$lastGenreId.'","'.$lastYearId.'")';
Also, it only works if each of tables you're inserting into has AUTO_INCREMENT enabled.
Did you ever try to debug your code?
With echo() (for showing your SQL queries) or var_dump() (for checking the results of e. g. mysql_insert_id(), mysql_query()).
Also check mysql_error().
Furthermore be sure to set the resource identifier in your mysql_*() functions. It's possible to have more than just one open MySQL resource - so be sure to identify the resource.
For example:
$result = mysql_query($SQL, $connection);
$lastInsertID = mysql_insert_id($connection);
And - it's very important to know that mysql_insert_id() just works with tables which have an AUTO_INCREMENT-field.
And what's also interesting with your code: you call mysql_insert_id solely after the last of 5 queries. Is this really wanted? So you only receive the ID of your last INSERT query.