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.
Related
I'm trying to use Firebird in my PHP application. I already managed to make interbase and Firebird PDO extensions work, and the connection is established without any problems.
But when I try to make a simple select into one of the tables (select * from filial), it always returns empty, just like there's nothing recorded in the table.
I already tested my script in another database, and it worked properly, so I guess it's not a PHP problem, but I think it has something with my database.
This is how I created the database and table with ISQL:
create database 'C:\My\Database\Path.fdb' page_size 4096 user 'myuser' password 'mypass' default character set UTF8;
connect 'C:\My\Database\Path.fdb' user 'myuser' password 'mypass';
create table filial (id int not null primary key, nome varchar(45));
insert into filial (id, nome) values (1, 'test');
When I run the 'select' query in ISQL, it returns the one inserted row. But doing it with interbase or PDO, I get an empty object.
I also tried using capital letters for the table and columns names.
What am I doing wrong?
I'm running this project in a Windows 7, with WAMP and Firebird server installed.
Interbase PHP code:
$db_server = 'localhost';
$db_user = 'SYSDBA';
$db_passw = 'masterkey';
$db_name = 'C:\Users\Joao\Firebirds\Desenvolvimento.fdb';
$host = $db_server.':'.$db_name;
$dbh = ibase_connect($host, $db_user, $db_passw);
$stmt = 'select * from filial';
$sth = ibase_query($dbh, $stmt);
while ($row = ibase_fetch_object($sth)) {
echo $row->ID.'<br />';
}
ibase_free_result($sth);
ibase_close($dbh);
PDO PHP code:
$db_server = 'localhost';
$db_user = 'SYSDBA';
$db_passw = 'masterkey';
$db_name = 'C:\Users\Joao\Firebirds\Desenvolvimento.fdb';
$str_conn='firebird:host='.$db_server.';dbname='.$db_name;
$conn = new PDO($str_conn, $db_user, $db_passw);
$q = $conn->prepare('SELECT * FROM filial;');
$q->execute();
$dados = $q->fetchAll(PDO::FETCH_OBJ);
foreach($dados as $row){
echo $row->ID.'<br/>';
}
As I'm working locally, I also put connection data.
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
How to add a new column in MySQL using PHP? I tried to do it many hours, but I can not solve my issue. Code:
<?php
$DB_HOST = "localhost";
$DB_USER = "xxxxxx";
$DB_PASSWORD = "xxxxxx";
$DB_NAME = "xxxxxx";
$connect = mysql_connect($DB_HOST,$DB_USER,$DB_PASSWORD);
$db="test_table";
if (! $connect)
die(mysql_error());
mysql_select_db($db , $connect) or die("Select Error: ".mysql_error());
$result=mysql_query("ALTER TABLE id
ADD street VARCHAR(30) AFTER birthday,
Add city VARCHAR(30) AFTER street,
ADD state VARCHAR(4) AFTER city,
ADD zipcode VARCHAR(20) AFTER state,
ADD phone VARCHAR(20) AFTER zipcode") or die("Alter Error: ".mysql_error());
mysql_close($connect);
print "Field added";
?>
When I test this code an error appears:
Select Error: Access denied for user 'xxxxxxxxxxxx'#'localhost' to database 'test_table'
How can I do that?
First be sure your user has the right privileges as described in this so question here
Probably need to run some mysql like this:
GRANT ALTER ON example_table TO 'someuser'#'somehost';
Then similar code to the following should work.
<?php
$db = new mysqli('localhost','USERNAME','PASSWORD','DATABASENAME');
$sql = '
ALTER TABLE id
ADD street VARCHAR(30) AFTER birthday,
Add city VARCHAR(30) AFTER street,
ADD state VARCHAR(4) AFTER city,
ADD zipcode VARCHAR(20) AFTER state,
ADD phone VARCHAR(20) AFTER zipcode';
try {
$r = $db->prepare($sql);
$r->execute();
}
catch(Exception $e) {
error_log(print_r($e->getMessage(),1).' '.__FILE__.' '.__LINE__, 0);
}
Your MySQL user do not have access to your database, but you can connect to your MySQL server (it gives back an error message) and login there.
This means, that the user is not privileged to use your database test_table, please check again the database name (in your example, you give a table name, make sure you are using the database name and not a table name!). Also, you can try it with root account, if it is your server.
This is not a problem of your code but of authentification. Make sure you use the correct information.
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.
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.