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

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');

Related

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

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

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();
}
?>

Mysql query create table does not works by php

I'm trying to copy 2 tables structures into a new database.
I use a function that makes by herself the SQL command: When i execute the code on phpmyadmin the code gets executed but when I execute this by PHP, it doesn't execute.
How is possible?
The sql command is this:
CREATE TABLE `tabella_1` (
`campo1` int(11) NOT NULL AUTO_INCREMENT,
`campo2` varchar(100) COLLATE latin1_general_ci NOT NULL,
`campo_3` int(11) NOT NULL,
PRIMARY KEY (`campo1`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;
CREATE TABLE `tabella_2` (
`campo1` int(11) NOT NULL DEFAULT '0',
`campo2` varchar(100) COLLATE latin1_general_ci NOT NULL,
`campo_3` int(11) NOT NULL,
PRIMARY KEY (`campo1`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;
Thanks
Update this code with your database connection details:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// sql to create table
$sql = "CREATE TABLE `tabella_1` ( `campo1` int(11) NOT NULL AUTO_INCREMENT, `campo2` varchar(100) COLLATE latin1_general_ci NOT NULL, `campo_3` int(11) NOT NULL, PRIMARY KEY (`campo1`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci";
if ($conn->query($sql) === TRUE) {
echo "Table 1 created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
// sql to create table
$sql2 = "CREATE TABLE `tabella_2` ( `campo1` int(11) NOT NULL DEFAULT '0', `campo2` varchar(100) COLLATE latin1_general_ci NOT NULL, `campo_3` int(11) NOT NULL, PRIMARY KEY (`campo1`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci";
if ($conn->query($sql2) === TRUE) {
echo "Table 2 created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
$conn->close();
?>
I got it!
I putted in a array() the functions and it works!
Tkanks to everybody!

Error performing sql query in PHP

I am trying to learn using mysql in php. I started off trying to create a table in mysql, and using the mysqli extension.
My code:
<?php
$truemsg = "Table created successfully";
$falsemsg = "Error creating table: ";
$servername = "localhost";
$username = "myuser";
$password = "mypass";
$db = "mytable";
// Create database
$sql = "USE ".$db.";".
'CREATE TABLE IF NOT EXISTS Authentication (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
userid VARCHAR(30) NOT NULL,
password VARCHAR(30) NOT NULL,
role VARCHAR(20) NOT NULL,
email VARCHAR(50)
);';
print "Sql command is ".$sql;
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
print "<p></p>";
if ($conn->query($sql) === TRUE) {
echo $truemsg;
} else {
echo $falsemsg . $conn->error;
}
$conn->close();
?>
The error is:
Sql command is USE mytable;CREATE TABLE IF NOT EXISTS Authentication ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, userid VARCHAR(30) NOT NULL, password VARCHAR(30) NOT NULL, role VARCHAR(20) NOT NULL, email VARCHAR(50) );
Error creating table: 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 'CREATE TABLE IF NOT EXISTS Authentication ( id INT(6) UNSIGNED AUTO_INCREMENT PR' at line 1
I tried pasting the same command on the mysql command line, and it works fine. What's the problem using this in php?
You are supposed to run queries one by one
$sql = "query one";
$conn->query($sql);
$sql = 'query two';
$conn->query($sql);
instead of coupling them all in one statement.
DO NOT use mysqi_multi_query() either, this asynchronous function is not intended for the everyday use.
Also, in this particular case USE query is superfluous. Database should go into constructor:
$conn = new mysqli($servername, $username, $password, $db);
^^^ here
Also, tell mysqli to throw errors by itself, automatically, instead of checking result of every database command manually:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
This way you will get neat and clean code:
<?php
$servername = "localhost";
$username = "myuser";
$password = "mypass";
$db = "mytable";
// Create data table
$sql = 'CREATE TABLE IF NOT EXISTS Authentication (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
userid VARCHAR(30) NOT NULL,
password VARCHAR(30) NOT NULL,
role VARCHAR(20) NOT NULL,
email VARCHAR(50)
)';
// Create connection
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli($servername, $username, $password, $db);
// Run a query
$conn->query($sql);
echo "Table created successfully";
This code will either report that table has been created successfully, or emit an error, with a detailed explanation on what went wrong.
This seems to be like a mysql multiple query problem
$conn->select_db($db);
you can use this function before the query to use the database and remove the use database statement from your query string , then you query string becomes
$sql = 'CREATE TABLE IF NOT EXISTS Authentication (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
userid VARCHAR(30) NOT NULL,
password VARCHAR(30) NOT NULL,
role VARCHAR(20) NOT NULL,
email VARCHAR(50)
)';
that may work for you ..

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.

Categories