MySQL Single Insert Multiple Rows fom post data array - php

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

Related

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.

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.

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

Error in getting the last inserted ID of a query using batch insert in CodeIgniter

How can I get the last inserted ID of a query using the batch insert in CodeIgniter. I used the code $this->db->insert_id() but it returns the ID of my first inserted array. I can't get the last insert.
Here's what I did:
for ($x = 0; $x < sizeof($filtername); $x++) {
$orders[] = array(
'poid' => null,
'order_id' => $poid,
'item_desc' => $filtername[$x],
'item_qty' => $filterquantity[$x],
'item_price' => $filterprice[$x],
'total' => $filtertotal[$x],
'cash_on_delivery' => $val_delivery,
'is_check' => $val_check,
'bank_transfer' => $val_transfer,
'transaction_date' => $dateorder
);
}
$this->db->insert_batch('po_order', $orders);
echo $this->db->insert_id(); //will return the first insert array
I can't spot where's my error. My last option is to get it using a query. I also did mysql_insert_id() but always returns to 0.
I think the best way would be to use the batch insert instead of individual inserts in a loop for performance , but to get the last insert id, ADD the First Insert ID & the Affected Rows.
$this->db->insert_batch('po_order', $orders);
$total_affected_rows = $this->db->affected_rows();
$first_insert_id = $this->db->insert_id();
$last_id = ($first_insert_id + $total_affected_rows - 1);
You will need to do something like this,
$insertIds = array();
for ($x = 0; $x < sizeof($filtername); $x++) {
$orders = array(
'poid' => null,
'order_id' => $poid,
'item_desc' => $filtername[$x],
'item_qty' => $filterquantity[$x],
'item_price' => $filterprice[$x],
'total' => $filtertotal[$x],
'cash_on_delivery' => $val_delivery,
'is_check' => $val_check,
'bank_transfer' => $val_transfer,
'transaction_date' => $dateorder
);
$this->db->insert('po_order', $orders);
$insertIds[$x] = $this->db->insert_id(); //will return the first insert array
}
print_r($insertIds); //print all insert ids

Categories