I'm having an issue with a piece of my code. It works perfectly fine, except it won't save itself to the database. This is the code:
function createOrder($user, $cart, $price, $method) {
try {
$username = "root";
$password = "";
$connection = new PDO('mysql:host=localhost;dbname=dreamlineslaapsystemen', $username, $password);
$connection->beginTransaction();
$productList=$_SESSION['products'];
$orderList=$_SESSION['orders'];
$orderItems=$_SESSION['orderitems'];
$orderid = generateOrderid();
$allOrders = array();
for($i=0; $i<count($orderList); $i++) {
array_push($allOrders, $orderList[$i]->getID());
}
while(in_array($orderid, $allOrders)) {
$orderid = generateOrderid();
}
$today = date("Y-m-d H:i:s");
$order = new Order($orderid, $user->getID(), $price, $today, $method);
$newOrder = array(
':id' => $orderid,
':userid' => $user->getID(),
':date' => $today,
':method' => $method
);
$addOrder = $connection->prepare('INSERT INTO orders(id, userid, date) VALUES (:id, :userid, :date, :method');
$addOrder->execute($newOrder);
array_push($orderList, $order);
foreach($cart->getCart() as $item => $amount) {
$itemid=null;
for($i=0; $i<count($productList);$i++) {
if($productList[$i]->getID()==$item) {
$orderitem = new Orderitem($orderid, $i, $amount);
array_push($orderItems, $orderitem);
$newOrderitem = array(
':orderid' => $orderid,
':productid' => $i,
':amount' => $amount
);
$addOrderitem = $connection->prepare('INSERT INTO orderitems(orderid, productid, amount) VALUES (:orderid, :productid, :amount');
$addOrderitem->execute($newOrderitem);
}
}
}
$connection->commit();
$_SESSION['orders']=$orderList;
$_SESSION['orderitems']=$orderItems;
return $orderid;
} catch(PDOException $e) {
$connection->rollback();
print "Er is iets fout gegaan: " . $e->getMessage() . "<br>";
return null;
}
}
It does add everything to the arrays and sessions and when I do var_dump to see if it is all stored correctly in the sessions/arrays. It just won't add to the database.
You have 3 columns yet you are inserting 4 values. I assume you have a method column in your table and your insert statements lacks closing ) parenthesis.
$addOrderitem = $connection->prepare('INSERT INTO orderitems(orderid, productid, amount, method) VALUES (:orderid, :productid, :amount, :method'));
$addOrderitem = $connection->prepare('INSERT INTO orderitems(orderid, productid, amount) VALUES (:orderid, :productid, :amount'));
Related
I have tables like this:
-artists
-djs
-track_artist
-track_dj
I am adding two or more artists/djs while adding song via multiple select box. But I couldn't find how to edit those rows.
Adding song function:
$sql = "INSERT INTO sarki (sarki_isim, sarki_tarz, sarki_file, sarki_resim, sarki_eklenmetarihi) VALUES (:isim, :tarz, :file, :resim, NOW())";
$sqlartist = "INSERT INTO trackartist (trackartist_artist, trackartist_track) VALUES (:artistid, :trackid)";
$sqldj = "INSERT INTO trackdj (trackdj_dj, trackdj_track) VALUES (:djid, :trackid)";
try {
$stmt = $this->db->prepare($sql);
$stmt->execute(array(':isim' => $b["isim"], ':tarz' => $b["tarz"], ':file' => $b["file"], ':resim' => $b["resim"]));
$trackid = $this->db->lastInsertId();
foreach ($b["artists"] as $artist) {
$insert = $this->db->prepare($sqlartist);
$insert->execute(array(":artistid" => $artist, ":trackid" => $trackid));
}
foreach ($b["djs"] as $artist) {
$insert = $this->db->prepare($sqldj);
$insert->execute(array(":djid" => $artist, ":trackid" => $trackid));
}
$db = null;
return $stmt;
} catch (PDOException $e) {
echo $e->getMessage();
}
I have an array like:
$arrays = array(
array('id' => '1','Name' => 'Monica','online' => '1'),
array('id' => '2','Name' => 'Jessica','online' => '1')
);
I only included 2, but let's say I have 200 of these. I already have a table in SQL with associated columns id, name and online.
Can you help me input these into database? I'm developing using wordpress. From Insert array into MySQL database with PHP I have an idea of how to do it for 1 single array
If you're having an array , you need to use a foreach loop to know the length content of insertion.
This is an example of insertion:
if(is_array($array)){
$sql = "INSERT INTO some_table (id, name, online) values ";
$valuesArr = array();
foreach($array as $row){
$id= (int) $row['id'];
$email = mysql_real_escape_string( $row['name'] );
$name = mysql_real_escape_string( $row['online'] );
$valuesArr[] = "('$id', '$email', '$name')";
}
$sql .= implode(',', $valuesArr);
mysql_query($sql) or exit(mysql_error());
}
Please try this.
Using PDO example
$sql = <<<EOT
INSERT IGNORE INTO
table_name (id, name, online)
VALUES
(:id, :name, :online)
;
EOT;
define("INSERT_UPDATE_SQL", $sql,true);
try{
$con = new PDO(CONNECTION_STRING);
if(is_array($arrays)){
$stmt = $con->prepare(INSERT_UPDATE_SQL);
$stmt->bindParam(':id', $id);
$stmt->bindParam(':name', $name);
$stmt->bindParam(':online', $online);
foreach($arrays as $row){
$id = (int)$row['id'];
$name = $row['Name'];
$online = $row['online'];
$stmt->execute();
}
$stmt = null;
}
$con = null;
}catch (PDOException $e) {
echo 'error !!';
throw $e;
}
not changed if already registered.
I have a table like so.
CREATE TABLE `GBPAUD` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`currency_pair` varchar(11) NOT NULL DEFAULT '',
`date` datetime NOT NULL,
`sell` float NOT NULL,
`buy` float NOT NULL,
`spread` float NOT NULL,
PRIMARY KEY (`id`)
)
I have written a script that opens CSV files, itterates the rows and inserts them into the table.
After the script has run and i look in the database the table appears like this.
The code that inserts the data looks like so.
private function insert($currencyPair, $date, $buy, $sell, $spread){
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$result_set = $this->pdo->prepare("INSERT INTO ".str_replace('_', '', $this->instrument)." (currency_pair, date, sell, buy, spread) VALUES (:currency_pair, :date, :sell, :buy, :spread)");
$result = $result_set->execute(array(':currency_pair' => $currencyPair, ':date' => $date, ':buy' => (float)$buy, ':sell' => (float)$sell, 'spread' => (float)$spread));
}
I print out the values just before the exacute stament and the values are correct.
Array
(
[:currency_pair] => GBP/AUD
[:date] => 2007-11-01 14:06:04.000
[:buy] => 2.273400
[:sell] => 2.272500
[spread] => 0
)
Anyone have any idea why its not inserting my data?
EDIT:
DB connection code
define("DSN", "mysql:dbname=rates_test;host=localhost;port=3306");
define("USER", "blah");
define("PASS", "blah");
$pdo = new PDO(DSN, USER, PASS);
EDIT 2
I have taken the insert out of the function and added to the while loop im doing so you can see whats happening.
while( false !== ( $data = fgetcsv($file) ) ) {
if(array(null) !== $data){ //skip blank lines
$currencyPair = $data[$column['columns']['instrument']];
$date = $data[$column['columns']['date']];
$sell = $data[$column['columns']['sell']];
$buy = $data[$column['columns']['buy']];
$spread = (float)$buy - (float)$sell;
echo "value => " . $currencyPair . "\r\n";
echo "value => " . $date . "\r\n";
echo "value => " . $sell . "\r\n";
echo "value => " . $buy . "\r\n";
echo "value => " . $spread . "\r\n";
echo var_dump(array(':currency_pair' => $currencyPair, ':date' => $date, ':buy' => (float)$buy, ':sell' => (float)$sell, ':spread' => (float)$spread));
$result_set = $this->pdo->prepare("INSERT INTO ".str_replace('_', '', $this->instrument)." (currency_pair, date, sell, buy, spread) VALUES (:currency_pair, :date, :sell, :buy, :spread)");
$result = $result_set->execute(array(':currency_pair' => $currencyPair, ':date' => $date, ':buy' => (float)$buy, ':sell' => (float)$sell, ':spread' => (float)$spread));
}
}
and here is the result
value => GBP/AUD
value => 2007-10-28 21:21:48.000
value => 2.229000
value => 2.229900
value => 0
array(5) {
[":currency_pair"]=> string(15) "GBP/AUD"
[":date"]=> string(47) "2007-10-28 21:21:48.000"
[":buy"]=> float(0)
[":sell"]=> float(0)
[":spread"]=> float(0)
}
Edit 3:
I solved it, but its a bit hacky. Also i have no control over over these CSV's so any invisible characters can be in it. Can anyone please confirm if this is enough to handle any invisible characters there may be? ( i have not put this into a function yet, but i am doing the same for ever variable im inserting)
$buy = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $buy);
$buy = (strpos($buy, ':') && strpos($buy, '-')) ? array_shift(explode('.', $buy)) : $buy;
I do not like what i am doing with the date, but i cannot think of any other ways (i cannot parse a legitamate date straight from the CSV because of the invisable characters) even without the invisible characters removed i cannot parse a date because some feilds have more than 6 micro seconds (PHP can only handel 6)
I just wrapped a bit of code around your posted code and it works fine. I did not even change the code for the spread to :spread suggestion.
I did however add a try/catch block as I see you set the mode to throw Exceptions, but the catch block was never activated.
<?php
class tst
{
private $pdo;
private $instrument = 'gbp_aud';
public function __construct()
{
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$username = 'test';
/*** mysql password ***/
$password = 'test';
/*** database name ***/
$dbname = 'test';
try {
$this->pdo = new PDO("mysql:host=$hostname;dbname=$dbname;charset=UTF8", $username, $password);
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
$this->pdo->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND,'SET NAMES UTF8');
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
exit;
}
}
private function insert($currencyPair, $date, $buy, $sell, $spread){
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
$result_set = $this->pdo->prepare("INSERT INTO ".str_replace('_', '', $this->instrument)." (currency_pair, date, sell, buy, spread) VALUES (:currency_pair, :date, :sell, :buy, :spread)");
$result = $result_set->execute(array(':currency_pair' => $currencyPair, ':date' => $date, ':buy' => (float)$buy, ':sell' => (float)$sell, 'spread' => (float)$spread));
}
catch(PDOException $e) {
print_r($this->pdo->errorInfo());
exit;
}
}
public function doit($currencyPair, $date, $buy, $sell, $spread){
$this->insert($currencyPair, $date, $buy, $sell, $spread);
}
}
$test = new tst();
$currencyPair = 'GBP/AUD';
$date = '2007-11-01 14:06:04.000';
$buy = 2.273400;
$sell = 2.272500;
$spread = 0;
$test->doit($currencyPair, $date, $buy, $sell, $spread);
$currencyPair = 'GBP/AUD';
$date = '2007-11-02 13:06:04.000';
$buy = 2.276600;
$sell = 2.278800;
$spread = 0.4;
$test->doit($currencyPair, $date, $buy, $sell, $spread);
Results:
I just read your last question, and I have to assume that you still have some odd characters in your data feed to this process.
Do a var_dump() of the array that you feed to the ->execute() statement, that will likely show more than a simple print_r()
UPDATE
The issue is that the older files are encoded in UNICODE and the new files are simple ASCII single byte encoded.
I converted the Older files offline so to speak back to ASCII and this code loaded an old and new file quite happily
The only remaining complication if that the older files dont have column names on row 1 and the field order is a little different, but thats just a FLOC. See the code below.
<?php
class tst
{
private $pdo;
private $instrument = 'gbp_aud';
public function __construct()
{
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$username = 'test';
/*** mysql password ***/
$password = 'test';
/*** database name ***/
$dbname = 'test';
try {
$this->pdo = new PDO("mysql:host=$hostname;dbname=$dbname;charset=UTF8", $username, $password);
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
$this->pdo->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND,'SET NAMES UTF8');
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
exit;
}
}
private function insert($currencyPair, $date, $buy, $sell, $spread){
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
$result_set = $this->pdo->prepare("INSERT INTO ".str_replace('_', '', $this->instrument)." (currency_pair, date, sell, buy, spread) VALUES (:currency_pair, :date, :sell, :buy, :spread)");
$result = $result_set->execute(array(':currency_pair' => $currencyPair, ':date' => $date, ':buy' => (float)$buy, ':sell' => (float)$sell, 'spread' => (float)$spread));
}
catch(PDOException $e) {
print_r($this->pdo->errorInfo());
exit;
}
}
public function doit($currencyPair, $date, $buy, $sell, $spread){
$this->insert($currencyPair, $date, $buy, $sell, $spread);
}
}
$test = new tst();
// One old and one new format file
$files = array('GBP_AUD_Week1.csv', 'GBP_AUD_Week5.csv');
foreach ($files as $file) {
$old_format = true;
if (($handle = fopen($file, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
// test old or new file layout
if ( $data[0] == 'lTid' ) {
// New file layout
$old_format = false;
// Skip the title row
continue;
}
if ( $old_format ) {
$test->doit($data[1], $data[2], $data[3], $data[4], $data[4]-$data[3]);
} else {
$test->doit($data[2], $data[3], $data[4], $data[5], $data[5]-$data[4]);
}
}
fclose($handle);
}
}
I add a lot a values with params ($queryArr) in INSERT statemnt in foreach
public function getClients()
{
helper::putToLog("\n----- getClients\n", true);
$managedCustomerService = $this->user->GetService('ManagedCustomerService', ADWORDS_VERSION);
$selector = new Selector();
$selector->fields = array("CustomerId", "Name", "CurrencyCode");
$graph = $managedCustomerService->get($selector);
if (isset($graph->entries)) {
$accounts = [];
foreach ($graph->entries as $account) {
$accounts[$account->customerId] = $account;
}
helper::putToLog('Clients found: '.count($accounts)."\n", true);
} else {
helper::putToLog('Clients not found'."\n", true);
return false;
}
$sth = $this->db->prepare('UPDATE `adwords_clients_google` set status = 2');
$sth->execute();
$sth = null;
$queryClients = "INSERT INTO `adwords_clients_google` (`client_foreign_id`, `status`, `client_name`, `client_currency`) VALUES";
foreach($accounts as $account) {
$queryArr[$account->customerId] = "(".$account->customerId.", 1, :".$account->customerId.", :".$account->customerId."_currencyCode)";
$nameArr[$account->customerId] = $account->name;
$currencyArr[$account->customerId."_currencyCode"] = $account->currencyCode;
}
$queryClients .= implode(',', $queryArr) . " ON DUPLICATE KEY UPDATE `status` = VALUES(`status`), `client_name` = VALUES(`client_name`) ";
$sth = $this->db->prepare($queryClients);
foreach ($nameArr as $key => $value) {
$sth->bindValue(":$key", str_replace("'", "\'", $value), PDO::PARAM_STR);
}
foreach ($currencyArr as $key => $value) {
$sth->bindValue(":$key", $value, PDO::PARAM_STR);
}
print_r($sth);
try {
if ($sth->execute()) {
helper::putToLog('ok queryCampaignArr, inserted rows: ' . $sth->rowCount());
} else {
helper::putToLog('not ok', true);
}
} catch (Exception $ex) {
helper::putToLog($sth->debugDumpParams(), true);
helper::putToLog("ERROR: ".$ex->getMessage(), true);
}
return true;
}
and there are 2 array of values I need to bind $nameArr and $currencyArr. I didn't get any errors but column client_currency is empty even though array $currencyArr contains all necessary values. What's wrong?
It looks like you haven't grasped the concept of prepared+paramterized statements yet.
You prepare them once and then execute them with varying parameters (one or) multiple times.
$sth = $this->db->prepare('
INSERT INTO
`adwords_clients_google`
(`client_foreign_id`, `status`, `client_name`, `client_currency`)
VALUES
(:id, 1, :name, :currency)
ON DUPLICATE KEY UPDATE
`status` = VALUES(`status`),
`client_name` = VALUES(`client_name`)
');
$sth->bindParam(':id', $id);
$sth->bindParam(':name', $name);
$sth->bindParam(':currency', $currency);
foreach($accounts as $account) {
$id = $account->customerId;
$name = $account->name;
$currency = $account->currencyCode;
$sth->execute();
}
if you haven't got any error message/log entries please make sure that the error handling mode of your PDO instance really is set to PDO::ERRMODE_EXCEPTION.
edit: to illustrate that, here's an sscce:
<?php
$pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'localonly', 'localonly', array(
PDO::ATTR_EMULATE_PREPARES=>false,
PDO::MYSQL_ATTR_DIRECT_QUERY=>false,
PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION
));
setup($pdo); // creating temporary table + sample data for this example
printTable("before", $pdo);
$sth = $pdo->prepare('
INSERT INTO
`soFoo`
(`client_foreign_id`, `status`, `client_name`, `client_currency`)
VALUES
(:id, 1, :name, :currency)
ON DUPLICATE KEY UPDATE
`status` = VALUES(`status`),
`client_name` = VALUES(`client_name`)
');
$sth->bindParam(':id', $id);
$sth->bindParam(':name', $name);
$sth->bindParam(':currency', $currency);
$accounts = data();
foreach($accounts as $account) {
$id = $account->customerId;
$name = $account->name;
$currency = $account->currencyCode;
$sth->execute();
}
printTable("after", $pdo);
function data() {
return array_map(function($e) { return (object)$e; }, array(
array('customerId'=>1, 'name'=>'customerA', 'currencyCode'=>'cA'),
array('customerId'=>2, 'name'=>'customerB', 'currencyCode'=>'cB'),
));
}
function printTable($cap, $pdo) {
echo $cap, "\r\n";
foreach( $pdo->query('SELECT * FROM soFoo', PDO::FETCH_ASSOC) as $r ) {
echo join(', ', $r), "\r\n";
}
}
function setup($pdo) {
$pdo->exec('
CREATE TEMPORARY TABLE soFoo (
client_foreign_id int,
`status` int,
client_name varchar(32),
client_currency varchar(32),
unique(client_foreign_id)
)
');
$pdo->exec("INSERT INTO soFoo (client_foreign_id,status,client_name,client_currency) VALUES (1, 0, 'agent smith', 'kruegerrand')");
}
prints
before
1, 0, agent smith, kruegerrand
after
1, 1, customerA, kruegerrand
2, 1, customerB, cB
This is my array of order detail, array structure will be: "ids" => "qtys":
$orderData = array();
$transactionID = 1;
$orderItems = $_POST['orders'];
//echo json_encode($orderItems);
foreach ($orderItems as $order){
$qtys = $order['qty']; //Which will be "quantity" insert into database;
$ids = $order['id']; //Which will be "itemID" insert into database;
$orderData["$ids"]=$qtys;
}
Now I am looking for solutions to push the array inside the database:
$sql = "INSERT INTO item_transaction (transactionID,itemID,quantity) VALUES ($transactionID,?,?)" ;
How should I continue?
You can use bindParam to insert it inside the loop.
something like...
$stmt = $conn->prepare("INSERT INTO item_transaction transactionID,itemID,quantity) VALUES (:transactionId,:itemId,:qty)");
$stmt->bindParam(':transactionId', $transactionID );
$stmt->bindParam(':itemId', $itemID);
$stmt->bindParam(':qty', $quantity);
foreach ($orderItems as $order){
$quantity = $order['qty'];
$itemID = $order['id'];
$stmt->execute();
}
Unfortunately, you did not provide your DDL and you did not show where some of your data comes from ($transactionID ?).
<?php
class Handler {
public $dbHostname = 'DATABASE-HOSTNAME-OR-IPADDRESS-GOES-HERE';
public $dbDatabaseName = 'MYSQL-DBNAME-GOES-HERE';
public $user = 'DATABASE_USERNAME';
public $password = 'DATABASE_PASSWORD';
//public $port = 3307;
public $message;
public function handleRequest($arg) {
$orderItems = $arg['orders'];
try {
$portChunk = ( isset($this->port) ) ? ';port=' . $this->port : null;
$dsn = "mysql:dbname={$this->dbDatabaseName};host={$this->dbHostname}{$portChunk}";
$pdo = new PDO($dsn, $this->user, $this->password);
$transactionID = 1;
$stmt = $pdo->prepare("INSERT INTO item_transaction transactionID, itemID, quantity) VALUES (?, ?, ?)");
foreach ($orderItems as $order){
$stmt->execute([$transactionID, $order['id'], $order['qty']]);
}
}
catch(PDOException $e) {
$this->log('Failed: ' . $e->getMessage());
}
}
}
// Change the following to false to test from the web.
$commandLine = true;
$handler = new Handler();
if ( $commandLine ) {
// run from command line
$handler->handleRequest(['orders' =>
['qty' => 9, 'id' => 111],
['qty' => 4, 'id' => 222],
['qty' => 11, 'id' => 333],
]);
}
else {
$handler->handleRequest($_POST);
}
Bear in mind that I have NOT tested this code at all. Run it and see what happens.