adding multiple rows in mysql table based on an array - php

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);
}

Related

Datastax PHP Cassandra, getting "No Value or Column for name" error

Cassandra\Exception\InvalidArgumentException: No value or column for name
I'm trying to update some old code from YACassandraPDO to Datastax's new PHP extension, and I'm running into some issues. Notably, this error. I can't figure out why or what's wrong.
A parameter numbers match. Is there something drastically different Datastax is doing for prepared statements?
$query = "UPDATE {$this->keyspace}.visit USING TTL {$this->ttl}
SET ip=:ip, browser=:browser, referrer=:ref, terms=:terms
, url=:url, stime=:stime, etime=:etime
, company=:company, isp=:isp, domain=:domain, client_type = :client_type
, city=:city, state=:state_cd, postal_cd=:postal, country=:country
, country_cd=:country_cd, latitude=:lat, longitude=:long, area_cd=:area_cd
, user_id=:user_id
WHERE visit_dt=:dt AND cid=:cid AND sid=:sid AND pvid=:pvid";
The array is:
$params = [
':dt' => new Timestamp(strtotime(date('Y-m-d')), 0),
':cid' => $data['customerId'],
':sid' => $data['sid'],
':pvid' => $data['pvid'],
// Columns
':ip' => $ip,
':browser' => utf8_encode($data['browser']),
':client_type' => utf8_encode($device),
':ref' => utf8_encode($data['referrer']),
':terms' => utf8_encode($terms),
':url' => utf8_encode($data['url']),
':stime' => $data['now'],
':etime' => $data['etime'],
':user_id' => $data['userid'],
// Geodecode information
':company' => utf8_encode($geo->isp),
':domain' => utf8_encode($geo->domainName),
':isp' => utf8_encode($geo->isp),
':city' => utf8_encode($geo->cityName),
':state_cd' => utf8_encode($geo->regionName),
':country' => utf8_encode($geo->countryName),
':country_cd' => utf8_encode($geo->countryCode),
':postal' => $geo->zipCode,
':lat' => floatval($geo->latitude),
':long' => floatval($geo->longitude),
':area_cd' => $areac
];
Execution:
$prep = $this->adapter()->prepare($stmnt);
$return = $this->adapter()->execute($prep, ['arguments' => $params]);
Okay, I've discovered the issue: the colens. ':key' needs to be just 'key'.
Man, that took just too long to see. All my old bind names were $stmnt->bindValue(':company', [...]);; so, it completely escaped my view.

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY093]: Invalid parameter

I have a table (q) have 30 colmns, I wrote it in code correct, but I don't know where it's wrong.
Here I check wrongs:
$formErrors = array();
if(empty($fullname)){$formErrors[] = '<div class="alert alert-danger" > هناك خطأ ما<strong> الاسم</strong></div>'; }
if(empty($email)){$formErrors[] = '<div class="alert alert-danger" >هناك خطأ ما <strong>الايميل</strong></div>'; }
//loop errors
foreach($formErrors as $error){redirecthome("$error");}
// check if not errors procces update
if(empty($formErrors)){
here the wrong code sql ..
$stmt = $con->prepare("INSERT INTO `u926512753_u`.`q` (`username`, `email`, `skill`, `info`, `q1`, `q2`, `q3`, `q4`, `q5`, `q6`, `q7`, `q8`, `q9`, `q10`, `q11`, `q12`, `q13`, `q14`, `q15`, `q16`, `q17`, `q18`, `q19`, `q20`, `q21`, `q22`, `q23`, `q24`, `q25`, `q26`) VALUES (:username, :email, :skill, :info, :q1, :q2, :q3, :q4, :q5, :q6, :q7, :q8, :q9, :q10, :q11, :q12, :q13, :q14, :q15, :q16, :q17, :q18, :q19, :q20, :q21, :q22, :q23, :q24, :q25, ':q26'); ");
$stmt->execute(array(':username' => $fullname, ':email' => $email, ':skill' => $skill, ':info' => $info, ':q1' => $q1, ':q2' => $q2, ':q3' => $q3, ':q4' => $q4, ':q5' => $q5, ':q6' => $q6, ':q7' => $q7, ':q8' => $q8, ':q9' => $q9, ':q10' => $q10, ':q11' => $q11, ':q12' => $q12, ':q13' => $q13, ':q14' => $q14, ':q15' => $q15, ':q16' => $q16, ':q17' => $q17, ':q18' => $q18, ':q19' => $q19, ':q20' => $q20, ':q21' => $q21, ':q22' => $q22, ':q23' => $q23, ':q24' => $q24, ':q25' => $q25, ':q26' => $q26 ));
Like said in a comment above. There is a syntax error due to a quote placed in the VALUES part.
:q25, ':q26'); "); should become :q25, :q26'); ");.

