I am using PDO to insert records from one table into another.
I'm trying to capture the records that were successfully inserted into the other table, while also capturing the records that might have failed to insert.
<?php
$checkcontainer = $_POST['checkcontainer'];
$checkscac = $_POST['checkscac'];
$comment = $_POST['comment'];
$time = date('Y-m-d H:i:s');
$containerSuccess = array();
$containerFail = array();
$count = count($checkcontainer);
for($i = 0; $i < $count; $i++)
{
$container = $checkcontainer[$i];
$scac = $checkscac[$i];
$insert = $dbc->prepare("INSERT IGNORE INTO trucker_edi_comms (container, scac, fac_comments, fac_datestamp) VALUES (:ucont,:uscac,:ucomm,:utime);");
$insert->execute([
'ucont' => $container,
'uscac' => $scac,
'ucomm' => $comment,
'utime' => $time
]);
if($insert)
{
$containerSuccess = $container;
//echo "containers saved: " . $containerSuccess;
}
else
{
$containerFail = $container;
//echo "containers failed: " . $containerFail;
}
}
echo "containers saved: " . $containerSuccess;
?>
The INSERT statement works. I can also set the $containerSuccess array to $container. If 3 containers are successfully inserted, the output from inside the FOR loop looks like this:
containers saved: TEST123456789containers saved: TEST98642357containers saved: TEST65897531
But I need to be able to echo $containerSuccess outside of the FOR loop. Currently, the output looks like this:
containers saved: TEST65897531
I'm only able to grab the last container that was saved.
I need to echo out all of the containers outside of the FOR loop to display to the user.
How can I make this happen?
Your example was trying to populate a declared array with a string, so you were on the right track concerning the variable type. You can populate an array for outputting the saved/failed containers after the loop completes, and if you want it to output on one line, use implode() for the output:
<?php
$checkcontainer = $_POST['checkcontainer'];
$checkscac = $_POST['checkscac'];
$comment = $_POST['comment'];
$time = date('Y-m-d H:i:s');
$containerSuccess = array();
$containerFail = array();
$count = count($checkcontainer);
for($i = 0; $i < $count; $i++)
{
$container = $checkcontainer[$i];
$scac = $checkscac[$i];
$insert = $dbc->prepare("INSERT IGNORE INTO trucker_edi_comms (container, scac, fac_comments, fac_datestamp) VALUES (:ucont,:uscac,:ucomm,:utime);");
$insert->execute([
'ucont' => $container,
'uscac' => $scac,
'ucomm' => $comment,
'utime' => $time
]);
if($insert)
$containerSuccess[] = $container;
else
$containerFail[] = $container;
}
echo "containers saved: " . implode(', ', $containerSuccess);
echo "containers failed: " . implode(', ', $containerFail);
?>
Related
I have an issue with one of API, where this API will create Order information. Each Order represents 1 buyer with multiple items. I want to loop the items in my API method. But, when I try to loop the function, it only stores the first array value, which is not what I want. I want to store a whole array of values to the Database.
Here is the API Code:
$s = $data->ItemIDs;
if($order->CreateOrderInfo()){
echo 'Order created successfully.';
echo "---";
for($i = 0; $i < sizeof($s); $i++){
$order->ItemCode = $s[$i];
$order->GetItemInfo();
if ($order->ItemCode != null){
$item_array = array(
'UserMememberNo' => $order->UserMememberNo,
'Image' => $order->Image,
'Description' => $order->Description,
'Price' => $order->Price,
'ItemBrand' => $order->ItemBrand,
'ItemModel' => $order->ItemModel
);
//GET DATA FOR ITEM TABLE
$order->ItemGUID = $data->ItemGUID;
$order->ItemName = $order->Description;
$order->ItemPrice = $order->Price;
$order->ItemQuantity = $data->ItemQuantity;
$order->ItemVariation1 = $data->ItemVariation1;
$order->ItemVariation2 = $data->ItemVariation2;
$order->ItemVariation3 = $data->ItemVariation3;
$order->ItemVariation4 = $data->ItemVariation4;
$order->ItemVariation5 = $data->ItemVariation5;
}
else{
echo json_encode('No item Found');
}
if($order->CreateItemInfo())
{
echo 'Item created';
}else{
echo 'Unable to create item';
echo '----';
}
}
if($order->CreateBuyerInfo()){
echo 'Buyer information created';
}else{
echo 'Unable to create buyer information';
}
Here is the model. This model is for inserting the values into the Database:
//CREATE FUNCTION FOR ITEM TABLE
public function CreateItemInfo() {
$sqlQuery = "INSERT INTO ".$this->item_info_table."
SET
GUID = :GUID,
ItemGUID = :ItemGUID,
ItemName = :ItemName,
ItemPrice = :ItemPrice,
ItemQuantity = :ItemQuantity,
ItemVariation1 = :ItemVariation1,
ItemVariation2 = :ItemVariation2,
ItemVariation3 = :ItemVariation3,
ItemVariation4 = :ItemVariation4";
$stmt = $this->conn->prepare($sqlQuery);
$this->GUID = htmlspecialchars(strip_tags($this->GUID));
$this->ItemGUID = htmlspecialchars(strip_tags($this->ItemGUID));
$this->ItemName = htmlspecialchars(strip_tags($this->ItemName));
$this->ItemPrice = htmlspecialchars(strip_tags($this->ItemPrice));
$this->ItemQuantity = htmlspecialchars(strip_tags($this->ItemQuantity));
$this->ItemVariation1 = htmlspecialchars(strip_tags($this->ItemVariation1));
$this->ItemVariation2 = htmlspecialchars(strip_tags($this->ItemVariation2));
$this->ItemVariation3 = htmlspecialchars(strip_tags($this->ItemVariation3));
$this->ItemVariation4 = htmlspecialchars(strip_tags($this->ItemVariation4));
$stmt->bindParam(":GUID", $this->GUID);
$stmt->bindParam(":ItemGUID", $this->ItemGUID);
$stmt->bindParam(":ItemName", $this->ItemName);
$stmt->bindParam(":ItemPrice", $this->ItemPrice);
$stmt->bindParam(":ItemQuantity", $this->ItemQuantity);
$stmt->bindParam(":ItemVariation1", $this->ItemVariation1);
$stmt->bindParam(":ItemVariation2", $this->ItemVariation2);
$stmt->bindParam(":ItemVariation3", $this->ItemVariation3);
$stmt->bindParam(":ItemVariation4", $this->ItemVariation4);
if($stmt->execute()) {
return true;
}
return false;
}
A screenshot below shows the issue, where only the first value of the array is successfully inserted to the Database.
Result of Database Insert
I have the following code that is overwriting my array on the second pass through of the while loop.
Here is my code:
<?php
require '../vendor/autoload.php';
require_once 'constants/constants.php';
use net\authorize\api\contract\v1 as AnetAPI;
use net\authorize\api\controller as AnetController;
require('includes/application_top.php');
define("AUTHORIZENET_LOG_FILE", "phplog");
function getUnsettledTransactionList()
{
//get orders that are in the exp status
$orders_pending_query = tep_db_query("select orders_id as invoice_number from " . TABLE_ORDERS . " where orders_status = '14' order by invoice_number");
$orders_pending = array();
while ($row = mysqli_fetch_array($orders_pending_query, MYSQLI_ASSOC)) {
$orders_pending[] = $row;
}
/* Create a merchantAuthenticationType object with authentication details
retrieved from the constants file */
$merchantAuthentication = new AnetAPI\MerchantAuthenticationType();
$merchantAuthentication->setName(\SampleCodeConstants::MERCHANT_LOGIN_ID);
$merchantAuthentication->setTransactionKey(\SampleCodeConstants::MERCHANT_TRANSACTION_KEY);
// Set the transaction's refId
$refId = 'ref' . time();
$pagenum = 1;
do {
$request = new AnetAPI\GetUnsettledTransactionListRequest();
$request->setMerchantAuthentication($merchantAuthentication);
$paging = new AnetAPI\PagingType;
$paging->setLimit("1000");
$paging->setOffset($pagenum);
$request->setPaging($paging);
$controller = new AnetController\GetUnsettledTransactionListController($request);
$response = $controller->executeWithApiResponse(\net\authorize\api\constants\ANetEnvironment::PRODUCTION);
$transactionArray = array();
$resulttrans = array();
if (($response != null) && ($response->getMessages()->getResultCode() == "Ok")) {
if (null != $response->getTransactions()) {
foreach ($response->getTransactions() as $tx) {
$transactionArray[] = array(
'transaction_id' => $tx->getTransId(),
'invoice_number' => $tx->getInvoiceNumber()
);
// echo "TransactionID: " . $tx->getTransId() . "order ID:" . $tx->getInvoiceNumber() . "Amount:" . $tx->getSettleAmount() . "<br/>";
}
$invoiceNumbers = array_column($orders_pending, "invoice_number");
$result = array_filter($transactionArray, function ($x) use ($invoiceNumbers) {
return in_array($x["invoice_number"], $invoiceNumbers);
});
$resulttrans = array_column($result, "transaction_id");
} else {
echo "No unsettled transactions for the merchant." . "\n";
}
} else {
echo "ERROR : Invalid response\n";
$errorMessages = $response->getMessages()->getMessage();
echo "Response : " . $errorMessages[0]->getCode() . " " . $errorMessages[0]->getText() . "\n";
}
$numResults = (int) $response->getTotalNumInResultSet();
$pagenum++;
print_r($resulttrans);
} while ($numResults === 1000);
return $resulttrans;
}
getUnsettledTransactionList();
?>
the print_r($resulttrans); is actually printing 2 separate arrays, instead of my desired 1 array.
If I move the print_r($resulttrans) to after the while loop, I am only seeing the second array, meaning the first array was overwritten. I am not seeing where this is happening though as to me it seems like all results should be added onto the array.
Your code is supposed to work as you described because you are reassigning the array variable in your loop like this
$resulttrans = array_column($result, "transaction_id");
If you need to get all the resulting values in the same array you need to append it to the array. you can do that by merging the new result into your array variable like this
$resulttrans = array_merge($resulttrans, array_column($result, "transaction_id"));
I have a code that runs a query on an external (slow) API and loops through a lot of variables and inserts data, sends email, ect'.
This is the main function as an example:
// MAIN: Cron Job Function
public function kas_alert() {
// 0. Deletes all the saved data from the `data` table 1 month+ ago.
// $this->kas_model->clean_old_rows();
// 1. Get 'prod' table
$data['table'] = $this->kas_model->prod_table();
// 2. Go through each row -
foreach ( $data['table'] as $row ) {
// 2.2. Gets all vars from the first query.
$last_row_query = $this->kas_model->get_last_row_of_tag($row->tag_id);
$last_row = $last_row_query[0];
$l_aaa_id = $last_row->prod_aaa_id;
$l_and_id = $last_row->prod_bbb_id;
$l_r_aaa = $last_row->dat_data1_aaa;
$l_r_and = $last_row->dat_data1_bbb;
$l_t_aaa = $last_row->dat_data2_aaa;
$l_t_and = $last_row->dat_data2_bbb;
$tagword = $last_row->tag_word;
$tag_id = $last_row->tag_id;
$country = $last_row->kay_country;
$email = $last_row->u_email;
$prod_name = $last_row->prod_name;
// For the Weekly report:
$prod_id = $last_row->prod_id;
$today = date('Y-m-d');
// 2.3. Run the tagword query again for today on each one of the tags and insert to DB.
if ( ($l_aaa_id != 0) || ( !empty($l_aaa_id) ) ) {
$aaa_data_today = $this->get_data1_aaa_by_id_and_kw($l_aaa_id, $tagword, $country);
} else{
$aaa_data_today['data1'] = 0;
$aaa_data_today['data2'] = 0;
$aaa_data_today['data3'] = 0;
}
if ( ($l_and_id != 0) || ( !empty($l_and_id) ) ) {
$bbb_data_today = $this->get_data1_bbb_by_id_and_kw($l_and_id, $tagword, $country);
} else {
$bbb_data_today['data1'] = 0;
$bbb_data_today['data2'] = 0;
$bbb_data_today['data3'] = 0;
}
// 2.4. Insert the new variables to the "data" table.
if ($this->kas_model->insert_new_tag_to_db( $tag_id, $aaa_data_today['data1'], $bbb_data_today['data1'], $aaa_data_today['data2'], $bbb_data_today['data2'], $aaa_data_today['data3'], $bbb_data_today['data3']) ){
}
// Kas Alert Outputs ($SEND is echoed in it's original function)
echo "<h1>prod Name: $prod_id</h1>";
echo "<h2>tag id: $tag_id</h2>";
var_dump($aaa_data_today);
echo "aaa old: ";
echo $l_r_aaa;
echo "<br> aaa new: ";
echo $aaa_data_today['data1'];
var_dump($bbb_data_today);
echo "<br> bbb old: ";
echo $l_r_and;
echo "<br> bbb new: ";
echo $bbb_data_today['data1'];
// 2.5. Check if there is a need to send something
$send = $this->check_if_send($l_aaa_id, $l_and_id, $l_r_aaa, $aaa_data_today['data1'], $l_r_and, $bbb_data_today['data1']);
// 2.6. If there is a trigger, send the email!
if ($send) {
$this->send_mail($l_aaa_id, $l_and_id, $aaa_data_today['data1'], $bbb_data_today['data1'], $l_r_aaa, $l_r_and, $tagword, $email, $prod_name);
}
}
}
This CodeIgniter controller is runs every day and I get this running (Cronjob) for too long using almost nothing from the CPU and RAM (RAM is at 400M/4.25G and CPU at ONLY 0.7%-1.3%).
I wonder if there's an option to split all foreach loops to smaller threads (and I'm not sure if forking will do here) and run all the foreach loops in parallel but in a way that it wont get my server crashing.
I'm no DevOps and really interested learning - What should I do in this case?
I have this code that store a "student" object in $_SESSION:
if(isset($_POST["name"]) && isset($_POST["note"]) && isset($_POST["year"]))
{
$nom = $_POST["name"];
$note = $_POST["note"];
$session = $_POST["year"];
$vec = array("name" => $name, "note" => $note, "year" => $year);
$_SESSION["students"][] = $vec;
echo "The student has been added.<br><br>";
}
Then I have this code in another page:
function calculateAverage()
{
$av = 0;
$count = 0;
foreach($_SESSION['students'] as $student)
{
$av = $av + $student["note"];
$count = $count + 1;
}
return $av / $count;
}
function bestNote()
{
//$best = array_search(max())
return $best;
}
function worstNote()
{
$worst = min(array_search(["note"], $_SESSION['students']));
return $worst;
}
if(isset($_SESSION['students']))
{
echo "The average note of the group is = " . calculateAverage() . "\n";
echo "The one with the best note is " . bestNote()["name"] . " is " . hauteNote()["note"] . " points.\n";
echo "The one with the worst note is " . worstNote()["name"] . " with " . basseNote()["note"] . " points.\n";
}
As you can see, it is not finished. What I want to do is to be able to get the note of a student that is stored in $_SESSION["students"]. How can I do this?
Thanks for answers.
you can access the stored values within a nested array like so:
$studentNote = $_SESSION["students"][YourActiveStudent]["note"];
However, you are currently not adding but overwriting data. Use array_push() to add data to an array (your students).
And when adding a student to the array, make sure to give it a name to make it associative so you can simply "call a student":
$_SESSION["students"][$nom] = $vec;
this way, if the $nom was "Max", you could say
$_SESSION["students"]["Max"]["note"]
to get Max's note (BTW, I assume you are talking about grades or marks, rather than notes?)
In my android app user can upload up to 5 images for an item they have in their collection.
This is what my android app java code is sending over to the PHP server via POST:
[user_id=83,
item_id=24,
item_number_of_photos=1,
item_image_filename_0=http://www.asdqwe.net/item_images/83_image_2014-02-07-16-44-12.jpg,
item_image_description_0=mouse]
This is the PHP Code that handles it:
if (!empty($_POST)) {
$user_id = $_POST["user_id"];
$item_id = $_POST["item_id"];
$item_number_of_photos = $_POST['item_number_of_photos'];
for ($x=0; $x<$item_number_of_photos; $x++) {
if(isset($_POST['item_image_filename_'.$x]) && !empty($_POST['item_image_filename_'.$x])) {
$item_image_filenames[$x] = $_POST['item_image_filename_'.$x];
}
if(isset($_POST['item_image_description_'.$x]) && !empty($_POST['item_image_description_'.$x])) {
$item_image_descriptions[$x] = $_POST['item_image_description_'.$x];
}
}
$query_add_item_photos = "INSERT INTO
product_photos (
product_id,
product_photo,
product_photo_added_by_user,
product_photo_description
)";
////////////////////////////////////////////////////////////
////ADD THE PHOTOS TO THE PHOTOS TABLE//////////////////////
////////////////////////////////////////////////////////////
try {
for($x = 0; $x<$item_number_of_photos; $x++) {
$query_add_item_photos+= " VALUES
(
:product_id,
:product_photo_filename_" . $x .",
:product_photo_added_by_user,
:product_photo_description_" . $x . "
)";
}
$input_parameters = array(
':product_id' => $item_id,
':product_photo_added_by_user' => $user_id,
);
for($x = 0; $x<$item_number_of_photos; $x++) {
$input_parameters[':product_photo_filename_' . $x] = $item_image_filenames[$x];
$input_parameters[':product_photo_description_' . $x] = $item_image_descriptions[$x];
}
$sth = $connection->prepare($query_add_item_photos);
$sth->execute($input_parameters);
} catch(PDOException $pe) {
$response["success"] = $http_response_server_error;
$response["message"] = $http_response_server_error . $pe . $query_add_item_photos;
die(json_encode($response));
}
$response["success"] = $http_response_success;
$response["message"] = "WE MADE IT";
die(json_encode($response));
$connection = null;
} else {
$response["success"] = $http_response_bad_request;
$response["message"] = $http_message_bad_request;
die(json_encode($response));
$connection = null;
}
At the end when I run this, I get a PDO error saying that the query = "0".
I have only basic understanding of PHP so this is huge pain for me
Local Variables Issue
In your for loop, you are assigning values to $item_image_filenames[$x] array element and also to $item_image_descriptions[$x] array element.
for ($x=0; $x<$item_number_of_photos; $x++) {
...
$item_image_filenames[$x] = $_POST['item_image_filename_'.$x];
...
$item_image_descriptions[$x] = $_POST['item_image_description_'.$x];
}
But (assuming you have posted all of your code), these 2 arrays fall out of scope and disappear as soon as you exit your for loop. They weren't defined before your for loop, which means that they are being defined local to your for loop.
The result of this is that, later, when you attempt to reference these arrays, they don't exist, and they have no values. So, later on in your code...
for($x = 0; $x<$item_number_of_photos; $x++) {
$input_parameters[':product_photo_filename_' . $x] = $item_image_filenames[$x];
$input_parameters[':product_photo_description_' . $x] = $item_image_descriptions[$x];
}
... is going to result in assigning to $input_parameters values that don't exist.
To solve this problem, define $item_image_filenames and $item_image_descriptions before you enter your for loop. This way, they will continue to exist inside and after your for loop. You can do this:
$user_id = $_POST["user_id"];
$item_id = $_POST["item_id"];
$item_number_of_photos = $_POST['item_number_of_photos'];
// Define empty arrays so that I can use them throughout my code.
$item_image_filenames = array();
$item_image_descriptions = array();
for ($x=0; $x<$item_number_of_photos; $x++) {
...
String Concatenation Syntax
I also noticed that your line of code:
$query_add_item_photos+= " VALUES
...
... is not the correct way to do string concatenation in PHP. You want to use .= instead of +=. In PHP, strings are concatenated with ., as in the example: $string1 = $string2 . $string3;
Your code should instead be:
$query_add_item_photos .= " VALUES
...