php/pdo insert into database mssql with arrays - php

I need some help
Is there a way to make this in PDO? https://stackoverflow.com/a/1899508/6208408
Yes I know I could change to mysql but I use a mssql server and can't use mysql. I tried some things but I'm not as good with PDO as mysql... It's hard to find some good examples of inserting array's into database with PDO. So quickly said I have a PDO based code connected to a mssql webserver.
best regards joep
I tried this before:
//id
$com_id = $_POST['com_id'];
//array
$mon_barcode = $_POST['mon_barcode'];
$mon_merk = $_POST['mon_merk'];
$mon_type = $_POST['mon_type'];
$mon_inch = $_POST['mon_inch'];
$mon_a_date = $_POST['mon_a_date'];
$mon_a_prijs = $_POST['mon_a_prijs'];
$data = array_merge($mon_barcode, $mon_merk, $mon_type, $mon_inch, $mon_a_date, $mon_a_prijs);
try{
$sql = "INSERT INTO IA_Monitor (Com_ID, Barcode, Merk, Type, Inch, Aanschaf_dat, Aanschaf_waarde) VALUES (?,?,?,?,?,?,?)";
$insertData = array();
foreach($_POST['mon_barcode'] as $i => $barcode)
{
$insertData[] = $barcode;
}
if (!empty($insertData))
{
implode(', ', $insertData);
$stmt = $conn->prepare($sql);
$stmt->execute($insertData);
}
}catch(PDOException $e){
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;

The code below should fix your problems.
$db_username='';
$db_password='';
$conn = new \PDO("sqlsrv:Server=localhost,1521;Database=testdb", $db_username, $db_password,[]);
//above added per #YourCommonSense's request to provide a complete example to a code fragment
if (isset($_POST['com_id'])) { //was com_id posted?
//id
$com_id = $_POST['com_id'];
//array
$mon_barcode = $_POST['mon_barcode'];
$mon_merk = $_POST['mon_merk'];
$mon_type = $_POST['mon_type'];
$mon_inch = $_POST['mon_inch'];
$mon_a_date = $_POST['mon_a_date'];
$mon_a_prijs = $_POST['mon_a_prijs'];
$sql = "INSERT INTO IA_Monitor (Com_ID, Barcode, Merk, Type, Inch, Aanschaf_dat, Aanschaf_waarde) VALUES (?,?,?,?,?,?,?)";
try {
$stmt = $conn->prepare($sql);
foreach ($mon_barcode as $i => $barcode) {
$stmt->execute([$com_id, $barcode, $mon_merk[$i], $mon_type[$i], $mon_inch[$i], $mon_a_date[$i], $mon_a_prijs[$i]]);
}
} catch (\PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
}
$conn = null;

Related

Transactions in MySql not working via PDO first correct query performed [duplicate]

How is everything
Please can anyone help me in this
I'm trying to use PHP PDO transaction and there is a problem that I face and I can't deal with it.
rollBack function doesn't work when It catch an exception
Here is the connection code
$host = 'localhost';
$user = 'root';
$pass = '';
$error = '';
$dbname = 'tameras_finance';
// Set DSN
$dsn = 'mysql:host=' . $host . '; dbname=' . $dbname;
// Set options
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
// Create a new PDO instanace
try {
$dbh = new PDO($dsn, $user, $pass);
$dbh->exec("set names utf8");
}
//Catch any errors
catch (PDOException $e) {
echo $error = $e->getMessage();
}
and here the code
try{
$dbh->beginTransaction();
$dbh->query('SET #newDebit = (SELECT max(`debtor_id`) + 1 AS maxDebit FROM `vocher`)');
for($x = 0; $x < count($debits); $x++){
$dbh->query('UPDATE `vocher` SET `debtor_id` = #newDebit, `status_id` = "4" WHERE `id` = '.$debits[$x]);
}
for($x = 0; $x < count($others); $x++){
$columns = '`acc_id`, `value`, `date`, `desc`, `reject`, `vo_type_id`, `user`, `debtor_id`';
$vals = "'".$accs[$x]."','".$values[$x]."','".$dates[$x]."','".$descs[$x]."','1','1','".$user."', #newDebit";
if($others[$x] == 'e'){
$columns .= ', `cheque_no`, `available_date`, `issue_date`, `bank_id`';
$vals .= ", '".$sns[$x]."', '".$availdates[$x]."', '".$issueDates[$x]."', '".$banks[$x]."'";
}
$dbh->query("INSERT INTO creditor (".$columns.") VALUES (".$vals.")");
if($lists[$x] != 'e'){
$lastId = $dbh->lastInsertId();
$q = 'INSERT INTO `creditor_cc` (`creditor`, `cc`) VALUES ';
for($y = 0; $y < count($lists[$x]); $y++){
$dif = count($lists[$x]) - $y;
$q .= '(';
$q .= '"' . $lastId . '",';
$q .= '"'.$lists[$x][$y].'"';
$q .= ')';
if($dif > 1){
$q .= ',';
}
}
$dbh->query($q);
}
}
$dbh->commit();
} catch(PDOException $e) {
echo $error = $e->getMessage();
$dbh->rollBack();
}
This code doesn't rollback
Please note that:
$sns, $others, $accs, $values, $dates, $descs, $availdates,
$issueDates and $banks are arrays with the same size
Also $lists is a two dimension array with the same size
please help me with this why this code doesn't rollBack
Transactions are not supported on MySQL's default table type MyISAM. You need to make sure you're using InnoDB tables.
Also check to make sure the exception that's being thrown is PDOException or it'll fall through the try/catch and not hit your rollback.
I would say it shoud be done this way:
$pdo = new \PDO(/*...*/);
$pdo->beginTransaction();
try {
//...
} catch(\Exception $e) {
$pdo->rollBack();
throw $e;
}
$pdo->commit();

I want to write code for check if data already exits then insert in different table

I already write the code to check if table call hm2_history type = commission if yes then insert data into table call hm2_deposit, when I test echo was correct and show the result is :
Connected successfully
354
368
But won't insert into hm2_deposit , I don't know how to adjust it i have a little bit knowledge about php
This is my code
<?php
$servername = "localhost";
$username = "tinybaht_findroom";
$password = "212224";
function setChecked($conn,$params){
$s = $conn->prepare("UPDATE `hm2_history`
SET history_ref_id=-1
WHERE id=:id
");
$s->execute($params);
}
try {
$conn = new PDO("mysql:host=$servername;dbname=tinybaht_findroom", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
$stmt = $conn->prepare("SELECT * FROM hm2_history");
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$a = $stmt->fetchAll();
$plans = array();
foreach($a as $i){
$plans[$i['type']] = 'commissions';
}
$stmt = $conn->prepare("SELECT * FROM hm2_history WHERE id NOT IN(SELECT ref_id FROM hm2_deposits WHERE ref_id > 0) AND type='commissions'");
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$rows = $stmt->fetchAll();
foreach($rows as $k=>$v) {
$plan_type = isset($plans)?:'';
$m = $v['type'];
if (!empty($plan_type)){
echo '<br>'.$v['id'];
if ($m = "commissions" ){
setChecked($conn,array('id'=>$v['id']));
continue;
}
}else{
setChecked($conn,array('id'=>$v['id']));
continue;
}
//deposits
$s = $conn->prepare("INSERT INTO `hm2_deposits`
SET `user_id`=:user_id,
`type_id`=:type_id,
`deposit_date`=:deposit_date,
`last_pay_date`=:last_pay_date,
`status`=:status,
`q_pays`=:q_pays,
`amount`=:amount,
`actual_amount`=:actual_amount,
`ec`=:ec,
`compound`=:compound,
`dde`=:dde,
`unit_amount`=:unit_amount,
`bonus_flag`=:bonus_flag,
`init_amount`=:init_amount,
`ref_id`=:ref_id
");
$v['ref_id'] = $v['id'];
$v['amount'] = $v['amount']*$rate;
$v['actual_amount'] = $v['actual_amount']*$rate;
$v['init_amount'] = $v['init_amount']*$rate;
$v['bonus_flag'] = 1;
$v['type_id']= 9;
unset($v['id']);
$s->execute($v);
$lastDepositId = $conn->lastInsertId();
$date = date('Y-m-d H:i:s');
}
?>
this is photo of my db table name is hm2_deposits hm2_deposits
this is photo of my db table name is hm2_history enter image description here
There is an error in your SQL:
$s = $conn->prepare("INSERT INTO hm2_deposits
SET user_id=:user_id,
type_id=:type_id,
deposit_date=:deposit_date,
last_pay_date=:last_pay_date,
status=:status,
q_pays=:q_pays,
amount=:amount,
actual_amount=:actual_amount,
ec=:ec,
compound=:compound,
dde=:dde,
unit_amount=:unit_amount,
bonus_flag=:bonus_flag,
init_amount=:init_amount,
ref_id=:ref_id
");
Read the proper way to do it at:
https://www.w3schools.com/sql/sql_insert.asp

PHP PDO transaction rollBack doesn't work

How is everything
Please can anyone help me in this
I'm trying to use PHP PDO transaction and there is a problem that I face and I can't deal with it.
rollBack function doesn't work when It catch an exception
Here is the connection code
$host = 'localhost';
$user = 'root';
$pass = '';
$error = '';
$dbname = 'tameras_finance';
// Set DSN
$dsn = 'mysql:host=' . $host . '; dbname=' . $dbname;
// Set options
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
// Create a new PDO instanace
try {
$dbh = new PDO($dsn, $user, $pass);
$dbh->exec("set names utf8");
}
//Catch any errors
catch (PDOException $e) {
echo $error = $e->getMessage();
}
and here the code
try{
$dbh->beginTransaction();
$dbh->query('SET #newDebit = (SELECT max(`debtor_id`) + 1 AS maxDebit FROM `vocher`)');
for($x = 0; $x < count($debits); $x++){
$dbh->query('UPDATE `vocher` SET `debtor_id` = #newDebit, `status_id` = "4" WHERE `id` = '.$debits[$x]);
}
for($x = 0; $x < count($others); $x++){
$columns = '`acc_id`, `value`, `date`, `desc`, `reject`, `vo_type_id`, `user`, `debtor_id`';
$vals = "'".$accs[$x]."','".$values[$x]."','".$dates[$x]."','".$descs[$x]."','1','1','".$user."', #newDebit";
if($others[$x] == 'e'){
$columns .= ', `cheque_no`, `available_date`, `issue_date`, `bank_id`';
$vals .= ", '".$sns[$x]."', '".$availdates[$x]."', '".$issueDates[$x]."', '".$banks[$x]."'";
}
$dbh->query("INSERT INTO creditor (".$columns.") VALUES (".$vals.")");
if($lists[$x] != 'e'){
$lastId = $dbh->lastInsertId();
$q = 'INSERT INTO `creditor_cc` (`creditor`, `cc`) VALUES ';
for($y = 0; $y < count($lists[$x]); $y++){
$dif = count($lists[$x]) - $y;
$q .= '(';
$q .= '"' . $lastId . '",';
$q .= '"'.$lists[$x][$y].'"';
$q .= ')';
if($dif > 1){
$q .= ',';
}
}
$dbh->query($q);
}
}
$dbh->commit();
} catch(PDOException $e) {
echo $error = $e->getMessage();
$dbh->rollBack();
}
This code doesn't rollback
Please note that:
$sns, $others, $accs, $values, $dates, $descs, $availdates,
$issueDates and $banks are arrays with the same size
Also $lists is a two dimension array with the same size
please help me with this why this code doesn't rollBack
Transactions are not supported on MySQL's default table type MyISAM. You need to make sure you're using InnoDB tables.
Also check to make sure the exception that's being thrown is PDOException or it'll fall through the try/catch and not hit your rollback.
I would say it shoud be done this way:
$pdo = new \PDO(/*...*/);
$pdo->beginTransaction();
try {
//...
} catch(\Exception $e) {
$pdo->rollBack();
throw $e;
}
$pdo->commit();

SELECT_IDENTITY() not working in php

Scenario:
I have a SQL Query INSERT INTO dbo.Grades (Name, Capacity, SpringPressure) VALUES ('{PHP}',{PHP}, {PHP})
The data types are correct.
I need to now get the latest IDENTIY which is GradeID.
I have tried the following after consulting MSDN and StackOverflow:
SELECT SCOPE_IDENTITY() which works in SQL Management Studio but does not in my php code. (Which is at the bottom), I have also tried to add GO in between the two 'parts' - if I can call them that - but still to no avail.
The next thing I tried, SELECT ##IDENTITY Still to no avail.
Lastly, I tried PDO::lastInsertId() which did not seem to work.
What I need it for is mapping a temporary ID I assign to the object to a new permanent ID I get back from the database to refer to when I insert an object that is depended on that newly inserted object.
Expected Results:
Just to return the newly inserted row's IDENTITY.
Current Results:
It returns it but is NULL.
[Object]
0: Object
ID: null
This piece pasted above is the result from print json_encode($newID); as shown below.
Notes,
This piece of code is running in a file called save_grades.php which is called from a ajax call. The call is working, it is just not working as expected.
As always, I am always willing to learn, please feel free to give advice and or criticize my thinking. Thanks
Code:
for ($i=0; $i < sizeof($grades); $i++) {
$grade = $grades[$i];
$oldID = $grade->GradeID;
$query = "INSERT INTO dbo.Grades (Name, Capacity, SpringPressure) VALUES ('" . $grade->Name . "',". $grade->Capacity .", ".$grade->SpringPressure .")";
try {
$sqlObject->executeNonQuery($query);
$query = "SELECT SCOPE_IDENTITY() AS ID";
$newID = $sqlObject->executeQuery($query);
print json_encode($newID);
} catch(Exception $e) {
print json_encode($e);
}
$gradesDictionary[] = $oldID => $newID;
}
EDIT #1
Here is the code for my custom wrapper. (Working with getting the lastInsertId())
class MSSQLConnection
{
private $connection;
private $statement;
public function __construct(){
$connection = null;
$statement =null;
}
public function createConnection() {
$serverName = "localhost\MSSQL2014";
$database = "{Fill In}";
$userName = "{Fill In}";
$passWord = "{Fill In}";
try {
$this->connection = new PDO( "sqlsrv:server=$serverName;Database=$database", $userName, $passWord);
$this->connection->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch( PDOException $e ) {
die("Connection Failed, please contact system administrator.");
}
if ($this->connection == null) {
die("Connection Failed, please contact system administrator.");
}
}
public function executeQuery($queryString) {
$results = array();
$this->statement = $this->connection->query( $queryString );
while ( $row = $this->statement->fetch( PDO::FETCH_ASSOC ) ){
array_push($results, $row);
}
return $results;
}
public function executeNonQuery($queryString) {
$numRows = $this->connection->exec($queryString);
}
public function getLastInsertedID() {
return $this->connection->lastInsertId();
}
public function closeConnection() {
$this->connection = null;
$this->statement = null;
}
}
This is PDO right ? better drop these custom function wrapper...
$json = array();
for ($i=0; $i < sizeof($grades); $i++) {
//Query DB
$grade = $grades[$i];
$query = "INSERT INTO dbo.Grades (Name, Capacity, SpringPressure)
VALUES (?, ?, ?)";
$stmt = $conn->prepare($query);
$success = $stmt->execute(array($grade->Name,
$grade->Capacity,
$grade->SpringPressure));
//Get Ids
$newId = $conn->lastInsertId();
$oldId = $grade->GradeID;
//build JSON
if($success){
$json[] = array('success'=> True,
'oldId'=>$oldId, 'newId'=>$newId);
}else{
$json[] = array('success'=> False,
'oldId'=>$oldId);
}
}
print json_encode($json);
Try the query in this form
"Select max(GradeID) from dbo.Grades"

creating pdo class in php

I'm trying to create a simple php object to manage a mysql database through pdo. So far it connects to the database just fine and now when I try to insert a new row i get the follow error:
PHP Fatal error: Using $this when not in object context on line 37
line 37 is $STH = $this->DBH->prepare($sql);
i'm probably just using $this wrong. any help will be appreciated.
<?
class Database {
private $DBH;
//connects to the database
function __construct($host,$dbname,$user,$pass) {
try {
$this->DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
}
catch(PDOException $e) {
echo $e->getMessage();
}
}
//inserts into the database
//$tableName name of the table to insert the info into
//$items is a multidimensional array of array(column name, value)
public function insert($tableName,$items){
$values = array();
$sql = "INSERT INTO $tableName(";
$valuePlaceHolder = ''; // holds the question marks at the end of the PDO sql string
foreach($items as $item){
$sql .= $item[0] . ',';
array_push($values, $item[1]);
$valuePlaceHolder .= '?,';
}
// remove the last comma from the sql statement
$sql = substr($sql,0,-1);
$valuePlaceHolder = substr($valuePlaceHolder, 0, -1);
$sql .= ") values ($valuePlaceHolder)";
echo $sql;
$STH = $this->DBH->prepare($sql);
$STH->execute($values);
}
}
?>
read this:
http://www.php.net/manual/es/language.oop5.basic.php#88665
So that you can solve your problem:
....
// remove the last comma from the sql statement
$sql = substr($sql,0,-1);
$valuePlaceHolder = substr($valuePlaceHolder, 0, -1);
$sql .= ") values ($valuePlaceHolder)";
echo $sql;
$STH = Database::DBH;
$SHT = $SHT->prepare($sql);
$STH->execute($values);
.......

Categories