I am trying to save the record in PDO, it does not shows any error and query execute sucessfully, But my record does not save

I am trying to save the record, but when I run this code it execute without any error, but in database it does not show my record inserted.....
This is my Code for saving the records:-
$qre = $conn->prepare("INSERT INTO student_master (`StudentId`, `AddmissionNo`, `AddmissionDate`, `AddmissionYear`, `AddmissionClass`, `StudentCode`, `RegistrationNo`, `EnquiryNo`, `StudentName`, `FatherName`, `MotherName`, `Address`, `City`, `State`, `ClassId`, `SectionId`, `GroupId`, `ClassRollNo`, `Gender`, `BloodGroup`, `DOB`, `DateOfJoining`, `GameId`, `PersonIdMark`, `Caste`, `Religion`, `ConcessionId`, `BoardAddmissionNoIXAndX`, `BoardAddmissionNoXIAndXII`, `BoardRollNoIXAndX`, `BoardRollNoXIAndXII`, `Nationality`, `FatherProfessionId`, `FatherDeptId`, `FatherDesgId`, `FatherBussiness`, `FatherWorkSpace`, `FatherAnnualIncome`, `MotherProfessionId`, `MotherDeptId`, `MotherDesgId`, `MotherBussiness`, `MotherWorkSpace`, `MotherAnnualIncome`, `ResidentPhone`, `FatherCellNo`, `MotherCellNo`, `FatherEmail`, `MotherEmail`, `EmergencyPhone`, `EmergencyCellNo`, `EmergencyContactPerson`, `EmergencyContactRelation`, `BusRateId`, `RouteNo`, `Height`, `Weight`, `VisionLeft`, `VisionRight`, `Teeth`, `OralHygine`, `BrotherSisterDetail`, `SiblingId`, `SessionId`) VALUES (:StudentId, :addmission_no, STR_TO_DATE(:ad_date', '%m/%d/%Y'), :addmission_yr, :addmission_cls, :student_code, :registration_no, :enquiry_no, :student_name, :father_name, :mother_name, :address, :city, :state, :class, :section, :group, :rollno, :gender, :bloodgroup, STR_TO_DATE(:dob', '%m/%d/%Y'), STR_TO_DATE(:doj', '%m/%d/%Y'), :game, :pidmark, :caste, :religion, :concession_cat, :board_addmission_noIX_X, :board_addmission_noXI_XII, :board_roll_noIX_X, :board_roll_noXI_XII, :nationality, :father_prof, :father_dept, :father_desg, :father_bussiness, :father_workplace, :father_annual_income, :mother_prof, :mother_dept, :mother_desg, :mother_bussiness, :mother_workplace, :mother_annual_income, :resident_phone, :father_cell, :mother_cell, :father_email, :mother_email, :emergency_phone, :emergency_cell, :contact_person_emergency, :emergency_contact_relation, :bus_rate, :route_no, :height, :weight, :vision_left, :vision_right, :teeth, :oral_hygiene, :brother_sister_detail,:sibling_id, :session_id)");
$res = $qre->execute(array(
':StudentId' => $StudentId,
':addmission_no' => $addmission_no,
':ad_date' => $addmission_date,
':addmission_yr' => $addmission_yr,
':addmission_cls' => $addmission_cls,
':student_code' => $student_code,
':registration_no' => $registration_no,
':enquiry_no' => $enquiry_no,
':student_name' => $student_name,
':father_name' => $father_name,
':mother_name' => $mother_name,
':address' => $address,
':city' => $city,
':state' => $state,
':class' => $class,
':section' => $section,
':group' => $group,
':rollno' => $rollno,
':gender' => $gender,
':bloodgroup' => $bloodgroup,
':dob' => $dob,
':doj' => $doj,
':game' => $game,
':pidmark' => $pidmark,
':caste' => $caste,
':religion' => $religion,
':concession_cat' => $concession_cat,
':board_addmission_noIX_X' => $board_addmission_noIX_X,
':board_addmission_noXI_XII' => $board_addmission_noXI_XII,
':board_roll_noIX_X' => $board_roll_noIX_X,
':board_roll_noXI_XII' => $board_roll_noXI_XII,
':nationality' => $nationality,
':father_prof' => $father_prof,
':father_dept' => $father_dept,
':father_desg' => $father_desg,
':father_bussiness' => $father_bussiness,
':father_workplace' => $father_workplace,
':father_annual_income' => $father_annual_income,
':mother_prof' => $mother_prof,
':mother_dept' => $mother_dept,
':mother_desg' => $mother_desg,
':mother_bussiness' => $mother_bussiness,
':mother_workplace' => $mother_workplace,
':mother_annual_income' => $mother_annual_income,
':resident_phone' => $resident_phone,
':father_cell' => $father_cell,
':mother_cell' => $mother_cell,
':father_email' => $father_email,
':mother_email' => $mother_email,
':emergency_phone' => $emergency_phone,
':emergency_cell' => $emergency_cell,
':contact_person_emergency' => $contact_person_emergency,
':emergency_contact_relation' => $emergency_contact_relation,
':bus_rate' => $bus_rate,
':route_no' => $route_no,
':height' => $height,
':weight' => $weight,
':vision_left' => $vision_left,
':vision_right' => $vision_right,
':teeth' => $teeth,
':oral_hygiene' => $oral_hygiene,
':brother_sister_detail' => $brother_sister_detail,
':sibling_id' => $sibling_id,
':session_id' => $session_id
));
var_dump($qre->errorInfo());
var_dump($qre->errorCode());
Thanks in advance........

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 )");

