insert_id is keep saying 0 - php

goodday.
I've a class called nieuws and i want to created a function that insert a record into the database. After that i need that id of the created record for something else so I sawon the internet that $...->insert_id has to give the id of the last created record in that table. But that did not work by me.
Anyone know what is wrong here?
$sql = "INSERT INTO nieuws (`id`, `titel`, `datum`, `gebruikerId`, `text`) VALUES (NULL, ?, ?, ?, ?)";
if ($datum = $this->_db->prepare($sql)) {
$datum->bind_param("siis", $this->_title, $this->_date, $this->_gebruikerId, $this->_tekst);
$datum->execute();
$this->_id = $datum->insert_id;
//$this->addRssNieuws();
}

The insert_id is an attribute of the connection, not the statement.
$this->_id = $this->_db->insert_id;
should work.

Related

Mysql MAX ID+1 incriment with insert query

Please help in manually incrementing id filed with insert query and PDO
(note: No primary key set in table)
if ($valid) {
$max="SELECT MAX(id)+1 from class";
$sql = "INSERT INTO class (id,Class,Notes) values(?,?, ?)";
$q = $pdo->prepare($sql);
$q->execute(array($max,$Class, $Notes));
header("Location: class_create.php");
}
This insert not incrementing id, Please help
INSERT INTO class (id, Class, Notes)
SELECT MAX(id)+1, ?, ?
FROM class
and
$q->execute(array($Class, $Notes));
Be ready to duplicated values due to parallel execution interference.

Update already existing values while adding new ones

I'm inserting some values into my database.
$stmt = $conn->prepare("INSERT INTO `members` (`id`, `name`, `nickname`, `prefix`, `suffix`) VALUES (?, ?, ?, ?, ?)");
$stmt->bind_param("sssss",$row['member_id'], $row['name'], $row['nickname'], $row['prefix'], $row['suffix']);
$stmt->execute();
This does what I want: if a new user has joined this will add them to members. However, if an already existing member has changed their nickname this info doesn't get updated. I would like to 1) add new members like it currently does but also 2) update the nicknames for already existing members if there are any changes.
I tried adding the following code after the one above (first add members and then update) but it doesn't seem to work as I wanted.
$stmt = $conn->prepare("UPDATE members SET nickname = '?' WHERE id = '?'");
$stmt->bind_param("ss",$row['nickname'], $row['id']);
$stmt->execute();
You can use REPLACE INTO instead of INSERT INTO
Your prepare() would have
REPLACE INTO `members` (`id`, `name`, `nickname`, `prefix`, `suffix`) VALUES (?, ?, ?, ?, ?)
REPLACE updates the new data if the primary key value already exists.
More details here: https://dev.mysql.com/doc/refman/5.5/en/replace.html

How to return ID of existing row if there is a duplicate row during MySQL INSERT?

