Get last ID on CRUD [duplicate] - php

$query = "INSERT INTO news VALUES (NULL, :param1 , :param2 )";
$stmt = $pdo->prepare($query);
$params = array(
"param1" => $p['title'],
"param2" => $p['body'],
);
$data = $stmt->execute($params);
// here i would like get current inserted ID. Is possible?
$id = $data->id ???? ;
How can i make this?

$query = "INSERT INTO news VALUES (NULL, :param1 , :param2 )";
$stmt = $pdo->prepare($query);
$params = array(
"param1" => $p['title'],
"param2" => $p['body'],
);
$data = $stmt->execute($params);
so you can do like this to get last inserted Id
$last_id = $pdo->lastInsertId();

Use :
$last_insert_id = $pdo->lastInsertId();

You could use PDO::lastInsertId
$last_insert_id = $pdo->lastInsertId();

Related

Query conditions to insert data from a form

What I'm trying to do is:
If the age input in my form = 28, 30, 25 or 21 then I want to auto insert value 8 in the column (VE), else keep it empty. Is this the right way to do that?
if($form_data->action == 'Insert')
{
$age=array(28, 30, 25, 21);
$age_str=implode("','", $age);
if($form_data->age == $age_str){
$query="INSERT INTO tbl
(VE) VALUE ('8') WHERE id= '".$form_data->id."'
";
$statement = $connect->prepare($query);
$statement->execute();
}
$data = array(
':date' => $date,
':first_name' => $first_name,
':last_name' => $last_name,
':age' => $age
);
$query = "
INSERT INTO tbl
(date, first_name, last_name, age) VALUES
(:date, :first_name, :last_name, :age)
";
$statement = $connect->prepare($query);
if($statement->execute($data))
{
$message = 'Data Inserted';
}
}
Also, how do I insert the new row with the row id from the other form data going into tbl?
Use php's in_array instead of trying to compare a string. To get the id of the query where you insert the form data, you can return the id of the insert row from your prepared statement.
if ($form_data->action == 'Insert') {
// assuming $age, $date, $first_name, $last_name
// already declared prior to this block
$data = array(
':date' => $date,
':first_name' => $first_name,
':last_name' => $last_name,
':age' => $age
);
$query = "
INSERT INTO tbl
(date, first_name, last_name, age) VALUES
(:date, :first_name, :last_name, :age)
";
$statement = $connect->prepare($query);
if ($statement->execute($data)) {
$message = 'Data Inserted';
// $id is the last inserted id for (tbl)
$id = $connect->lastInsertID();
// NOW you can insert your child row in the other table
$ages_to_insert = array(28, 30, 25, 21);
// in_array uses your array...so you don't need
// if($form_data->age == $age_str){
if (in_array($form_data->age, $ages_to_insert)) {
$query="UPDATE tbl SER VE = '8' WHERE id= '".$id."'";
$statement2 = $connect->prepare($query);
$statement2->execute();
}
}
}

PDO transaction last inserted id in table1 to be used in table2

I have a form where I publish data to two different db tables. You can see my Transaction below.
$db->beginTransaction();
$sql = "INSERT INTO clients (name, contact_person, phone, email, url)
VALUES (:name, :contact_person, :phone, :email, :url)";
$stm = $db->prepare ( $sql );
$stm->bindParam ( ":name", $name );
$stm->bindParam ( ":contact_person", $contact_person );
$stm->bindParam ( ":phone", $phone );
$stm->bindParam ( ":email", $email );
$stm->bindParam ( ":url", $url );
$client = $stm->execute ();
//$last_id = $db->lastInsertId;
$sql = "INSERT INTO task (title, description, user_id, status_id, client_id)
VALUES (:title, :description, :user_id, :status_id ,:client_id)";
$stm = $db->prepare ( $sql );
$stm->bindParam ( ":title", $title );
$stm->bindParam ( ":description", $description );
$stm->bindParam ( ":user_id", $user_id );
$stm->bindParam ( ":status_id", $status_id );
//$stm->bindParam ( ":client_id", $last_id );
$task = $stm->execute ();
$db->commit();
However, in my table "task" I have another column "client_id" where I want to bind a value. And the value here, should be the same as the id value that has been auto-incrementet on my clients table.
I therefor need to somehow get the last insertet id from table one, and use that value in table two. I have outcommented my failed attempt, which didn't work, and returned NULL
Can anyone give me some pointers on how to manage this?
Use the function instead:
$last_id = $db->lastInsertId();
Put the execute statment of first tbl into
-----> if() condition
and get a last inserted id of table1 using
-----> $last_id = $this->conn->lastInsertId();
Replace your $sql query value
-----> :client_id replace with $last_id
here is the correct code (Remove the stars from code)
**if(**$client = $stm->execute ()**){**
**$last_id = $this->conn->lastInsertId();**
$sql = "INSERT INTO task (title, description, user_id, status_id, client_id)
VALUES (:title, :description, :user_id, :status_id ,**$last_id**)";
$stm = $db->prepare ( $sql );
$stm->bindParam ( ":title", $title );
$stm->bindParam ( ":description", $description );
$stm->bindParam ( ":user_id", $user_id );
$stm->bindParam ( ":status_id", $status_id );
$stm->bindParam ( ":client_id", $last_id );
$task = $stm->execute ();
$db->commit();
}

