please, could someone help me what is my mistake? Creating a database works well but when I create a table it makes this SQLSTATE error[3D000]: Invalid catalog name: 1046 No database selected
Here are the codes:
<? php
$server = 'localhost';
$login = 'root';
$password = '';
try{
$connexion = new PDO('mysql:host = $server; dbname=test', $login, $password);
$connexion->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$connexion->exec("CREATE TABLE utilisateur(nom varchar(50))");
echo 'RĂ©ussi';
}
catch(PDOException $e){
echo 'Echec de la connexion : '.$e->getMessage();
}
?>
Just like the error says:
'No database selected'
Before you can create a table you must select which database it's being created in. If you're creating the table manually you'd login to your mysql server, and then in mysql server you'd type this:
USE dbname;
Since you're likely looking to create the table within php you should already have logged into the mysql server under the database you want:
$connexion = new PDO('mysql:host = $server; dbname=test', $login, $password);
If that database does not exist already you need to create it using this command:
CREATE DATABASE dbname;
Related
i am new to working in php, i am work on how to alter table dynamically in database through coding in php
database like this,
database name : data_switch
table name - data
did dataname host dbuser dbpwd dbname
1 abc local root root abc_db // here dataname create new database, when register new dataname
2 pqr ubuntu root passwd pqr_db
php code below:
<?php
$dsn = "localhost";
$username = "root";
$password = "passwd";
$db = new PDO("mysql:host=$dsn;dbname=data_switch", $username, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
foreach ($db->query("select * from data") as $row)
{
$dataname = $row['dataname'];
$host = $row['host'];
$dbuser = $row['dbuser'];
$dbpwd = $row['dbpwd'];
$dbname = $row['dbname'];
$connection_array['data1'][] = array(
'dataname' => $dataname,
'host' => $host,
'dbuser' => $dbuser,
'dbpwd' => $dbpwd,
'dbname' => $dbname
);
}
echo "<pre>";
print_r($connection_array);
$dbh = new PDO("mysql:host=$host;dbname=$dbname", $dbuser, $dbpwd);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// here all dataname find but i dont know how to generate dataname's own connection. dynamically
?>
i am getting all dataname in loop but i am not able to dynamically diffrent connection,i am register new dataname in form as like abc then it create a new database dynamically, but when i am alter the table i am not getting how to connection dynamically on each dataname's host,dbname,dbpwd through each own dataname.
Any body having any idea please help to sort it out. Thanks
I know it's an old post but it came up in a search as a possible relation to a question I had.
I have a script doing very similar to what is being asked. You need to place your connections in a dynamic variable.
eg.
I have a list of branches and their respective database connection details in an array called $branchDcom. I can make calls to all my branches without closing connections and opening all the time.
I have a connection function that connects to a database with the sent values in the function conn_dcom_branch('your_server', 'your_db', 'your_username', 'your_password')
The following creates connections to all databases.
$connection = array();
foreach ($branchDcom as $key => $value) {
$branch = $value['Name'];
if (!is_resource($connections[$branch]['conn'])) {
${'connection_'.$branch} = conn_dcom_branch($value['server'], $value['db'], $value['username'], $value['password']);
${'connection_'.$branch.'_db'} = $value['db'];
}
}
This gives me an array of all branch connections and their respective database names.
To use just enter in the branch name and it will use that connection:
$branch = 'select_name';
$query = "
SELECT
your_field
FROM
[".${'connection_'.$branch.'_db'}."].['table_name']
";
$rs = ${'connection_'.$branch}->execute($query);
This may help someone
This question already has answers here:
Why shouldn't I use mysql_* functions in PHP?
(14 answers)
Closed 5 years ago.
I wonder if someone can help. I gave up web programming about 3 years ago. Since returning to programming about a week ago I realize I have forgotten quite a lot and so much has changed.
I signed on to a deal with php7 but my code is php5 and when I came to running my scripts nothing really works.
For example I couldn't even connect to the database. My database connection file for php5 was
<?php
$db_host = "localhost";
// Place the username for the MySQL database here
$db_username = "db_username_here";
// Place the password for the MySQL database here
$db_pass = "db_password_here";
// Place the name for the MySQL database here
$db_name = "name_of_database_here";
// Run the actual connection here
mysql_connect("$db_host","$db_username","$db_pass") or die ("could not connect to mysql");
mysql_select_db("$db_name") or die ("no database");
?>
I spoke to the server company and they told me everything has changed and to get my code compatible with php7. They then helped me get my database connected by giving me a sample file of how it should be which is this code.
<?
/* DATEBASE CONFIGURATION */
$dbHost = "ip Address";
$dbName = "name_of_database_here"; // Database name
$dbUser = "db_username_here"; // Database user
$dbPasswd = "db_password_here"; // Database password
function dbConnect(){
global $dbHost, $dbUser, $dbPasswd, $dbName;
mysql_connect( $dbHost, $dbUser, $dbPasswd ) or error( mysql_error() );
mysql_select_db( $dbName );
}
?>
I have always run my database $dbHost from localhost so I have guessed that because they haven't done the connection as localhost and done it as gobal with an ip address I have figured that the database is not on the same server as the website.
I then came to my database scripts for running from the browser to phpmyadmin and they also didnt work. Here is my database script php5.
<?php
require "connect_to_mysql.php";
$sqlCommand = "CREATE TABLE admin (
id int(11) NOT NULL auto_increment,
username varchar(24) NOT NULL,
password varchar(24) NOT NULL,
last_log_date date NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY username (username)
) ";
if (mysql_query($sqlCommand)){
echo "Your admin table has been created successfully!";
} else {
echo "CRITICAL ERROR: admin table has not been created.";
}
?>
I was wondering if someone could give me some advice on why the script isn't running
Many thanks, Gary
mysql_connect is removed from php7.
instead of that you can use either mysqli or pdo
example with mysqli
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
example with pdo
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
For more reffer details https://www.w3schools.com/php/php_mysql_connect.asp
I'm using a mysql database. I would like to connect to it with the script i wrote :
<?php
function getDatabase() {
$host = 'localhost:3306';
$db = 'freya';
$login = 'root';
$pw = 'helloitsme';
try {
return new PDO('mysql:host='.$host.';dbname='.$db.';charset=utf8', $login, $pw);
} catch (Exception $e) {
die('Erreur : '.$e->getMessage());
}
}
$db = getDatabase();
I have seen that this error is recurent but none of the solutions worked for.
I checked the my.cnf, and i'm sure that i'm using the port where the mysql db is.
I'm also sure that the db name, the login and the password are correct, because i'm using them to reach the db with the shell.
What could be the problem ?
You don't need to specify the port as 3306 is default for mysql, but if you do, the correct connection string is
'mysql:host=localhost;port=3306 ...'
I have a table on PHPmyamdmin, and when i try to select it with the following code:
*<?php
//connect.php
session_start();
$server = 'localhost';
$username = 'zimmer';
$password = '';
$database = 'csgopit';
if(!mysql_connect($server, $username))
{
exit('Error: could not establish database connection');
}
if(!mysql_select_db($database))
{
exit('Error: could not select the database');
}
?>*
i get this error when i open the page in localhost:
Error: could not select the database
In the database i have 4 tables, one of them is users and i have manually added the user "zimmer" to it, i'm using this to create and experiment forum in my learning experiences, also, using this same code as a "connect.php" if i use it as for example on another file simply by using this line
using connect.php or include connect.php
would it work in a login or would it load only the user zimmer?
I started with PHP couple of days ago so sorry for the rookie question.
Try PDO.
$handler = '';
$server = 'localhost';
$username = 'zimmer';
$password = '';
$database = 'csgopit';
try {
$this->handler = new PDO('mysql:host='. $server .';dbname='. $database . ';charset=utf8', $username, $password);
} catch(PDOException $e) {
echo $e->getMessage();
die();
}
But you also mentioned you added the user "zimmer" to the users table. This is different than your $username you pass to connect to the database.
Did you set up a username and password to a database?
I am trying to have a database created for each user that signs up for my web app. This database will be based on a template to store their data.
The problem I'm running into is that Google Could SQL doesn't seem to be creating the Database via PHP and MySQL queries.
Connecting to the Instance works fine and triggers no errors based on this code:
//CLOUD SQL CONNECTION FOR SUBSCRIPTIONS
$hostname = details;
$username = details;
$password = details;
$port = details;
$socket = details;
$connection = new mysqli($hostname, $username, $password, $port, $socket);
// Check Connection
if($connection->connect_error) {
trigger_error('Connection failed: ' . $connection->connect_error, E_USER_ERROR);
}
However, when I go to create a simple database, mysqli fails without an error...:
//Create Database
$username = 'account';
$database = 'sub_'. $username .'_db';
$query = "CREATE DATABASE IF NOT EXISTS `{$database}`;";
if(mysqli_query($connection, $query)) {
echo "Database my_db created successfully";
} else {
echo "Error creating database: " . mysqli_error($connection);
}
The output of this is simply: Error creating database:
Am I missing something? How do I create a database in a Cloud SQL instance via PHP? Thanks for any input.
Can anyone confirm that this can actually be done on GAE PHP and Cloud SQL?
It seems the $connection variable was actually NULL despite not throwing an error. This worked for me though:
I connected to an existing database:
//CLOUD SQL CONNECTION FOR SUBSCRIPTIONS
$hostname = details;
$username = details;
$password = details;
$db = details;
$port = details;
$socket = details;
$connection = new mysqli($hostname, $username, $password, $db, $port, $socket);
// Check Connection
if($connection->connect_error) {
trigger_error('Connection failed: ' . $connection->connect_error, E_USER_ERROR);
}
Then I created a new database:
//Create Database
$username = 'account';
$database = 'sub_'. $username .'_db';
$query = "CREATE DATABASE IF NOT EXISTS `{$database}`;";
if(mysqli_query($connection, $query)) {
echo "Database my_db created successfully";
} else {
echo "Error creating database: " . mysqli_error($connection);
}
Then used mysqli_select_db() to select the newly created database.
//Select Newly Created DB
mysqli_select_db($connection, $database);