I have two tables: movies and genres, and a junction table movieOfGenre for many-to-many relationships between the movies and genres tables. Now, when I am using transactions to insert movies and genres into my database using PHP, genres were being created twice even if there was a duplicate. Then I updated the code with ...ON DUPLICATE KEY UPDATE... and now if there is an existing genre with the same name, the auto_increment ID of the existing genre is being updated when I use this transaction query:
mysqli_autocommit($connect, false);
$query_success = true;
$stmt = $connect->prepare("INSERT INTO movies (id, title, plot, rating, releaseDate, duration, language, country, posterUrl, trailerUrl) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("ssssssssss", $defaultId, $title, $plot, $rating, $releaseDate, $duration, $language, $country, $poster, $trailer);
if (!$stmt->execute()) {
$query_success = false;
}
$movieId = mysqli_insert_id($connect);
$stmt->close();
foreach ($genres as $genre) {
$stmt = $connect->prepare("INSERT INTO genres (id, name) VALUES (?, ?) ON DUPLICATE KEY UPDATE id = LAST_INSERT_ID()");
$stmt->bind_param("ss", $defaultId, $genre);
if (!$stmt->execute()) {
$query_success = false;
}
$genreId = mysqli_insert_id($connect);
$stmt->close();
$stmt = $connect->prepare("INSERT INTO movieofgenre (movieId, genreId) VALUES (?, ?)");
$stmt->bind_param("ii", $movieId, $genreId);
if (!$stmt->execute()) {
$query_success = false;
}
$stmt->close();
}
if ($query_success) {
mysqli_commit($connect);
} else { ?>
alert('Error adding movie.');
<?php mysqli_rollback($connect);
}
How do I write the query so that if during insertion there is an existing row with the same genre.name, it returns the ID of the existing row without updating it?
Thanks in advance.
genres.name should be a unique column:
CREATE TABLE genres
...
UNIQUE KEY name
use IGNORE - duplicate exception will not be thrown
INSERT IGNORE INTO genres (name) VALUES (?)
get the id by name:
SELECT id FROM genres WHERE name = ?
I'm not sure this help but you may want to check example below. Lazy to do php coding this days, But I have similar issue with MYSQL last time if I understand your issue correctly :P
INSERT INTO sample_table (unique_id, code) VALUES ('$unique_id', '$code')
ON DUPLICATE KEY UPDATE code= '$code'
Hope this resolve your problem

Issue On Inserting Auto Incremented ID in MySQL Using Prepared Statement

I have table in MySQL database called MyGuests which has 4 fields as : id (PK and Auto Increment), name,age and email. I am using following code to insert data from user input form to the database:
<?php
$sql = mysqli('localhost','user','password','database');
$name = $_POST['name'];
$age = $_POST['age'];
$email = $_POST['email'];
$query = $sql->prepare("INSERT INTO MyGuests ( id, name, age, email) VALUES (?, ?, ?, ?)");
$query->bind_param("isis",$name,$age,$email);
$query->execute();
?>
now I am confused how to insert value for id which is auto incremented field using the Prepared statement! As you can see I passed 4 parameters as (?, ?, ?, ?) for data entry and used the "isis" for bind_param(); but not sure what must put in $name,$age,$email for id?
Can you please help me to figure this out?
Thanks
Just omit the id in the query i.e.
INSERT INTO MyGuests ( name, age, email) VALUES (?, ?, ?)
It will automatically add the incremented id, hence the name :)
one more option is supplying null value to the auto-increment column:
ie.
instead of $query = $sql->prepare("INSERT INTO MyGuests ( id, name, age, email) VALUES (?, ?, ?, ?)"); use $query = $sql->prepare("INSERT INTO MyGuests ( id, name, age, email) VALUES (null, ?, ?, ?)");

Insert auto-incremented ID using prepared statements

When inserting a new record into a table with an auto-incrementing ID column, it is normally enough to give the ID field the value NULL or omit it from the INSERT query, as explained at How to insert new auto increment ID
INSERT INTO `database`.`table` (`id`, `user`, `result`) VALUES (NULL, 'Alice', 'green')");
or
INSERT INTO `database`.`table` (`user`, `result`) VALUES ('Alice', 'green')");
My question is - how do you do the same thing when using prepared statements. I have tried the following, using NULL:
$stmt = $db->prepare("INSERT INTO `db` (id, name, password, text) VALUES (NULL, ?, ?, ?)");
$stmt->bind_param('sss', $name, $password, $text);
$stmt->execute();
and the fowllowing, omitting the ID field:
$stmt = $db->prepare("INSERT INTO `test_db` (name, password, text) VALUES (?, ?, ?)");
$stmt->bind_param('sss', $name, $password, $text);
$stmt->execute();
When I run this I get nothing inserted and no error message in the browser. I think it is because it is trying to insert a duplicate value for the ID field (stackoverflow.com/questions/12179770/…) - but why it should do that when this seems equivalent to the non-prepared-statement way of inserting data, and then give no message, I'm not sure.
Any ideas most welcome!

Categories