How to insert data into nested tables through PHP?

I think this is something related to PDO.
this is my patientinfo table
patientid | name | age | email | address
and this is my remarks tables
patientid | remarksid | date | description
I'd like to INSERT data to the patientinfo and to the remarks table where patientid of both tables will be synchronized. The problem is I dont know how to query this. This is what I do but it gives me an error.
$query = "INSERT INTO patientinfo (name, age, email, address)
VALUES (:name, :age, :email, :address);";
$query_params = array(
':name' => $_POST['name'],
':age' => $_POST['age'],
':email' => $_POST['email'],
':address' => $_POST['address'],
);
$query = "INSERT INTO remarks (patient_id, description) VALUES (:patient_id, :remarks) WHERE remarks.patient_id = patientinfo.patient_id;";
$query_params = array(':remarks' => $_POST['remarks']);
try{
$stmt = $dbname->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex){
$response["success"] = 0;
$response["message"] = $ex ;
die(json_encode($response));
}
i made patientid in the patientinfo AUTOINCREMENT.
PLEASE! THANK YOU SO MUCH FOR YOUR HELP!
$query = "INSERT INTO patientinfo (name, age, email, address)
VALUES (:name, :age, :email, :address);";
$query_params = array(
':name' => $_POST['name'],
':age' => $_POST['age'],
':email' => $_POST['email'],
':address' => $_POST['address'],
);
try{
$stmt = $dbname->prepare($query);
$stmt->execute($query_params);
$patient_id = $dbname->lastInsertId();
$query = "INSERT INTO remarks (patientid, description) VALUES (:patient_id, :remarks)";
$query_params = array(':remarks' => $_POST['remarks'],':patient_id'=>$patient_id);
$q = $dbname->prepare($query);
$q->execute($query_params);
}catch(PDOException $ex){
$response["success"] = 0;
$response["message"] = $ex ;
die(json_encode($response));
}
You should write something like that. Check column names please(patientid or patient_id ? )

Update query with PDO throws error

I'm trying to get the hang of PDO but I'm getting the following error:
Call to a member function execute() on a non-object
Here's my code to update the members table
$firstname = ($_POST['firstname']);
$lastname = ($_POST['lastname']);
$update = query("UPDATE members SET
firstname = '$firstname',
lastname = '$lastname',
WHERE id = '$id'" );
$q = $conn->prepare($update);
$q->execute(array($firstname,$lastname));
What am I doing wrong here ?
Your use of parentheses around your variables makes them true/false which is not your intent. Then, the whole point of using prepared statements is not to directly insert data into your queries, but instead either use ? or :someVariable so they will be properly escaped and can be used for multiple inserts. Try something like the following:
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$id = $_POST['id'];
$update = query("UPDATE members SET firstname = ?, lastname = ? WHERE id = ?");
$q = $conn->prepare($update);
$q->execute(array($firstname,$lastname,$id));
//OR
$update = query("UPDATE members SET firstname = :firstname , lastname = :lastname WHERE id = :id");
$q = $conn->prepare($update);
$q->execute(array('firstname'=>$firstname,'lastname'=>$lastname,'id'=>$id));
You have a comma where you shouldn't have one:
$update = query("UPDATE members SET
firstname = '$firstname',
lastname = '$lastname'
WHERE id = '$id'" );
Should work, though I would use params in the prepared SQL statement.
$update = query("UPDATE members SET
firstname = :FirstName,
lastname = :LastName
WHERE id = :ID" );
$q = $conn->prepare($update);
$q->execute(array(':FirstName' => $firstname, ':LastName' => $lastname, ':ID' => $ID));
the parameters must be a key value array. string key being the associated parameter in the prepared sql.
$q->execute(array(
'firstname' => $firstname,
'lastname' => $lastname
));
and you're missing 'id' parameter
also, the parameters in the query should prefix with a colon
$update = query("UPDATE members SET
firstname = :firstname,
lastname = :lastname
WHERE id = :id" );

mysql_insert_id, does not return the last inserted id when i place it in a function

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.

Categories