Trouble with PDO update

I am updating a form using PDO's update function. For some reason it is not going through.
Here is code:
$data = "UPDATE insuranceverificationdisclaimer SET InsCoName =:insur, PhoneNumber = :phone, Policy = :policy, InsuredName = :insurname
, MailingAdrs = :mailingad, EffDate = :effdate, ExpDate = :expdate, Email1 = :email, YrVehicle = :yr, Make = :make
, Model = :model, VIN = :vin, TraineeUserName = :user, EmpName = :empname, EmpCoName = :empcomp, AgencyNumber = :agnum
, SignDate = :signdate, AgentName = :agname, AgentPhone = :agphone, AgentEmail = :agemail, Combinedlimit = :csl, bodyinjur = :body
, bodyinjureachacc = :acc
, propertydmg = :prop WHERE TraineeUsername = :user";
echo"1";
$insertdata = $DBH->prepare($data);
$insertdata->execute(array(':insur' => $compname, ':phone' => $phone , ':policy' => $policynum, ':insurname' => $nameofPolicyholder
, ':mailingad' => $newMailingAdrs, ':effdate' => $Policyeffdate, ':expdate' => $Policyexpdate, ':email' => $newEmployeeEmail
, ':yr' => $YearOfVehicle, ':make' => $MakeOfVehicle, ':model' => $ModelOfVehicle, ':vin' => $Vehicleid, ':user' => $username, ':empname' => $EmployeeName, ':empcomp' => $EmployeeCompanyName, ':agnum' => $Agencynum
, ':signdate' => $TodaysDate, ':agname' => $agentname, ':agphone' => $agentphone, ':agemail' => $agentemail, ':csl' => $singlelimit
, ':body' => $bodyinjur, ':acc' => $eachacc, ':prop' => $propertydmg ));
Where , ':csl' => $singlelimit, ':body' => $bodyinjur, ':acc' => $eachacc, ':prop' => $propertydmg begins this is the function that is not working, these are ints in the database and the values are ints. If I remove from the select and the array it will work but besides that it will not.
Let me know if you need anything else!
UDATED---------------------------
Wont go through once you hit execute page just stays white.
You should turn on your error reporting as suggested by Michael Berkowski. For now I can only assume that the error is cause by params datatypes not being defined. You can try the following:
$insertdata->bindParam(':insur', $compname, PDO::PARAM_STR);
$insertdata->bindParam(':csl', $singlelimit, PDO::PARAM_INT);
//...bind the other params
$insertdata->execute();

Categories