PhP PDO exec() doesn`t creates tables [duplicate] - php

This question already has answers here:
Reference — frequently asked questions about PDO
(3 answers)
Closed 8 years ago.
I am new to PhP , and i am kind of stuck with this problem : i have a database created end when i try to use PDO exec() to create a table nothing happends , no table is created, no error message is displayed .I tryed validating my code online and got no error.Please help.Thanks.
$host = 'localhost';
$db = 'test';
$user = 'root';
$pass = '';
try{
$connect = new PDO("mysql:host = $host ; dbname = $db", $user , $pass);
$sql = "CREATE TABLE IF NOT EXISTS book(
id INT(20) NOT NULL UNSIGNED AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(20) NOT NULL,
autor VARCHAR(20) NOT NULL
)";
$connect->exec($sql);
$connect = null;
}catch(PDOException $e){
$e->getMessage();
}

In your catch block, you're not actually doing anything with the exception message. Try changing
$e->getMessage();
to
echo $e->getMessage();
and see if that shows you any errors.

Related

I can't find what *exactly* the syntax error is in mysql [duplicate]

This question already has answers here:
Why can't I run two mysqli queries? The second one fails [duplicate]
(2 answers)
Closed 4 years ago.
I am creating a simple database and it's table for learning purpose:
This is my php code(script.php)
<?php
$sql = file_get_contents("init.sql");
$servername = "localhost";
$username = "root";
$password = "";
// connect to database
$conn = new mysqli($servername, $username, $password);
if ($conn->connect_error) {
die("Connection error: " . $conn->connect_error);
}
if($conn->query($sql) == True){
echo "Database and Table has been created succesfully!";
}
else {
echo "\nError creating database and table: . $conn->error";
}
?>
And this is mysql file(init.mysql)
CREATE DATABASE test;
USE test;
CREATE TABLE Users (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
date_of_registration TIMESTAMP)
The exact error I am seeing is:-
Error creating database and table: . You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'USE test; CREATE TABLE Users ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY ' at line 2
In my opinion, the code is syntactically correct but as you see I am getting an error
So I am struggling to find where is the error but no luck :(
Or I am blind enough to see it.
To process multiple queries in one call (you have three in your file), you need to use multi_query. Change
if($conn->query($sql) == True){
to
if($conn->multi_query($sql) == True){

PHP Update Data in MySQL using PDO [duplicate]

This question already has answers here:
Sql syntax error using UPDATE database query [closed]
(2 answers)
Closed 7 years ago.
I'm trying to Update Data in MySQL using PDO.
I have set up the code below but get the error
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 '(h1, text) values ('Blah blah' at line 1
if (isset($_POST['Submit']))://if admin wants to edit category
$h1 = $_POST['h1'];
$text = $_POST['text'];
$servername = "localhost";
$username = "user";
$password = "password";
$dbname = "dbname";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Prepare statement
$stmt = $conn->prepare('UPDATE sections (h1, text) values (:h1, :text) WHERE id=1');
$stmt->bindParam(':h1', $h1);
$stmt->bindParam(':text', $text);
// execute the query
$stmt->execute();
// echo a message to say the UPDATE succeeded
echo $stmt->rowCount() . " records UPDATED successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
Update syntax should be:
UPDATE table_name SET `field1` = new-value1, `field2` = new-value2.
Your query should be:
UPDATE sections SET `h1` = :h1, `text` = :text WHERE id = 1;
See the Update query syntax
text is a reserved word in mysql.
Write your query as below:-
UPDATE sections SET `h1` = :h1, `text` = :text WHERE id = 1;

Can't INSERT INTO after creating MySQL table via PHP PDO [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I am fairly new to PDO and MySQL and am running into a weird problem. I've looked in many PDO and MySQL threads but nobody seemed to have this exact problem.
After I create the database, new mysql new user, a table and a few columns, I am unable to use INSERT INTO to populate the database. PDO throws the following Error:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'cms01db.cms_settings' doesn't exist
If I look in PHPMyAdmin, the database exists, the table and columns exist, collation is correct etc. If I then drop the table in PHPMyAdmin and recreate it manually in there, with exactly the same specs, I can use the very same INSERT INTO script and it works just fine.
What am I doing wrong?
Script to create the Database:
// define server and root login
$servername = 'localhost';
$username = 'root';
// define new user for new database and login password
$newUser = 'admin';
$newPass = 'password';
$dbname = 'cms01db';
// create database
try {
// connect to mysql and login
$conn = new PDO("mysql:host=$servername", $username);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// setup command to create database, new user and asign to new database
$sql = "CREATE DATABASE `$dbname` CHARACTER SET ascii COLLATE ascii_general_ci;
CREATE USER '$newUser'#'localhost' IDENTIFIED BY '$newPass';
GRANT ALL ON `$dbname`.* TO '$newUser'#'localhost';
FLUSH PRIVILEGES;";
// use exec() because no results are returned
$conn->exec($sql);
echo "Database created successfully<br>";
}
// if shit goes wrong...
catch(PDOException $e)
{
// display error why
echo $sql . "<br>" . $e->getMessage();
}
// terminate db connection
$conn = null;
Script to create the table and columns:
// login with new user and create database tables & columns
try {
// connect to mysql and login
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $newUser, $newPass);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// sql to create table and columns
$sql = "DROP TABLE IF EXISTS cms_setings;
CREATE TABLE cms_setings (
measurements VARCHAR(1) NOT NULL,
brasizes VARCHAR(3) NOT NULL,
shoesizes VARCHAR(3) NOT NULL
)";
// use exec() because no results are returned
$conn->exec($sql);
echo "CMS Settings Table created successfully<br>";
}
// if shit goes wrong...
catch(PDOException $e)
{
// display error why
echo $sql . "<br>" . $e->getMessage();
}
// terminate db connection
$conn = null;
Script to INSERT INTO:
//prepare variables
//measurements: 'm' for metric, 'i' for inches
$measurements_data = 'i';
//brasizes: 'us' for USA/Canada, 'uk' for UK, 'aus' for Australia, 'eu' for Europe, 'bef' for Belgium/Spain/France
$brasizes_data = 'us';
//shoesizes: 'us' for USA/Canada, 'uk' for UK, 'eu' for Europe, 'jap' for Japan
$shoesizes_data = 'us';
// login and insert data into columns
try {
// connect to mysql and login
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $newUser, $newPass);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// sql to create insert data
$sql = "INSERT INTO cms_settings (measurements,brasizes,shoesizes) VALUES (:measurements,:brasizes,:shoesizes)";
//prepare the statement
$stmt = $conn->prepare($sql);
// execute statement
$stmt->execute(array(':measurements' => $measurements_data,
':brasizes' => $brasizes_data,
':shoesizes' => $shoesizes_data));
echo "CMS Setting Populated Successfully<br>";
}
// if shit goes wrong...
catch(PDOException $e)
{
// display error why
echo $sql . "<br>Error: " . $e->getMessage();
}
// terminate db connection
$conn = null;
In your code you have a misspelling. Change the line
CREATE TABLE cms_setings (
to
CREATE TABLE cms_settings (
Cheers

Database table is not created using PHP

When I try to create a table using PHP, it's not created. But when I try to execute same code in MySQL, it works perfectly.
Here is my code.
$sql = "CREATE TABLE docs_1 (  id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,  date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,  leadid text NOT NULL,  filename text NOT NULL,  title text NOT NULL)";
mysql_query($sql);
There's nothing wrong with your query itself.
The reason may very well be the MySQL library you are using which may be deprecated. Using error reporting will tell you if it is.
Another possible reason could be that you haven't successfully connected to your database. That information hasn't been included in your original post.
Use this mysqli_ method which was tested successfully:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$DB_HOST = 'xxx'; // Replace
$DB_USER = 'xxx'; // with
$DB_PASS = 'xxx'; // your
$DB_NAME = 'xxx'; // own
$db = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($db->connect_errno > 0) {
die('Connection failed [' . $db->connect_error . ']');
}
$sql = "CREATE TABLE docs_1
(id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
leadid text NOT NULL,
filename text NOT NULL,
title text NOT NULL)";
$result = mysqli_query($db,$sql);
if(!$result) {
die('There was an error running the query [' . $db->error . ']');
}
else {
echo "Successful query.";
}
?>
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
It's because date is a predefinied word in MySQL, and you can't use it as a colum's name.
EDIT:
Sry, Fred -ii- has right, it isn't a predefined word, so my answer isn't relevant

Error when creating MySQL Table with PDO

I have just created a MySQL database named "test2" using PDO. Now I'm trying to create a table named "Visiteurs" but it seems my code do not work properly.
The error echoed is:
"SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected"
(which is wrong I think) and my code is the following:
$serveur = "localhost";
$login = "root";
$pass = "root";
try{
$conn = new PDO("mysql:host = $serveur; dbname = test2", $login, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$codesql = "CREATE TABLE Visiteurs (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
nom VARCHAR(50) NOT NULL,
prenom VARCHAR(50) NOT NULL,
email VARCHAR(70)
)";
$conn->exec($codesql);
echo 'Table "Visiteurs" créée !';
}
catch(PDOException $e) {
echo 'Echec : ' . $e->getMessage();
}
Can someone help me find where is the error?
Althout the PDO MySQL DSN string documentation is not specific about whitespace, experience tells me that whitespace is not permitted in a DSN string. Since you have dbname = test2, the dbname is not actually being parsed and used, so PDO complains that no database was selected. Your DSN should look like the following, with no spaces between the key=value pairs:
"mysql:host=$serveur;dbname=test2"
You mentioned in comments that a previous connection succeeded and you were able to issue a CREATE DATABASE statement. That was only due to the coincidence of the default host being localhost and your $serveur variable being set to localhost as well. PDO probably did not parse the host= parameter from the DSN, but instead used localhost as the default connection with your user credentials. Since a CREATE DATABASE statement does not need to have a database selected, the dbname= was irrelevant.

Categories