This question already has answers here:
PHP PDO - There is no active transaction
(2 answers)
Closed 2 years ago.
im trying to update 2 tables at once. from my research i have to use a transaction for this:
protected function myUpdateFunction(){
try{
$this->connect()->beginTransaction();
$itemID = filter_input(INPUT_POST, 'updateItemID');
$itemName = filter_input(INPUT_POST, 'updateItemName');
$itemDescription = filter_input(INPUT_POST, 'updateItemDescription');
$itemPrice = filter_input(INPUT_POST, 'updateItemPrice');
$itemStock = filter_input(INPUT_POST, 'updateItemStock');
$updateItemBtn = filter_input(INPUT_POST, 'updateItemBtn');
$sql = "UPDATE oopphp_items SET itemName = ?, itemDescription = ?, itemPrice = ?, itemStock = ? WHERE itemID = ?";
$stmt = $this->connect()->prepare($sql);
$stmt->bindParam(1, $itemName, PDO::PARAM_STR);
$stmt->bindParam(2, $itemDescription, PDO::PARAM_STR);
$stmt->bindParam(3, $itemPrice, PDO::PARAM_STR);
$stmt->bindParam(4, $itemStock, PDO::PARAM_INT);
$stmt->bindParam(5, $itemID, PDO::PARAM_INT);
$stmt->execute();
//wishlist
$itemID_fk = filter_input(INPUT_POST, 'updateItemID');
$itemName_fk = filter_input(INPUT_POST, 'updateItemName');
$itemDescription_fk = filter_input(INPUT_POST, 'updateItemDescription');
$itemPrice_fk = filter_input(INPUT_POST, 'updateItemPrice');
$sql = "UPDATE oopphp_wishlist SET itemName_fk = ?, itemDescription_fk = ?, itemPrice_fk = ? WHERE itemID_fk = ?";
$stmt = $this->connect()->prepare($sql);
$stmt->bindParam(1, $itemName_fk, PDO::PARAM_STR);
$stmt->bindParam(2, $itemDescription_fk, PDO::PARAM_STR);
$stmt->bindParam(3, $itemPrice_fk, PDO::PARAM_STR);
$stmt->bindParam(4, $itemID_fk, PDO::PARAM_INT);
$stmt->execute();
$this->connect()->commit();
}
catch(Exception $e){
echo $e->getMessage();
$this->connect()->rollBack();
}
}
i get the following error:
Fatal error: Uncaught PDOException: There is no active transaction
when i tried looking for answers they all said to put it inside a try-catch, which i already did. all examples i could find do it like this. as seen here: PHP PDO - There is no active transaction
i also found some people suggest adding these to the database file:
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute( PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
which also hasent done anything.
now if i just remove the code inside the catch() then the error goes away and i both my update queries work.
the only difference i could spot is that all examples dont have their database connection as a function.
so where i do:
$this->connect()->beginTransaction();
they do:
$pdo->beginTransaction();
and obviously same for commit() and rollBack(). though i cant imagine this being the problem. especially when it works perfectly if i remove the catch() content.
this is where i got the code from: https://thisinterestsme.com/php-pdo-transaction-example/
i seem to have the same code apart from the connect() vs $pdo.
my connect function:
protected function connect(){
try{
$dsn = 'mysql:host=' . $this->DB_HOST . ';dbname=' . $this->DB_NAME;
$pdo = new PDO($dsn, $this->DB_USER, $this->DB_PASS);
//setting default fetch mode
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
//setting errors for exceptions for try/catch
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute( PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::ATTR_AUTOCOMMIT, false);
return $pdo;
}
catch(PDOException $error){
echo 'Connection error: ' . $error->getMessage();
}
finally{
//$pdo = null;
}
}
i fixed it with the help of the comment, and a final note at the end if someone sees this later:
this line i mentioned: $pdo->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
made it so my CRUD didnt work anymore. the other 2 setAttribute() didnt cause errors with anything at this moment.
When you call connect(), you get a different PDO object each time. Thus,
$this->connect()->beginTransaction(); // pdo object 1
$this->connect()->commit(); // pdo object 4
PDO object 4 has no transaction in progress! the Exception is normal.
Quick fix :
in you try block
$pdo = $this->connect();
$pdo->beginTransaction();
.... // replace all $this->connect() by $pdo
$pdo->commit();
Related
This question already has answers here:
PDO valid characters for placeholders
(2 answers)
Closed 2 years ago.
Hej.
I´m new to PHP but strugling to learn. i have found out that this is the way to handle database connection. Have debugged the code but have one stubborn thing left. Cant seem to wrap my brain around this errorcode. Any pointer in simple way so even i understand. ;-)
I am surfing this pages: https://www.php.net/manual/en/pdostatement.bindparam.php
Error-message:
Database connection establishedPDOException: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined in C:\xampp\htdocs\Test\dbtest.php:28 Stack trace: #0 C:\xampp\htdocs\Test\dbtest.php(28): PDOStatement->execute() #1 {main}
<?php
// Require needed classes
require_once('dbhandler.php');
// Create needed objects
$dbh = new DBHandler();
// Check if database connection established successfully
if ($dbh->getInstance() === null) {
die("No database connection");
}
//$datetime = date("Y-m-d H:i:s");
$epost = 'svante#telia.com';
$namn = 'Svante';
$användarnamn = 'Poffe';
$lösenord = '1596';
try {
$sql = "INSERT INTO users(epost, namn, användarnamn, lösenord) VALUES(:epost, :namn, :användarnamn, :lösenord)";
$stmt = $dbh->getInstance()->prepare($sql);
$stmt->bindParam(':epost', $epost, PDO::PARAM_STR);
$stmt->bindParam(':namn', $namn, PDO::PARAM_STR);
$stmt->bindParam(':användarnamn', $användarnamn, PDO::PARAM_STR);
$stmt->bindParam(':lösenord', $lösenord, PDO::PARAM_STR);
$stmt->execute();
}
catch(PDOException $e) {
echo $e;
}
?>
/Svante
It might be worth trying a simplified version that omits the special characters from the PHP variable and the assigned placeholders.
<?php
require_once('dbhandler.php');
$dbh = new DBHandler();
$e = 'svante#telia.com';
$n = 'Svante';
$a = 'Poffe';
$l = '1596';
$sql = "INSERT INTO users( `epost`, `namn`, `användarnamn`, `lösenord` ) VALUES( :e, :n, :a, :l )";
$stmt = $dbh->getInstance()->prepare($sql);
$stmt->bindParam(':e', $e, PDO::PARAM_STR);
$stmt->bindParam(':n', $n, PDO::PARAM_STR);
$stmt->bindParam(':a', $a, PDO::PARAM_STR);
$stmt->bindParam(':l', $l, PDO::PARAM_STR);
$stmt->execute();
I am unable to get the lastInserId using PDO in php
$conn = new Db();
$query = "INSERT INTO orders SET
order_timestamp= :orderTimestamp ,
customer_id= :customerId";
$stmt = $conn->dbConnect()->prepare($query);
$stmt->bindParam(':orderTimestamp', date("Y-m-d H:i:s"), PDO::PARAM_STR);
$stmt->bindParam(':customerId', $_SESSION["customerId"], PDO::PARAM_INT);
$stmt->execute();
$orderId = $conn->lastInsertId();
return $orderId;
Below is the code used for DB Connection
public function dbConnect(){
try {
$conn = new PDO('mysql:host='.DBHOST.';dbname='.DBNAME, DBUSER, DBPASSWORD);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
return $conn;
}
I am getting an error as mentioned below.
Strict Standards: Only variables should be passed by reference in
H:\xampp\htdocs\php\tuf4\hunger\includes\classes\class.hunger.php on
line 31
Fatal error: Call to undefined method Db::lastInsertId() in
H:\xampp\htdocs\php\tuf4\hunger\includes\classes\class.hunger.php on
line 34
bindParam expects a variable, to be passed by reference. date("Y-m-d H:i:s") is clearly not a variable ;)
Try bindValue instead.
Using the correct function will stop the domino effect of errors, and allow you to get the lastInsertId you are seeking.
EDIT: On further review, you are trying to call lastInsertId on your Db wrapper class, not on the PDO object. Try:
$pdo = $conn->dbConnect();
$stmt = $pdo->prepare($query);
// ...
$orderId = $pdo->lastInsertId();
I am trying to write this basic function to get a value from a table.
<?php
function getvalue($value, $from, $id){
//Returns the value of a table
require('includes/connect.php');
$db = new PDO('mysql:host=localhost;dbname='.$database, $username, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT :value AS value
FROM :from
WHERE id = :id
LIMIT 1";
$stmt = $db->prepare($sql);
$stmt->bindParam(':value', $value, PDO::PARAM_STR);
$stmt->bindParam(':from', $from, PDO::PARAM_STR);
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();
$data = $stmt->fetch();
$return = $data['value'];
return $return;
}//function
?>
It gives this Fatal error:
Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''project' WHERE id = '1'' at line 2' in /functions/getvalue.php:26 Stack trace: #0 /functions/getvalue.php(26): PDOStatement->execute() #1 /
test.php(24): getvalue('tarief', 'project', '1') #2 {main} thrown in /functions/getvalue.php on line 26
Although your idea of having such a function is excellent, the implementation is just terrible. Some essential drawbacks are:
you are connecting to database every time this function is called
this code is prone to SQL injection
yet it is awfully inflexible, letting you to run no query different from silly SELECT ... WHERE id. Eventually you will learn other queries and find this function unusable.
It should be a function that accepts an SQL query and array with parameters to bind:
<?php
//Returns the value of a query
function getvalue($sql, $params = array())
{
global $pdo;
$stmt = $db->prepare($sql);
$stmt->execute($params);
return $stmt->fetchColumn();
}
require('includes/connect.php');
$name = getValue("SELECT name FROM users WHERE id =?",array($_GET['id']))
simple, robust and usable.
While connection string better to be moved into includes/connect.php
$dsn = "mysql:host=localhost;dbname=$database;charset=utf8";
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$pdo = new PDO($dsn, $username, $password, $opt);
Try this (be sure $value and $from variables values are escaped):
<?php
function getvalue($value, $from, $id){
//Returns the value of a table
require('includes/connect.php');
$db = new PDO('mysql:host=localhost;dbname='.$database, $username, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT " . $value . " AS value
FROM " . $from . "
WHERE id = :id
LIMIT 1";
$stmt = $db->prepare($sql);
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();
$data = $stmt->fetch();
$return = $data['value'];
return $return;
}//function
?>
Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 9 years ago.
Improve this question
I recently moved to MariaDB, because since MySQL 5.6 it has been failing a lot for me.
MariaDB works flawlessly but, in a new project, I cannot insert data to the database with a PHP script. I can only insert manually. I have made no changes from scripts working with MySQL.
The INSERT statement is:
INSERT INTO participantes (nome, curso, email, equipe) VALUES (:nome, :curso, :email, :equipe);
And the script which should be inserting is:
$stmt = $this->dbh->prepare($this->SQL_INSERT);
$nome = $participante->nome();
$curso = $participante->curso();
$email = $participante->email();
$equipe = $participante->equipe();
$stmt->bindParam(':nome', $nome);
$stmt->bindParam(':curso', $curso);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':equipe', $equipe);
$stmt->execute();
The "participante" functions return data to be used, with no problems. Everything is inside a try/catch block, which reports no exceptions.
My PDO class is as follows:
class Connection extends PDO {
private $dsn = 'mysql:host=localhost;port=3307;dbname=dacu';
private $usr = 'dacu';
private $pwd = 'my password';
public $handle = null;
function __construct() {
try {
if ($this->handle == null) {
$dbh = new PDO($this->dsn, $this->usr, $this->pwd);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->handle = $dbh;
return $this->handle;
}
}
catch (PDOException $e) {
throw new Exception('Não foi possível conectar-se ao banco de dados: ' . $e->getMessage());
}
catch (Exception $e) {
throw new Exception('Um erro não identificado ocorreu: ' . $e->getMessage());
}
}
}
And using controller->insert gives me:
Warning: PDO::prepare(): SQLSTATE[00000]: No error: PDO constructor was not called in C:\Webserver\Files\dacu\controller\EquipesController.php on line 25
I can post code on pastebin if necessary, just ask.
Check your connection, then try this way, its working fine:
//first you need a connection to mysql use this and replace the variables
try {
$dbh = new PDO('mysql:host=localhost;dbname='.$db_name.'', $user, $pass, array(
PDO::ATTR_PERSISTENT => true
));
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
//then do the insert variable
$sql = 'INSERT INTO encomendas (`nome`, `user`, `id`, `email`) ';
$sql .= 'VALUES (:nome, :curso, :email, :equipe )';
$query = $dbh->prepare($sql);
//bindParam with your own variables
$query->bindParam(':nome', $varDoNome, PDO::PARAM_STR);
$query->bindParam(':curso', $varDoCurso, PDO::PARAM_STR);
$query->bindParam(':email', $varDoEmail, PDO::PARAM_STR);
$query->bindParam(':equipe', $varDaequipe, PDO::PARAM_STR);
//execute query
$query->execute()
;
This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 7 years ago.
I'm trying to work with PDO class on php but I have some trouble to find the right way to handle errors, I've wrote this code:
<?php
// $connection alreay created on a class which works with similar UPDATE statements
// I've simply added here trim() and PDO::PARAM... data type
$id = 33;
$name = "Mario Bros.";
$url = "http://nintendo.com";
$country = "jp";
try {
$sql = "UPDATE table_users SET name = :name, url = :url, country = :country WHERE user_id = :user_id";
$statement = $connection->prepare ($sql);
$statement->bindParam (':user_id', trim($id), PDO::PARAM_INT);
$statement->bindParam (':name', trim($name), PDO::PARAM_STR);
$statement->bindParam (':url', trim($url), PDO::PARAM_STR);
$statement->bindParam (':country', trim($country), PDO::PARAM_STR, 2);
$status = $statement->execute ();
} catch (PDOException $e) {
print $e->getMessage ();
}
print $status; // it returns a null value, and no errors are reported
?>
this portion of code doesn't report errors, but it simply doesn't work, the var $status at the bottom, return a null value.
can someone help me to find where I'm wrong?
PDO won't throw exceptions unless you tell it to. Have you run:
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
on the PDO object?
You can add the attribute one time while you connect you mysql.
function connect($dsn, $user, $password){
try {
$dbh = new PDO($dsn, $user, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
exit;
}
}
Thanks