PDO how to get auto_increment value from a table - php

I am creating a calendar in php and grabbing events from a database. We also have to insert events using prepared PDO statements. I can successfully create the new event and insert it into an event table. I also have to link and event with a family member.
$stmt = $handle->prepare("INSERT INTO events(name, description, starthour, meridian, eventdate)
VALUES(:name, :description, :starthour, :meridian, :eventdate)");
$stmt->execute(array(
"name" => $name,
"description" => $description,
"starthour" => "$starthour",
"meridian" => "$meridian",
"eventdate" => "$eventdate"
));
$stmt1 = $handle->prepare("INSERT INTO familymemberevents(familymemberID,eventID)
VALUES(:familymemberID, :eventID)");
$stmt1->execute(array(
"familymemberID" => $familymemberid,
"eventID" =>
));
eventID auto-increments. Is there anyway I can get this number from the database?
Thanks in advance!

$stmt = $handle->prepare("INSERT INTO events(name, description, starthour, meridian, eventdate)
VALUES(:name, :description, :starthour, :meridian, :eventdate)");
$stmt->execute(array(
"name" => $name,
"description" => $description,
"starthour" => "$starthour",
"meridian" => "$meridian",
"eventdate" => "$eventdate"
));
$eventID = $handle->lastInsertId();
if($eventID){
//Event Insert successful, continue with familymemberevent insert
$stmt1 = $handle->prepare("INSERT INTO familymemberevents(familymemberID,eventID)
VALUES(:familymemberID, :eventID)");
$stmt1->execute(array(
"familymemberID" => $familymemberid,
"eventID" => $eventID
));
}else{
//Event Insert failed - handle appropriately here
}

Related

PHP PDO INSERT INTO not inserting

I have a problem while inserting datas in MySQL database with PDO.
I have no error, it just seems to didn't have inserted datas in the table when I select them after execute the code with MySQL in terminal.
I've tried solutions in answers on stackoverflow, like wraping name and description in backticks, but it's still not working
Here is my sql columns :
Here is the code :
$query = $pdo->prepare("INSERT INTO cities (`name`, departement, province, lat, long, `description`, poi_id) VALUES(`:name`, :departement, :province, :lat, :long, `:description`, :poi_id)");
$query = $query->execute([
"name" => $name,
"departement" => $code_dpt,
"province" => (int)$provinces[$departements[$code_dpt]],
"lat" => $lat,
"long" => $long,
"description" => $description,
"poi_id" => (int)$poi_id
]);
$query = $pdo->prepare("INSERT INTO cities (`name`, departement, province, lat, long, `description`, poi_id) VALUES(:name, :departement, :province, :lat, :long, :description, :poi_id)");
$query->execute([
':name' => $name,
':departement' => $code_dpt,
':province' => (int)$provinces[$departements[$code_dpt]],
':lat' => $lat,
':long' => $long,
':description' => $description,
':poi_id' => (int)$poi_id
]);
use placeholder in execute function.
I've found the solution.
First, I've enabled errors like this :
$pdo = new PDO('mysql:host=localhost;dbname=bpfmgr', 'root', '', array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
I was using a property named long for longitude, but it's a MySQL reserved keyword, so it mades errors. I've added backticks to wrap long and that's working.

Row name based on column ID in mysql

I have a little problem. I'm very new to mysql and I'm creating some sort of basic database of cats. I'm adding 100 positions to database through that code:
$result_set = $pdo->prepare("INSERT INTO koty2 (name, age, breed, author, tag, image) VALUES (:name, :age, :breed, :author, :tag, :image)");
$result_set->execute(array(
':name' => $name,
':age' => $age,
':breed' => $breed,
':author' => $author,
':tag' => $tag,
':image' => $image
));
for ($i=0; $i<100; $i++) {
$result_set->execute(array(
':name' => $name,
':age' => $age,
':breed' => $breed,
':author' => $author,
':tag' => $tag,
':image' => $image
));
I tried multiple ways of adding the $name to the database with row's ID which is auto incremented - so it would be "Name+ID". So far I failed. Can somebody tell me how to do this?
Thank you.
One work around is, you can first insert the data you want to insert, get the last inserted ID, then just update the name by concatenating the name and ID. See below code:
// insert first
$result_set = $pdo->prepare("INSERT INTO koty2 (name, age, breed, author, tag, image) VALUES (:name, :age, :breed, :author, :tag, :image)");
$result_set->execute(array(
':name' => $name,
':age' => $age,
':breed' => $breed,
':author' => $author,
':tag' => $tag,
':image' => $image
));
// get the inserted ID
$last_ins_id = $pdo->lastInsertId();
// update the inserted name
$update_row = $pdo->prepare("UPDATE koty2 SET name = :name WHERE ID = :id");
$update_row->execute(array(
':name' => $name . $last_ins_id,
':id' => $last_ins_id
));
Im not sure if this is the best solution but this logic will still do the work
If you want to get the inserted auto-incremented ID everytime you insert a new Cat( xD ), you can use:
$pdo->lastInsertId();
http://php.net/manual/en/pdo.lastinsertid.php
This will echo the whole column "$Name $CatID" do what you want:
$stmt = $pdo->query("SELECT name, catID FROM koty2");
while ($row = $stmt->fetch(PDO::FETCH_NUM)) {
print "Name: <p>{$row[0] $row[1]}</p>";
}
For more, check:
http://php.net/manual/en/pdostatement.fetch.php

adding multiple rows in mysql table based on an array

I have a form which allows people to message each other, a user can select multiple people to message, when i submit a form it gives me the name and id of people selected to message in an array. uptil here i am able to get it to work for a single recipient
I want to be able to use this array and INSERT message for each user in different rows of mysql table
this is the array that i get when i submit a form
Array (
[to_user_id] => Array
(
[0] => 54
[1] => 55
)
[subject] => aaa
[message] => bbb
[send_message] =>
this is the part of code that works for a single recipient but not multiple
$to_user_id_array = ($_POST['to_user_id']);
$params = array(
':to_user_id' => $to_user_id_array,
':subject' => $_POST['subject'],
':message' => $_POST['message'],
':sender_id' => $this->user_id,
':status' => "0",
':type' => "message",
':sender_name' => $sender_name,
':to_user_name' => $to_user_name,
':delete_received' => 'no',
':delete_sent' => 'no',
);
$sql = "INSERT INTO `messages` (`sender_id`,`subject`,`comment`,`to_user_id`,`status`,`type`,`sender_name`,`to_user_name`,`delete_received`,`delete_sent`)
VALUES (:sender_id, :subject, :message, :to_user_id, :status, :type, :sender_name,:to_user_name,:delete_received,:delete_sent);";
parent::query($sql, $params);
$this->error = "<div class='alert alert-success'>" . _('Your message has been sent.') . "</div>";
Will really appreciate any help..
This is what worked for me, i hope this helps someone else in similar position
while ($value = $stmt->fetch(PDO::FETCH_ASSOC)) {
$params = array(
':to_user_id' => $value['user_id'],
':subject' => $_POST['subject'],
':message' => $_POST['message'],
':sender_id' => $this->user_id,
':status' => "0",
':type' => "message",
':sender_name' => $sender_name,
':to_user_name' => $value['name'],
':delete_received' => 'no',
':delete_sent' => 'no',
);
$sql = "INSERT INTO `messages` (`sender_id`,`subject`,`comment`,`to_user_id`,`status`,`type`,`sender_name`,`to_user_name`,`delete_received`,`delete_sent`)
VALUES (:sender_id, :subject, :message, :to_user_id, :status, :type, :sender_name,:to_user_name,:delete_received,:delete_sent);";
parent::query($sql, $params);
}

One PHP Script with two PDO queries?

I've recently starting using PDO in a rebuild of a client's taxi booking system.
I have a script called create_booking.php, which initially inserts the booking details into a bookings table in the MySQL database. After inserting the customers details it retrieves the lastinsertID to get the booking ref. It then creates a job in the jobs table and references the booking reference to relate the job/booking.
The first insert is working fine, but the second insert isn't . Any ideas?
if (isset($_POST['customer_title'])) {
include('../assets/db_connection.php');
$create_booking = $db->prepare("INSERT INTO bookings(customer_name, billing_address, contact_tel, contact_mob, contact_email, party_pax, party_cases, booking_notes, price, booking_agent, booking_date, booking_status, authorised)
VALUES(:customer_name, :billing_address, :contact_tel, :contact_mob, :contact_email, :party_pax, :party_cases, :booking_notes, :price, :booking_agent, :booking_date, :booking_status, :authorised );");
$create_booking->execute(array(
":customer_name" => $customer_title . ' ' . $customer_first_name . ' ' . $customer_last_name,
":billing_address" => $billing_address,
":contact_tel" => $customer_tel,
":contact_mob" => $customer_mobile,
":contact_email" => $customer_email,
":party_pax" => $passengers,
":party_cases" => $cases,
":booking_notes" => $booking_notes,
":price" => $price,
":booking_agent" => $booking_agent,
":booking_date" => $booking_date,
":booking_status" => $booking_status,
":authorised" => $authorised
));
$booking_ref = $db->lastInsertId('booking_ref'); // Takes Booking Ref generated in $create_booking
$create_job = $db->prepare("INSERT INTO jobs(booking_ref, pickup_date, pickup_time, pickup_address, destination_address, return, scheduled)
(:booking_ref, :pickup_date, :pickup_time, :pickup_address, :destination_address, :return, :scheduled )");
$create_job->execute(array(
":booking_ref" => $booking_ref,
":pickup_date" => $pickup_date,
":pickup_time" => $pickup_time,
":pickup_address" => $pickup_address,
":destination_address" => $pickup_destination,
":return" => "N",
":scheduled" => "N"
));
}
Your second SQL query is missing VALUES.
INSERT INTO() ... VALUES()
$create_job = $db->prepare("INSERT INTO jobs(booking_ref, pickup_date, pickup_time, pickup_address, destination_address, return, scheduled)
VALUES (:booking_ref, :pickup_date, :pickup_time, :pickup_address, :destination_address, :return, :scheduled )");

phpmyadmin and mysql pdo lastInsertId()

i have this
$query = "INSERT INTO players VALUES (
UUID(),
:firstname,
:lastname,
:age,
:birthplace,
:height,
:weight,
:bats,
:throws,
:position,
:jersey,
:status,
:team,
:image_path
)";
$sth = $db->prepare($query);
$sth->execute(array(
':firstname' => $firstname,
':lastname' => $lastname,
':age' => $age,
':birthplace' => $birthplace,
':height' => $height,
':weight' => $weight,
':bats' => $bats,
':throws' => $throws,
':position' => $position,
':jersey' => $jersey,
':status' => $status,
':team' => $team,
':image_path' => $image_path
));
$id = $db->lastInsertId();
return $id;
and i'm trying to return the last ID that was inserted, and all i'm getting is a 0 returned.
any help is greatly appreciated
thanks
LAST_INSERT_ID() and friends will work only for integer IDs that are created via an AUTO_INCREMENT column. You need to run two queries - first
SELECT UUID() AS newuuid;
then fetch and store this result (e.g. in $uuid), then
"INSERT INTO players VALUES (
:uuid,
:firstname,
:lastname,
...
execute(array(
':uuid' => $uuid,
':firstname' => $firstname,
':lastname' => $lastname,
':age' => $age,
leaving you with the $uuid still valid.

Categories