Why did the transaction that contained DDL statement throw an exception? - php

For example
$conn = new PDO("mysql:host=127.0.0.1;dbname=test", 'root', '123456');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->beginTransaction();
try {
$sql = "CREATE TABLE IF NOT EXISTS test2 (
`id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
`text` varchar(32) NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;";
$conn->exec($sql);
$conn->commit();
} catch (\Exception $e) {
$conn->rollBack();
}
It works fine in PHP 7.4, but it does not work in PHP 8.0 and throws an exception on line $conn->commit();:
PDOException: There is no active transaction

This is due to this PDO change
https://github.com/php/php-src/commit/7b9519a792a04d6943ff7082ff343a96ec00157f#diff-9a6d6a4359a98668fef29400492f877938424d1b1d2e84933c91ab34161cf360

Related

How to execute a SQL file on a MySQL database using PDO?

I want to create the database from .sql file but I do not know how to do it. Is it possible to do that?
file connect database PDO
<?php
require "db.sql";
$dsn = "mysql:host=localhost;dbname=DBNAME;charset=utf8";
$user= 'root';
$pass= '';
try {
$connect = new PDO($dsn, $user, $pass);
$connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$connect->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
} catch (PDOException $e) {
echo " error ,not connected data base :".$e->getMessage();
}
file db.sql
CREATE DATABASE IF NOT EXISTS DBNAME;
CREATE TABLE `nameTable` (
`id` int(11) NOT NULL AUTO_INCREMENT ,
PRIMARY KEY (`id`),
`pseudo` varchar(35) NOT NULL,
`password` varchar(255) NOT NULL,
`nameWebsite` varchar(255) NOT NULL DEFAULT 'xxxx'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `nameTable` (`id`, `pseudo`, `password`) VALUES
(1, 'admin', 'admin');

Create table with PDO

I get this error:
Uncaught Error: Call to undefined method PDO::execute()
My code:
<?php
session_start();
require("../connecting-to-database.php");
$query = "CREATE TABLE `classes`(
`ID_class` int(11),
`name` varchar(255),
PRIMARY KEY(`ID_class`))";
$pdo->execute($query);
What is my problem?
Execute is for prepared statements not executing directly.
Also don't forget to catch your exception.
Try the following:
<?php
session_start();
require("../connecting-to-database.php");
try {
$query = $pdo->prepare("CREATE TABLE `classes`(
`ID_class` int(11),
`name` varchar(255),
PRIMARY KEY(`ID_class`))");
$query->execute();
}
catch (PDOException $e) {
echo $e->getMessage();
}

PHP PDO, connecting to database/selecting database + execute

This is my code http://prntscr.com/a2d8qq currently, I am learning things but I am really wondering why it will say that there is no database selected, tho I have selected it in line 5, also if I remove the "dbname = users_details" and then execute a query that creates a databse then it is fine. But whenever I create a table in that database (I selected it) it will not make me, I searched across google and it really is the same to my code but mine will not work.
<?php
try {
$connect = new PDO("mysql: host = 'localhost'; dbname = users_details", 'root', '');
$connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sqlQuery = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";
$connect->exec($sqlQuery);
echo 'Successfully created table.';
}
catch(PDOException $e) {
echo $e->getMessage();
}
?>
So this fixed my problem: I have to execute a query to use a specified database into where I want my tables to be in. Then in the line 5 I have just removed the "dbname =
<?php
try {
$connect = new PDO("mysql: host = 'localhost';", 'root', '');
$connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sqlQuery = "CREATE TABLE details (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";
$connect->exec("use users_details");
$connect->exec($sqlQuery);
echo 'Successfully created table.';
}
catch(PDOException $e) {
echo $e->getMessage();
}
?>

PHP PDO::lastInsertId() returns 0

Thanks in advance for reading this, I couldn't find an answer that solved my problem... I don't understand what I'm doing differently than the tutorials/suggestions I found:
SQL Table
CREATE TABLE IF NOT EXISTS `LastInsertID` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` char(150) NOT NULL,
`email` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=6 ;
PHP File
<?php
// Connect to database
$user = "foo";
$pswd = "bar";
$db = new PDO( 'mysql:host=localhost;dbname=test', $user, $pswd );
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Prepare request
$rq = $db->prepare('INSERT INTO `LastInsertID` VALUES(NULL,:name,:email)');
// Begin and commit request
$db->beginTransaction();
$values = array('name'=>'Foo','email'=>'bar#baz.com');
$rq->execute($values);
$db->commit();
// Echo last ID
echo $db->lastInsertId();
?>
This returns 0 when it should return 6. Where is the problem?
You must use $db->lastInsertId() before you commit if you are in a transaction. Even if you rollback a transaction, the id is "used" or skipped, which is why you should not depend on IDs to be sequential.
Use this
INSERT INTO `LastInsertID` (name, email) VALUES(:name,:email)
instead
INSERT INTO `LastInsertID` VALUES(NULL,:name,:email)
I have removed the NULL.

mysql_insert_id() 0, but insert is done successfully

this is table schema:
CREATE TABLE `USERS` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`email` varchar(30) DEFAULT '',
`first_name` varchar(15) DEFAULT '',
`last_name` varchar(15) DEFAULT '',
`password` varchar(15) DEFAULT '',
`gender` int(1) DEFAULT '-1',
PRIMARY KEY (`id`)
)
in php:
$sql = 'INSERT INTO Users (email, first_Name, last_Name, password, gender ) VALUES ("'.$email.'", "'.$first_name.'", "'.$last_name.'", "'.$password.'", '.$gender.')';
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->execute();
//$user = $stmt->fetchObject();
echo 'last id was '.mysql_insert_id();
$db = null;
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
I can't figure out why mysql_insert_id() returns 0. there are no other processes running. id is set to auto increment. Insert is done and seen in db.
You are using PDO to interface with the database. Use PDO::lastInsertId() to get the last inserted id.
$stmt->execute();
echo 'last id was ' . $db->lastInsertId();
mysql_insert_id() is part of the ext/mysql extension. You cannot mix-match functions from both extensions to interface with the same connection.

Categories