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()
;
Related
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();
I want to insert data into CLOUD and IDC tables.
Cloudid is the foreign key of IDC table, so i want to use transaction.
Before $conn->beginTransaction(); and $conn->commit(); are added ,it works fine, but without them, it works fine.
Here is my code:
<?php
if($_GET["act"]=="add")
{
try
{
$conn=new PDO('mysql:host=localhost;port=3306;dbname=xxx' , 'root' , 'xxxx');
//$conn->beginTransaction();
$query="
insert into CLOUD (name,date) VALUES('".$_POST['customerName']."','".$_POST['firstDay']."');
insert into IDC (name,id,phone,cloudid) VALUES('".$_POST['engName3']."','".$_POST['engID3']."','".$_POST['engPhone3']."',LAST_INSERT_ID());
insert into IDC (name,id,phone,cloudid) VALUES('".$_POST['engName4']."','".$_POST['engID4']."','".$_POST['engPhone4']."',LAST_INSERT_ID());
";
$stmt=$conn->query($query);
//$conn->commit();
echo "success";
}
catch(PDOException $e)
{
$conn->rollBack();
echo "connect failed!".$e->getMesage();
exit;
}
}
?>
Transactions are only available when the database uses InnoDB as the storage engine. You are probably using MyISAM
Have a look here for more details on the difference between the storage engines https://dev.mysql.com/doc/refman/5.7/en/storage-engines.html
As a side note, your code is vulnerable to SQL injections because you use raw post data in non prepared queries. you should have a look there : How can I prevent SQL injection in PHP?
Try to initiate your connection and get last inserted id like below, also i would recommend you to use prepared statements (see http://php.net/manual/ru/pdo.prepare.php):
if($_GET["act"]=="add")
{
try {
$dbh = new PDO('mysql:host=localhost;port=3306;dbname=xxx', 'root', 'xxx',
array(PDO::ATTR_PERSISTENT => true));
echo "Connected\n";
} catch (Exception $e) {
die("Unable to connect: " . $e->getMessage());
}
try {
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->beginTransaction();
$stmt = $dbh->prepare('insert into CLOUD (name,date) VALUES(:customerName,:firstDay)');
$stmt->execute([
'customerName' => $_POST['customerName'],
'firstDay' => $_POST['firstDay']
]);
$cloud_id = $dbh->lastInsertId();
$stmt = $dbh->prepare('insert into IDC (name,id,phone,cloudid) VALUES(:name,:id,:phone,:cloudid)');
$stmt->bindParam(':name', $name);
$stmt->bindParam(':id', $id);
$stmt->bindParam(':phone', $phone);
$stmt->bindParam(':cloudid', $cloud_id);
$name = $_POST['engName3'];
$id = $_POST['engID3'];
$phone = $_POST['engPhone3'];
$stmt->execute();
$name = $_POST['engName4'];
$id = $_POST['engID4'];
$phone = $_POST['engPhone4'];
$stmt->execute();
$dbh->commit();
} catch (PDOException $e) {
$dbh->rollBack();
echo "Failed: " . $e->getMessage();
}
}
I have the following PHP code:
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$insert_query = mysql_query("INSERT INTO articles(articleTitle, articleContent, typeID)
VALUES
('$_POST[articleTitle]','$_POST[articleContent]',$_POST[articleType])");
}
typeID => is number, the other values are text.
There is no error in this code, but the insert query doesn't work (I have no idea why because I don't get any error message).
How can I fix it?
There are a number of problems with your code.
It's open to SQL injectoion
mysql_* functions have been deprecated
This code is untested but should give you an idea:
try
$dbh = new PDO('mysql:host=localhost;dbname=your_database_name', $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sth = $dbh->prepare('INSERT INTO Persons (articleTitle, articleContent, typeID) VALUES (:articleTitle, :articleContent, :articleType)');
$sth->execute($_POST);
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
}
Have a look at this article on Why you Should be using PHP’s PDO for Database Access
Try this
if(isset($_POST[articleTitle])) {
$insert_query = mysqli_query("INSERT INTO Persons (articleTitle, articleContent,typeID)
VALUES
('$_POST[articleTitle]','$_POST[articleContent]',$_POST[articleType])");
}
I have the following SQL query:
UPDATE uploads SET UserName='Test2', UserEmail='Test2', UploadCount='4'
WHERE Country = 'Algeria'
When I run this query via MySQL workbench it executes fine.
I am trying to run this via a website / PHP however, and am attempting to execute the query in the following way:
$sql = "UPDATE uploads SET UserName='$user_data[name]', UserEmail='$user_data[email]', UploadCount='$user_data[FilesUploaded]' WHERE Country = '$country'";
echo $sql;
try
{
$pdo = new PDO('mysql:host=localhost; dbname=db01', $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare($sql);
$stmt->execute();
# Affected Rows?
echo $stmt->rowCount(); // 1
} catch(PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
The SQL query is being built via variables here, however I copy / pasted the echo of $sql into workbench to check that there were no syntax errors creeping in, the echo of $sql is what I pasted above.
When I run it via the web application, I get 0 row affected and the UPDATE is not made, where am I going wrong?
Thank you
UPDATE: A new paramatarized version of the PDO:
$sql = "UPDATE uploads SET ";
$sql .="UserName = :name,
UserEmail = :email,
UploadCount = :FilesUploaded";
$sql .=" WHERE Country = '$country'";
try
{
$pdo = new PDO('mysql:host=localhost; dbname=db01', $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare($sql);
$stmt->bindParam(":name", $user_data['name']);
$stmt->bindParam(":email", $user_data['email']);
$stmt->bindParam(":FilesUploaded", $user_data['FilesUploaded']);
$stmt->execute();
# Affected Rows?
echo $stmt->rowCount(); // 1
} catch(PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
It looks like you're trying to insert information from an array while it's in quotes. Try this:
$sql = "UPDATE uploads SET UserName='".$user_data['name']."', UserEmail='".$user_data['email']."', UploadCount='".$user_data['FilesUploaded']."' WHERE Country = '$country'";
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