PHP PDO put commands in transaction problem - php

I am using PHP PDO for work with database SQLITE3. Can somebody show me how to put this commands in one transaction ?
$db = new PDO('sqlite:/var/db/fan_coil.db');
$sql = 'DELETE FROM fan_coil_plan WHERE fan_coil_id = :fan_coil_id;';
$sth = $db->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute(array(':fan_coil_id' => $fan_coil_id));
$sql = ' DELETE FROM fan_coil_working_mode WHERE fan_coil_id = :fan_coil_id;';
$sth = $db->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute(array(':fan_coil_id' => $fan_coil_id));
//****************** inserting working mode *************************************************************************************************
$i = 0;
$sql = 'INSERT INTO fan_coil_working_mode
(fan_coil_id,working_mode, temperature_set_point, max_positive_temperature,min_positive_temperature,mode_type,max_fan_speed)
VALUES(:fan_coil_id,:working_mode,:temperature_set_point,:max_positive_temperature,:min_positive_temperature,:mode_type,:max_fan_speed)';
$sth = $db->prepare($sql);
foreach ($modes as $key => $value) {
//file_put_contents('error.txt',$value['temperature_set_point'], FILE_APPEND );
$working_mode = '0'; //treba da se izbaci ova kolona iz tabele
$temperature_set_point = $value['temperature_set_point'];
$max_positive_variation = $value['max_positive_variation'];
$min_positive_variation = $value['min_positive_variation'];
$max_fan_speed = $value['max_fan_speed'];
$mode_type = ++$i;
$sth->execute(array(':fan_coil_id' => $fan_coil_id, ':working_mode' => $working_mode, ':temperature_set_point' => $temperature_set_point, ':max_positive_temperature' => $max_positive_temperature, ':min_positive_temperature' => $min_positive_temperature, ':mode_type' => $mode_type, ':max_fan_speed' => $max_fan_speeed));
}

$db = new PDO('sqlite:/var/db/fan_coil.db');
$db->beginTransaction();
try {
// your code
$db->commit();
}catch(PDOException $e) {
$db->rollBack();
throw $e;
}

Related

foreach loop update only last value three times in table

This is a code to update a table with foreach loop. But it update the last value three times which is POST[s3_name]
<?php
$names = [$_POST['s1_name'], $_POST['s2_name'], $_POST['s3_name']];
$query = "update students SET Name=:Name WHERE ProjectID='$id'";
foreach ($names as $name) {
try
{
$stmt = $conn->prepare($query);
$stmt->bindParam(':Name', $name);
$result = $stmt->execute();
$msg = "Record updated";
}
catch(PDOException $ex)
{
$msg = $ex -> getMessage();
}
}
You could get the id from somewhere and loop that as well. Something like this
$names = [
['id' => 1, 'name' => 'name1'],
['id' => 2, 'name' => 'name2'],
['id' => 3, 'name' => 'name3']
];
foreach ($names as $name) {
try {
$query = "update students SET Name=:Name WHERE ProjectID=:Id";
$stmt = $conn->prepare($query);
$stmt->bindParam(':Name', $name['name']);
$stmt->bindParam(':Id', $name['id']);
$result = $stmt->execute();
$msg = "Record updated";
} catch(PDOException $ex) {
$msg = $ex -> getMessage();
}
}

Mysql - Get Last inserted ID is not working

I dont know why this is not working. The LAST_INSERT_ID() is not being catched, can someone help me please?
$query = "
INSERT INTO products_categories (
name,
url
) VALUES (
:name,
:url
) SELECT LAST_INSERT_ID();
";
$query_params = array(
':name' => $_POST['name'],
':url' => $_POST['url']
);
try{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex){
echo 0;
return true;
}
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$id_category = $result["id"];
"You can remove your SELECT LAST_INSERT_ID() part from the query and use $db->lastInsertId(); instead." - #barell
Try this;
<?php
$query = "
INSERT INTO products_categories (
name,
url
) VALUES (
:name,
:url
)
";
$query_params = array(
':name' => $_POST['name'],
':url' => $_POST['url']
);
try{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex){
echo 0;
return true;
}
$result = $stmt->fetch(PDO::FETCH_ASSOC);
//$id_category = $result["id"];
$id_category = $db->lastInsertId();
Hope it helps

How to convert mysqli code to PDO stmt?

