Sqlite Call to a member function bindParam() on boolean - php

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

Related

PDO is inserting "null" for empty values

I am using PDO for writing to sqlite database.
// $dbo is an instance of PDO
$query = "INSERT INTO items (id, name, rank) VALUES (:id, :name, :rank)";
$statement = $dbo->prepare($query);
$values = array('id' => 1, 'name' => 'Some Name', 'rank' => '');
$statement->execute($values);
$values = array('id' => 1, 'name' => 'Some Name', 'rank' => NULL);
$statement->execute($values);
After executing any of these, I expect "rank" to be an empty string or even a NULL is acceptable.
But what I get in the database is 'null', yes a string 'null' value, not the real NULL.
Could not find any solution after several attempts.
Try sending NULL directly in this line
$values = array('id' => 1, 'name' => 'Some Name', 'rank' => NULL);

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.

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!

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

Zend db insertion exception

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.

Categories