Database table is not created using PHP - 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

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){

How to connect to a new database using PHP MySQL

So I've been trying to learn how to use MySQL with PHP, and I've managed to create a connection and create a database along with a table. What I don't know how to do is create the database along with the tables all in one go.
What I mean by this is easier shown in my code (Which will show unable to connect error message because the connect method is trying to connect to a database that does not exist.
<?php
$servername = isset($_POST["servername"]) ? $_POST["servername"] : '';
$username = $_POST["username"];
$password = $_POST["password"];
$dbname = $_POST["dbname"];
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Create database
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}
// sql to create table
$sql = "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
)";
if (mysqli_query($conn, $sql)) {
echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
So, all I am trying to achieve is Connect to MySQL, create the database, create a table for said database and close the connection all within one .php file.
On a side note, due to the user being able to define a database name ($dbname), how would I add this value into the MySQL code above? I heard somewhere that you're supposed to add the variable into quotes? So '$dbname'. Any help with that would be good too! Thanks in advance!
Okay, the reason for this question is because I am creating a setup-type page where the user will be able to connect to their own database, allowing them to give it a name and connect using their credentials. Obviously I am not very experienced within this field, I hope I have explained it better.
All the code you have looks fine to me. The only thing I think your missing is after you create a database you have to call
$conn->select_db("myDB");
Also if you want to have the database name be $dbname then
$sql = "CREATE DATABASE myDB";
should be
$sql = "CREATE DATABASE " . $dbname;
If I didn't cover your problem please give me more detail on your problem.
where you passing all of this variable ?
$servername = isset($_POST["servername"]) ? $_POST["servername"] : '';
$username = $_POST["username"];
$password = $_POST["password"];
$dbname = $_POST["dbname"];
just simply hardcode the servername, username, password and your dbname.

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.

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

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.

Roleback CREATE TABLE using MySql Transactions

I'm writing a upgrader for a mysql database using PHP. The behavior of the upgrader should be as follows.
If all the queries executed successfully the changes should be committed.
If a sinngle query get faild eveything should be roled back to previouse state.
Part of my program is as follows.
$host = 'localhost';
$user = 'root';
$password = 'root';
$db = 'transaction';
$con = mysqli_connect($host, $user, $password);
mysqli_select_db($con, $db);
mysqli_autocommit($con, FALSE);
$query1 = "create table `status` (
`id` int not null auto_increment,
`name` varchar(60) not null,
primary key (`id`)
) engine=innodb default charset=utf8;";
$result1 = mysqli_query($con, $query1);
$query2 = "ALTER TABLE status
CHANGE name value varchar(512);";
$result2 = mysqli_query($con, $query2);
if(!($result1 && $result2)) {
mysqli_rollback($con);
} else {
mysqli_commit($con);
}
mysqli_close($con);
But if the 'status' table already exists the first create table query is failing. So both queries should be rolled back. But the alter query has executed and not rolled back.
I saw a post which list all the queries which cannot be rolled back in mysql. http://www.sitepoint.com/mysql-transaction-gotchas-good-parts/
Is there any possible way to do this role back in mysql.
No. You would need to run a new alter table query undoing your previous alter statement.
do it manualy
if(!($result1 && $result2)) {
#drop table
$query1 = "drop table `status`";
$result = mysqli_query($con, $query1);
}
Would it be better to just export the data into (say) a collection of CSV files. Then modify any dataif needed to match the new structure. Then just create the database with the new structure and import the data into it.
Seems a simpler solution that trying to make an upgrader.

Categories