Zend db insertion exception - php

Please some body help me verified many times but i couldn't find where i did a mistake
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '' for key 'Index_6'
This is my code:
$first_name = $_POST ['firstName'];
$middle_name = $_POST ['middleName'];
$last_name = $_POST ['lastName'];
$office_ph_no = $_POST ['officePhoneNumber'];
$cell_ph_no = $_POST ['cellPhoneNumber'];
$email = $_POST ['emailId'];
$supervisor_name = $_POST ['supervisorName'];
$supervisor_email = $_POST ['supervisorEmail'];
$supervisor_ph = $_POST ['supervisorPhone'];
$pass = $_POST ['password'];
$sql = $db->query ( "INSERT INTO user( user_id, title, first_name, last_name, user_identity_id, email_id, password, office_phone_number, public_id, session_id, address_id, created_by, last_modified_by, created_on, last_modified_on, is_activated, is_deprecated, middle_name, cell_phone_number, superviser_name, superviser_email, superviser_phone_number)
VALUES ( :p_user_id, :p_title, :p_first_name, :p_last_name, :p_user_identity_id, :p_email_id, :p_password, :p_office_phone_number, :p_public_id, :p_session_id, :p_address_id, :p_created_by, :p_last_modified_by, :p_created_on, :p_last_modified_on, :p_is_activated, :p_is_deprecated, :p_middle_name, :p_cell_phone_number, :p_superviser_name, :p_superviser_email, :p_superviser_phone )",
array (
'p_user_id' => '',
'p_title' => NULL,
'p_first_name' => $first_name,
'p_last_name' => $last_name,
'p_user_identity_id' => 'id',
'p_email_id' => $email,
'p_password' => $pass,
'p_office_phone_number' => $office_ph_no,
'p_public_id' => NULL,
'p_session_id' => NULL,
'p_address_id' => NULL,
'p_created_by' => NULL,
'p_last_modified_by' => NULL,
'p_created_on' => '',
'p_last_modified_on' => '',
'p_is_activated' => '0',
'p_is_deprecated' => '0',
'p_middle_name' => $middle_name,
'p_cell_phone_number' => $cell_ph_no,
'p_superviser_name' => $supervisor_name,
'p_superviser_email' => $supervisor_email,
'p_superviser_phone' => $supervisor_ph
)

In array the name 'p_ is_deprecated' has a blank space.

Related

Sqlite Call to a member function bindParam() on boolean

Hello I try with PDO to insert data to Sqlite, i have tried many ways, but I always get following errors: Call to a member function bindParam() on boolean.
I see also the bindParam() or bindValue return false if an error exist. But I don't find an error.
thx in advance
function insertCostumers(){
$costumers = 'INSERT IGNORE INTO costumers(first_name,last_name,age)
VALUES(:first_name,:last_name,:age)';
$stmt = $this->pdo->prepare($costumers);
$data = [['firstName' => 'Hans',
'lastName' => 'Meier',
'age' => 32],
['firstName' => 'Anna',
'lastName' => 'Mueller',
'age' => 35],
['firstName' => 'Steffi',
'lastName' => 'Gygax',
'age' => 67]];
$stmt->bindParam(
':first_name', $firstName,
':last_name', $lastName,
'age', $age);
foreach ($data as $d) {
// Set values to bound variables
$firstName = $d['firstName'];
$lastName = $d['lastName'];
$age = $d['age'];
// Execute statement
$stmt->execute();
}
die('hello');
}
require "SQLiteConnection.php";
require "SQLiteCreateTable.php";
$sqlite = new SQLiteCreateTable((new SQLiteConnection())->connect());
// create new tables
$sqlite->createTables();
$sqlite->insertCostumers();
$tables = $sqlite->getOrderList();
require "index.view.php";
#SebastianBrosch Thats the Create Statement.
public function createTables() {
$commands = ['CREATE TABLE IF NOT EXISTS costumers (
costumer_id integer PRIMARY KEY,
first_name text NOT NULL,
last_name text NOT NULL,
age integer NOT NULL
)',
'CREATE TABLE IF NOT EXISTS orders (
order_id integer PRIMARY KEY,
order_nr integer NOT NULL,
costumer_id integer,
FOREIGN KEY (costumer_id) REFERENCES costumers (costumer_id)
ON DELETE CASCADE ON UPDATE NO ACTION)'];
// execute the sql commands to create new tables
foreach ($commands as $command) {
$this->pdo->exec($command);
}
}
The variable $stmt is not a PDOStatement object. It is a boolean value (in this case false).
Your INSERT statement is not valid. Try the following instead (missing OR):
$costumers = 'INSERT OR IGNORE INTO costumers(first_name, last_name, age)
VALUES(:first_name, :last_name, :age)';
You can use the methods PDO::errorInfo and PDO::errorCode to get further information.
$costumers = 'INSERT OR IGNORE INTO costumers(first_name,last_name,age)
VALUES(:first_name,:last_name,:age)';
$stmt = $this->pdo->prepare($costumers);
if ($stmt === false) {
echo $this->pdo->errorCode().': '.$this->pdo->errorInfo();
}
You also use $firstName and $lastName before init:
function insertCostumers() {
$costumers = 'INSERT OR IGNORE INTO costumers(first_name, last_name, age)
VALUES(:first_name, :last_name, :age)';
$stmt = $this->pdo->prepare($costumers);
$data = [['firstName' => 'Hans',
'lastName' => 'Meier',
'age' => 32],
['firstName' => 'Anna',
'lastName' => 'Mueller',
'age' => 35],
['firstName' => 'Steffi',
'lastName' => 'Gygax',
'age' => 67]];
foreach ($data as $d) {
$firstName = $d['firstName'];
$lastName = $d['lastName'];
$age = $d['age'];
$stmt->bindParam(':first_name', $firstName, PDO::PARAM_STR);
$stmt->bindParam(':last_name', $lastName, PDO::PARAM_STR);
$stmt->bindParam(':age', $age, PDO::PARAM_INT);
$stmt->execute();
}
}
To make sure the combination of first_name and last_name is unique, you need to add a UNIQUE constraint to your table costumers. Use the following CREATE TABLE statement:
CREATE TABLE IF NOT EXISTS costumers (
costumer_id INTEGER PRIMARY KEY,
first_name TEXT NOT NULL,
last_name TEXT NOT NULL,
age INTEGER NOT NULL,
UNIQUE (first_name, last_name)
);
You can see the difference with and without the UNIQUE constraint on these following demo:
http://sqlfiddle.com/#!7/79b1c/1/1