if($_REQUEST['action'] == 'addToCart' && !empty($_REQUEST['id'])){
$productID = $_REQUEST['id'];
// get product details
$query = $db->query("SELECT * FROM products WHERE id = ".$productID);
$row = $query->fetch_assoc();
$itemData = array(
'id' => $row['id'],
'name' => $row['name'],
'price' => $row['price'],
'qty' => 1
);
$insertItem = $cart->insert($itemData);
$redirectLoc = $insertItem?'viewCart.php':'index.php';
header("Location: ".$redirectLoc);
}
I'm trying to convert this code to PDO stmt. Please help me with this, I'm new here.
You need to develop and pdo connection with whichever database you have. Check the connection check and connect with it.
Make sure that you have install PDO library, check it your php info.
try
{
$conn =new PDO("sqlsrv:Server=$this->hostName;Database=$this->dbName", "$this->userName", "$this->password");
$productID = $_REQUEST['id'];
$sql = "SELECT * FROM products WHERE id=?";
$stmt->bindParam(1, $productID);
$stmt = $conn->prepare($sql);
$this->result = $stmt->execute();
if (!$this->result)
{
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$itemData = array(
'id' => $row['id'],
'name' => $row['name'],
'price' => $row['price'],
'qty' => 1
);
}
}
$insertItem = $cart->insert($itemData);
$redirectLoc = $insertItem?'viewCart.php':'index.php';
header("Location: ".$redirectLoc);
}
catch(Exception e)
{
echo $e->getMessage();
exit();
}

prepare statement in php not work

Hi i get a value with post methos and i want to check it with function func_check_seven_userid()
when i use :
$stmt = $this->conn->prepare("SELECT * FROM content where content_id= ".$this->seven);
$stmt->execute();
it work.
but when i use :
$stmt = $this->conn->prepare("SELECT * FROM content WHERE content_id = :id");
$stmt->execute(array(":id" => $this->seven));
it is not work!!!
my complet code is :
<?php
class insert_content {
private $conn;
private $seven;
private $row_id;
//**********************************************************************
function connect() {
include 'db_connection.php';
try {
$this->conn = new PDO("mysql:host=$servername;dbname=$db_name", $username, $password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Exception $e) {
echo "Connection failed: " . $e->getMessage();
}
}
//************************************************************************
private function func_check_seven_userid() {
$stmt = $this->conn->prepare("SELECT * FROM content WHERE content_id = :id");
$stmt->execute(array(":id" => $this->seven));
$row = $stmt->fetch();
$this->row_id = $row[0];
if ($this->row_id) {
echo 'yes';
}
else {
echo 'no';
}
}
//****************************************************************
function __construct($parms) {
$this->connect();
$this->seven = $parms['seven'];
$this->func_check_seven_userid();
}
function __destruct() {
$this->conn = null;
}
}
if (isset($_POST['seven'])) {
$parms = array('seven' => ($_POST['seven']));
$class = new insert_content($parms);
}
?>
thanks for help
I found this:
<?php
/* Execute a prepared statement by passing an array of values */
$sql = 'SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour = :colour';
$sth = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute(array(':calories' => 150, ':colour' => 'red'));
$red = $sth->fetchAll();
$sth->execute(array(':calories' => 175, ':colour' => 'yellow'));
$yellow = $sth->fetchAll();
?>
on http://php.net/manual/en/pdo.prepare.php
Here the statement is prepared with PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY
Maybe it does the difference. Hope it helps

PDO JSON encode multiple HTML table rows

I am building a PHP function that is supposed to answer a jQuery Ajax call, depending on what id is submitted. There can be multiple forms with the same ID and I can't figure out why it is not sending back more than one record. PS: My dad will kill me if I don't figure this out by Monday...
My PHP:
<?php
if (!empty($_GET['id'])) {
$id = $_GET['id'];
try {
$objDb = new PDO('mysql:host=localhost;dbname=blankett', 'root', 'root');
$objDb->exec('SET CHARACTER SET utf8');
$sql = "SELECT *
FROM `forms`
WHERE `id` = '$id'";
$statement = $objDb->prepare($sql);
$list = $statement->fetchAll(PDO::FETCH_ASSOC);
if (!empty($list)) {
$out = array();
foreach ($list as $row ) {
$out[] = '<tr><td>'.$row['name_form'].'</td> <td>'.$row['date_added'].'</td></tr>';
}
echo json_encode(array('error' => false, 'list' => $out));
} else {
echo json_encode(array('error' => true));
}
} catch(PDOException $e) {
echo json_encode(array('error' => true));
}
} else {
echo json_encode(array('error' => true));
}
?>
You're using the prepared statement incorrectly. First, you should not be putting your variable in the statement. Second, you need to execute the statement.
Here is an example from the php.net site:
$sql = 'SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour = :colour';
$sth = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute(array(':calories' => 150, ':colour' => 'red'));
$red = $sth->fetchAll();
$sth->execute(array(':calories' => 175, ':colour' => 'yellow'));
$yellow = $sth->fetchAll();
And here is how you would do it:
$sql = "SELECT *
FROM `forms`
WHERE `id` = :formID";
$statement = $objDb->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$statement ->execute(array(':formID' => $id));
$list= $statement ->fetchAll();

Categories