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 )");
Related
Here is the return of AJAX, which display what value I am trying to store into database:
Here is what is really stored into database (58.00 is what I stored):
Here is the structure of table:
Here is the PHP:
$req = $bdd->prepare("INSERT INTO salon_histo(reference, designation, colour, size, type, price, qty, payment, date) VALUES(:reference, :designation, :colour, :size, :type, :price, :qty, :payment, NOW())");
$req->execute(array(
'reference' => $_POST['reference'],
'designation' => $_POST['designation'],
'colour' => $_POST['colour'],
'size' => $_POST['size'],
'type' => $_POST['type'],
'price' => floatval($price[0]),
'qty' => $_POST['soldQty'],
'payment' => $_POST['payment']
));
$req->closeCursor();
echo json_encode($price[0]);
How can MySQL store a data with 2 decimals at 0 when I am trying to store 58,33? I tried in PHP to use floatval and indeed the number becomes 58.
Price appears to be an array:
'price' => floatval($price[0]),
Possibly the decimal part has key 1?
'price' => (float) ($price[0] . '.' . $price[1]),
If that doesn't work, please var_dump($price) and paste me the result.
The other thing to check is wether PHP is formatting those numbers with a comma or not.
In PHP I'm attempting to build a form that needs to check for an ID in one table and if it exists it should create a record in another table. So far, that works but the issue I'm having is when I attempt to handle the case if the ID I checked for didn't exist. If it doesn't exist I'd like to create another one. But every time I try it, I get 500 errors from the server when I fetch the results.
Essentially I made the following function
function trySQL($con, $query, $params) {
$stmt = $con->prepare($query);
$result = $stmt->execute($params);
$id = $stmt->insert_id;
return array($stmt,$result,$id);
}
I call this function multiple times through out my php code but when I call it more then once and attempt to fetch the results it breaks.
$custINSquery = "
INSERT INTO custs (
FirstName,
LastName,
EmailAddress,
PhoneNumber
) VALUES (
:FirstName,
:LastName,
:EmailAddress,
:PhoneNumber
)
";
$createJob = "
INSERT INTO jobs (
custs_id,
StAddress,
State,
ZipCode,
MoistureLocation,
status_id
) VALUES (
:custs_id,
:StAddress,
:State,
:ZipCode,
:IssueDesc,
:status_id
)
";
$custSELquery = "SELECT id, FirstName, LastName, EmailAddress FROM custs WHERE FirstName = :FirstName AND LastName = :LastName AND EmailAddress = :EmailAddress";
$custSELquery_params = array(
':FirstName' => $_POST['FirstName'],
':LastName' => $_POST['LastName'],
':EmailAddress' => $_POST['EmailAddress']
);
$checkcust = trySQL($db, $custSELquery, $custSELquery_params);
$row = $checkcust[0]->fetch();
if(!$row){
$custINSquery_params = array(
':FirstName' => $_POST['FirstName'],
':LastName' => $_POST['LastName'],
':EmailAddress' => $_POST['EmailAddress'],
':PhoneNumber' => $_POST['PhoneNumber']
);
$custins = trySQL($db, $custINSquery, $custINSquery_params);
$custsel = trySQL($db, $custSELquery, $custSELquery_params);
$custs_id = $custsel[0]->fetch();
if ($custs_id != null) {
$createJobParam = array(
':custs_id' => $custs_id,
':StAddress' => $_POST['StAddress'],
':State' => $_POST['State'],
':ZipCode' => $_POST['ZipCode'],
':IssueDesc' => $_POST['MoistureLocation'],
':status_id' => $_POST['status_id']
);
$jobins = trySQL($db, $createJob, $createJobParam);
$jobres = $jobins[0]->fetch();
die("um...");
if ($jobres) {
# code...
die("looks like I made it");
}
}
} else {
$createJobParam = array(
':custs_id' => $row['id'],
':StAddress' => $_POST['StAddress'],
':State' => $_POST['State'],
':ZipCode' => $_POST['ZipCode'],
':IssueDesc' => $_POST['MoistureLocation'],
':status_id' => $_POST['status_id']
);
$data['success'] = true;
$data['message'] = 'Success!';
}
Additional Notes: When I look through the php doc's they are saying that I could use the inserted_id thing in order to get the ID that I inserted previously but when I try that it just gives me nulls with this set up.
Any help would be appreciated.
Thanks!
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
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
}
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);
}