Weird error when using MySQL when using PDO

I encountered a very strange bug today. I am getting sideblinded by this so bad as it's breaking my entire application.
So, I have this little framework that I've built where I have a standard modell, so snippeting this will be a little long and descriptive.
<?php include('inc/inc.php'); ?>
<?php
if(!empty($_POST['answer']) && !empty($_POST['levelstart'])){
if($stmt = $site->answerQuestion($_POST['levelstart'], $_POST['answer'])){
if($stmt[0]){
echo json_encode(array('success' => true, 'correct' => $stmt[1], 'correctanswer' => $stmt[2], 'round_end' => $stmt[3]));
}else{
echo json_encode(array('success' => false, 'error' => 'error occurred'.$stmt[1]));
}
}else{
echo json_encode(array('sucess' => false, 'error' => 'Unknown error'));
}
}else{
echo json_encode(array('success' => false, 'error' => 'Provide all necessary parameters.'));
}
?>
this piece of code outputs the following.
INSERT INTO quiz_level_starts (`user_id`, `question_id`, `time`, `round_id`, `type`, `success`, `ref_id`) VALUES ('4', '10', '1471887809', '', '1', '1', '905'){"success":false,"error":"error occurred23000"}
The generated query above is only a dummy one that i simple put together so I don't need the parameterization for simply testing. The "error" key in the json array contains error data, and the errorcode is dumped there.
23000 is the mysql error code for there being a duplicate unique column, but there is no unique column that I'm using in the query(see table struct below.)
Since the function answerQuestion is a very long one, I'll only paste the related lines next. In $site->answerQuestion it calls a function called "insertLevelStarts" which is supposed to insert an entry to the db.
This is how i call it:
if($stmtss = $this->db->insertLevelStarts($_SESSION['user']['id'], $stmts['return'][0]['id'], time(), $roundid, 1, 1, $levelstart)){
And this is how it's declared, also the rest of the related and unknown code:
public function insertLevelStarts($user_id, $question_id, $time, $round_id, $type = 0, $success = 0, $refid = 0){
/*
Type=0 start 1 stop
success=0 for start 1 if successfull on stop
*/
$query = 'INSERT INTO quiz_level_starts (`user_id`, `question_id`, `time`, `round_id`, `type`, `success`, `ref_id`) VALUES (:user_id, :question_id, :time, :round_id, :type, :success, :refid)';
echo $this->genFakeQuery($query, array(
':user_id' => $user_id,
':question_id' => $question_id,
':time' => $time,
':type' => $type,
':success' => $success,
':refid' => $refid,
':round_id' => $round_id
));
return $this->execInsert($query, array(
':user_id' => $user_id,
':question_id' => $question_id,
':time' => $time,
':type' => $type,
':success' => $success,
':refid' => $refid,
':round_id' => $round_id
)
);
}
public function genFakeQuery($query, $array){
foreach($array as $key => $val){
$query = str_replace($key, "'$val'", $query);
}
return $query;
}
public function execUpdate($query, $preparray, $updatearr){
try {
$stmt = $this->db->prepare($query);
$stmt->execute(array_merge($preparray, $updatearr));
$rows = $stmt->rowCount();
if($rows > 0){
return array('type' => 'rowsaffected', 'return' => $rows);
}else{
return array('type' => 'noreturn', 'return' => 'none');
}
} catch(PDOException $ex) {
return array('type' => 'error', 'return' => $ex);
}
}
public function updateClause($query, $update, $updatearr){
if(count($update) > 0){
$count = 0;
foreach($update as $k => $v){
if($count > 0){
$query .= ',';
}
$query .= " `$k` = :$k";
$updatearr[":$k"] = $v;
$count++;
}
}
return array('query' => $query, 'updatearr' => $updatearr);
}
The aforementioned query
INSERT INTO quiz_level_starts (`user_id`, `question_id`, `time`, `round_id`, `type`, `success`, `ref_id`) VALUES ('4', '10', '1471887809', '', '1', '1', '905')
inserts into a table looking like this:
CREATE TABLE IF NOT EXISTS `quiz_level_starts` (
`id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`question_id` int(11) NOT NULL,
`time` int(11) NOT NULL,
`type` int(11) NOT NULL,
`success` int(11) NOT NULL,
`ref_id` int(11) NOT NULL,
`round_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `quiz_level_starts`
ADD PRIMARY KEY (`id`);
ALTER TABLE `quiz_level_starts`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
Will greatly appriciate any help recieved.
I assume that the error occurs because round_id is an integer field that can not be NULL and has no default value and you pass it an empty value.
Try if this query works:
INSERT INTO quiz_level_starts (`user_id`, `question_id`, `time`, `round_id`, `type`, `success`, `ref_id`) VALUES ('4', '10', '1471887809', '0', '1', '1', '905')

Running Multiple MySQL Queries in PHP

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!

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

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