PDO insert array is only showing one entry - php

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.

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

How to use multiple array in foreach

Array
(
[0] => Array
(
[emp_name] =>
[emp_title] => Senior Developer
[emp_master_id] => 0
[emp_designation] => TL
[emp_skills] => PHP, MySQL
[emp_experience] => 4-5
[emp_location] => Chennai
)
[1] => Array
(
[emp_name] =>
[emp_title] => Web Developer
[emp_master_id] => 0
[emp_designation] => Senior Developer
[emp_skills] => 10Base-T Switching, PHP
[emp_experience] => 4-5
[emp_location] => Chennai
)
)
I want Insert the array In Db by using Foreach.. Any Suggestions
let say your array name is $data
foreach($data as $key => $value){
$sql="Insert into table_name (empname,..... )values('".$value['empname']."',....);";
$result=$conn->query($sql);
}
This should do the work, Assuming that you have connection variable something like
$conn = new mysqli($servername, $username, $password, $dbname);
Give the column name as in your table in the sql query.
EDIT
The secure way of doing it
foreach($data as $key => $value){
// prepare and bind
$stmt = $conn->prepare("INSERT INTO table_name(emp_name, title, ...) VALUES (?, ?, ..)");//No of question marks are equal to columns you have mentioed
$stmt->bind_param("sss", $empName, $title, ...);
// i - integer
// d - double
// s - string
// b - BLOB
// set parameters and execute
$empName= $value['empname'];
$title= $value['title'];
//continue to do it for all...
$stmt->execute();
$stmt->close();
}
$conn->close();
NOTE: You can use function also if you know how to do it, less code inside the foreach
Happy coding :)
foreach($arr as $v){
$sql = ') VALUES (';
foreach($v as $k => $value){
$sql = ",".$k.$sql.'"'.$value.'",';
}
$sql = 'Insert into table_name ('.trim($sql,',').';';
$result=$conn->query($sql);
}
this maybe working.

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

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
}

MySQL Single Insert Multiple Rows fom post data array

I have search but dont see any answer or example that fits mine code. I am pretty new to MySQL/PHP, so I might not understand the answers I have looked at.
I have a web page that posts data over that I want to use just one insert. This is what I have so far for the insert:
$statement1 = $link->prepare("INSERT INTO collection_items(collection_list_id, collection_item_number, username_id, collection_item_title, collection_item_text, created_date)
VALUES(:collection_list_id, :collection_item_number, :username_id, :collection_item_title, :collection_item_text, now())");
$statement1->execute(array(
"collection_list_id" => $last_id,
"collection_item_number" => "1",
"username_id" => $user_number,
"collection_item_title" => $collection_item_title_1,
"collection_item_text" => $collection_item_text_1
),
(
"collection_list_id" => $last_id,
"collection_item_number" => "2",
"username_id" => $user_number,
"collection_item_title" => $collection_item_title_2,
"collection_item_text" => $collection_item_text_2
));
If I drop the last set of data it works just fine for one row. I have about 20 twenty rows of data from the page post.
TIA
This is what I have, but can't get it to work. I'v shown more code to help.
$form = $_POST;
$collection_item_title_1 = $form[ 'number1' ];
$collection_item_text_1 = $form[ 'comment1' ];
$collection_item_title_2 = $form[ 'number2' ];
$collection_item_text_2 = $form[ 'comment2' ];
$last_id = $link->lastInsertId();
$q= $link->query("SELECT id FROM sitelok WHERE Username='$slusername'");
$user_number = $q->fetchColumn();
$collection_item_titles = array($collection_item_title_1, $collection_item_text_1, $collection_item_title_2, $collection_item_text_2);
$statement1 = $link->prepare("INSERT INTO collection_items(collection_list_id, collection_item_number, username_id, collection_item_title, collection_item_text, created_date)
VALUES(:collection_list_id, :collection_item_number, :username_id, :collection_item_title, :collection_item_text, now())");
for ($i = 0; $i < size($collection_item_titles); $i++)
$statement1->execute(array(
"collection_list_id" => $last_id,
"collection_item_number" => "$i",
"username_id" => $user_number,
"collection_item_title" => $collection_item_title[$i],
"collection_item_text" => $collection_item_text[$i]
));
You could create an array and loop through the data and instead of having your data in separate variables ($collection_item_title_1, $collection_item_title_2) you could do something such as $collection_item_titles[] then loop through as such:
statement1 = $link->prepare("INSERT INTO collection_items(collection_list_id, collection_item_number, username_id, collection_item_title, collection_item_text, created_date)
VALUES(:collection_list_id, :collection_item_number, :username_id, :collection_item_title, :collection_item_text, now())");
for ($i = 0; $i < size($collection_item_titles); $i++)
$statement1->execute(array(
"collection_list_id" => $last_id,
"collection_item_number" => "$i",
"username_id" => $user_number,
"collection_item_title" => $collection_item_title[$i],
"collection_item_text" => $collection_item_text[$i]
);
You can't pass more then 1 argument to execute
You can either insert values in a foreach loop or create a query with hundreds of placeholders.
I think first way is better, for example:
$values = array(); // your inserted values array here
$statement1 = $link->prepare("INSERT INTO collection_items(collection_list_id, collection_item_number, username_id, collection_item_title, collection_item_text, created_date) VALUES(:collection_list_id, :collection_item_number, :username_id, :collection_item_title, :collection_item_text, now())");
foreach ($values as $v) {
$statement1->execute($v);
}

Categories