Row name based on column ID in mysql - php

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

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.

PDO insert array is only showing one entry

I am try to insert an array into a table with PDO and it is only inserting the first (or last, depending how you look at it) item in the array. Here is my code:
$pdo = new PDO("mysql:charset=utf8mb4;host=$servername;dbname=$dbname", $username, $password);
$sql = "INSERT INTO orderitems
(pid,
name,
style,
weight,
price,
quantity)
VALUES (:pid,
:name,
:style,
:weight,
:price,
:quantity) ";
$stmt= $pdo->prepare($sql);
foreach ($order as $order) {
$stmt->execute(array (
'pid' => $order['id'],
'name' => $order['name'],
'style' => $order['style'],
'weight' => $order['weight'],
'price' => $order['price'],
'quantity' => $order['quantity']
));
}
The problem may be here:
foreach ($order as $order) {
Probably, the first $order variable, as it's naming suggests, is not an array.

PDO how to get auto_increment value from a table

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
}

Insert into mysql with prepared statment - not working

I am using php-login.net projectfiles for a tiny webapp. I just tried to connect to m db and insert some stuff but am keep getting this strange error which i cannot figure out. What am missing in this code
$query = $db->prepare('INSERT INTO cours (category, title, description, places, price) VALUES (:category, :title, :description, :places, :price');
$query->execute(array(':category' => $category, ':title' => $title, ':decription' => $decription, ':places' => $places, ':price' => $price));
You had a typo in description (was decription) also a ) was missing after :price
$query = $db->prepare('INSERT INTO cours (category, title, description, places, price) VALUES (:category, :title, :description, :places, :price)');
$query->execute(array(':category' => $category, ':title' => $title, ':description' => $description, ':places' => $places, ':price' => $price));
Can you try now and tell us if it works?

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