Create table with PDO - php

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

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

PDO prepared statement does nothing [duplicate]

This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed last month.
I am trying to do a simple insert using PDO and a prepared statement but it doesn't insert the data, return an error, or anything. The logs are empty as well. Here is the code that is getting executed but doing nothing. The values are not null.
try {
$query = $this->db_handler->prepare('INSERT INTO submissions (firstname, lastname, email, phone, mailinglist) VALUES (:firstname, :lastname, :email, :phone, :mailinglist);');
$query->bindParam(':firstname', $values['firstname']);
$query->bindParam(':lastname', $values['lastname']);
$query->bindParam(':email', $values['email']);
$query->bindParam(':phone', $values['phone']);
$query->bindParam(':mailinglist', $values['mailinglist']);
$query->execute();
} catch (PDOException $e) {
echo "DB error: " . $e->getMessage();
}
Weirdly, this code is working fine, which is being executed right before the previous code on every request:
try {
$this->exec("CREATE DATABASE IF NOT EXISTS $this->db_name;");
$this->exec("USE $this->db_name;");
$this->exec("CREATE TABLE IF NOT EXISTS $this->table_name (
id INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(50) NOT NULL,
lastname VARCHAR(50) NOT NULL,
email VARCHAR(50) NOT NULL,
phone VARCHAR(12) NOT NULL,
mailinglist BOOLEAN NOT NULL,
submitdate TIMESTAMP
);");
} catch (PDOException $e) {
echo "DB error: " . $e->getMessage();
}
As MarcB pointed out in the comments, I had not been enabling exceptions in PDO. Using db_handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); after instantiating a PDO instance showed that there was an error with the query.
http://php.net/manual/en/pdo.error-handling.php

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

mysqli fatal error: No index used in query/prepared statement

I want to execute a simple prepared Statement using mysqli, but it won't work.
I have this table:
CREATE TABLE IF NOT EXISTS `account` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`email` varchar(100) COLLATE latin1_german2_ci NOT NULL,
`password` varchar(100) COLLATE latin1_german2_ci NOT NULL,
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_german2_ci AUTO_INCREMENT=4 ;
And want to print the id of a specific email.
$mysqli = new mysqli($server,$user,$pass,$db);
if(mysqli_connect_errno()) {
echo "Connection Failed: " . mysqli_connect_errno();
exit();
}
$user = "test#dada.com";
$pass = "dada";
/* Create a prepared statement */
if($stmt = $mysqli -> prepare("SELECT * FROM account WHERE email=?
AND password=?")) {
/* Bind parameters
s - string, b - blob, i - int, etc */
$stmt -> bind_param("ss", $user, $pass);
/* Execute it */
$stmt -> execute();
/* Bind results */
$stmt -> bind_result($result);
/* Fetch the value */
$stmt -> fetch();
echo $user . "id of user is " . $result;
/* Close statement */
$stmt -> close();
}
/* Close connection */
$mysqli -> close();
But i get following Error:
Fatal error: Uncaught exception 'mysqli_sql_exception' with message 'No index used in query/prepared statement SELECT * FROM account WHERE email=? AND password=?' mysqli_stmt->execute() #1 {main}
Your problem is that the query you are executing is going to be inefficient without using an INDEX.
SELECT * FROM account WHERE email=? AND password=?
There's no index on any of the two fields you have used in the WHERE clause. One solution would be to create an index on both fields which should make the error go away.
ALTER TABLE account ADD INDEX `index_on_email_and_password` (email, password);
In many situations, you know that the INDEX is not going to improve the performance, so you can safely ignore this error. To do so, replace the following line of code:
mysqli_report(MYSQLI_REPORT_ALL);
with one of these
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// or
mysqli_report(MYSQLI_REPORT_ALL & ~MYSQLI_REPORT_INDEX);
This will keep on reporting normal SQL errors, but it will ignore all warnings about bad indexes.
Well I think you have to do this:
CREATE TABLE IF NOT EXISTS `account` (
`id` PRIMARY KEY int(11) NOT NULL AUTO_INCREMENT,
// the rest
The above code makes the id field of your table as PRIMARY KEY so it never repeats itself and it remains the index of your table.

Attempting to create a database and table and insert some data

This is what I have so far.... I do not understand why it is not working? Any ideas? This is just a simple script to connect to a database, create a table and insert some data. I also want to retrieve the data but I think I may be jumping a little a head.
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
$link = mysql_connect('localhost', 'root', '');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
if (mysql_query("CREATE_DATABASE nogjhghkgst98", $link))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}
if ($link="CREATE TABLE contactsZ8 (id int(6) NOT NULL auto_increment,first varchar(15) NOT NULL,last varchar(15) NOT NULL,phone varchar(20) NOT NULL,mobile varchar(20) NOT NULL,fax varchar(20) NOT NULL,email varchar(30) NOT NULL,web varchar(30) NOT NULL,PRIMARY KEY (id),UNIQUE id (id),KEY id_2 (id))") {
echo "ineserted";
}
else
{
echo "not inserted" . mysql_error();
}
$link = "INSERT INTO contactsZ VALUES ('','John','Smith','01234 567890','00112 334455','01234 567891','johnsmith#gowansnet.com','http://www.gowansnet.com')";
$link="SELECT * FROM contactsZ";
$link=mysql_query($link);
mysql_close($link);
?>
There is definitely something wrong:
if ($link="CREATE TABLE contactsZ8 (id int(6) NOT NULL auto_increment,first varchar(15) NOT NULL,last varchar(15) NOT NULL,phone varchar(20) NOT NULL,mobile varchar(20) NOT NULL,fax varchar(20) NOT NULL,email varchar(30) NOT NULL,web varchar(30) NOT NULL,PRIMARY KEY (id),UNIQUE id (id),KEY id_2 (id))") {
an assignment in an if
query not executed (that is not so bad: once the table is created, executing again the query when reloading the page will fail)
assigning to $link ! this is confusing (but should not generate any error)...
Then :
$link = "INSERT INTO contactsZ VALUES ('','John','Smith','01234 567890','00112 334455','01234 567891','johnsmith#gowansnet.com','http://www.gowansnet.com')";
The query is not executed.
Edit: the INSERT is done in contactsZ, whereas the CREATE TABLE creates contactsZ8.
Edit2: And finally:
mysql_close($link);
After re-assigning 3 times $link, $link is not the (optional, by the way) link identifier any more...

Categories