- php script automatically creating mysql database?
- Auto create database php
- Создание базы данных
- Создание таблицы
- PHP Create a MySQL Database
- Create a MySQL Database Using MySQLi and PDO
- Example (MySQLi Object-oriented)
- Example (MySQLi Procedural)
- Example (PDO)
- mysql_create_db
- Description
- Parameters
- Return Values
- Examples
- Notes
- See Also
- User Contributed Notes
- Auto Creation of Database Tables and Insertion of Values in PHP Free Source Code
- Sample Code
- Web App Interface Snapshots
- How to Run
- DEMO
- Tags
- Comments
- Thank you for Tutorial
- SQLite Database Setup
- Nice, thanks
- Add new comment
- Share Source Code or Tutorial
php script automatically creating mysql database?
You cannot create a username and password unless you log in yourself with a user with a higher level. That’s usually the root. Creating database is a breeze after using the username and password with sufficient privileges.
query("CREATE USER 'user_name'@'%' IDENTIFIED BY 'pass_word';"); //Creation of database "new_db" $pdo->query("CREATE DATABASE `new_db`;"); //Adding all privileges on our newly created database $pdo->query("GRANT ALL PRIVILEGES on `new_db`.* TO 'user_name'@'%';"); ?>
In this script, I assumed your root user is called «root» and its password is empty if that’s not the case, change line 4 to match.
i think I will already be logged into the server. I plan to install the script with ftp to my website and server, then i would like to create an install.php page to make it easy to create the database. I might not be explaining things correctly.
Your script should not create the database (imho), but the user who wishes to install your application should. Take note of all the larger CMSs and applications, they ask you, the user, for the database name, username and password. However, if you already have a PDO object opened and connected at the time of running the script, feel free to skip the first 2 lines.
you cannot create new user without logging in.
You can create database with root account or user with privileges
you may try this for your problem
i have just been doing this on my project
the actual answer is you can but it’s a little complicated.
Cpanel doesnt allow you to use the normal «CREATE DATABASE ‘mydbname’;» in a php script to create a new database.
the only way you can do it is via logging on to your cpanel, going through the database wizard and creating a new one. Up until now you have probably been doing this manually each time.
this can been done with a php script but you have to use an api — which kind of goes through those same actions but automatically. You have to give the api your cpanel username and cpanel password.
just follow the answer to this question Create cpanel database through php script
Auto create database php
Для выполнения запросов к серверу базы данных у объекта PDO вызывается метод exec() , в который передается выполняемое выражение SQL.
$conn = new PDO("mysql:host=localhost", "root", "mypassword"); $conn->exec(команда_sql);
Создание базы данных
Для создания базы данных применяется SQL-команда CREATE DATABASE , после которой указывается имя создаваемой базы данных.
Создадим базу данных через PHP:
exec($sql); echo "Database has been created"; > catch (PDOException $e) < echo "Database error: " . $e->getMessage(); > ?>
В данном случае после подключения к серверу определяется переменная $sql , которая хранит команду на создание бд с именем «textdb1»:
$sql = "CREATE DATABASE testdb1";
Далее для выполнения этой команды передаем ее в метод exec() :
В итоге при успешном создании базы данных мы увидим в браузере сообщение об создании БД:
Создание таблицы
Подобным образом можно выполнять запросы на создание таблиц в базе данных. Для создания таблиц применяется SQL-команда CREATE TABLE , после которой указывается имя создаваемой таблицы и в скобках определения столбцов.
Так, возьмем выше созданную базу данных «testdb1». И создадим в ней таблицу, которая описывается следующим кодом
CREATE TABLE Users (id INTEGER AUTO_INCREMENT PRIMARY KEY, name VARCHAR(30), age INTEGER);
Здесь создается таблица под названием «users». Она будет хранить условных пользователей. В ней будет три столбца: id, name и age. Столбец id представляет числовой уникальный идентификатор строки — или идентификатор пользователя. Столбец name представляет строку — имя пользователя. А столбец age представляет число — возраст пользователя.
Для создания таблицы определим следующий скрипт php:
exec($sql); echo "Table Users has been created"; > catch (PDOException $e) < echo "Database error: " . $e->getMessage(); > ?>
Обратите внимание, что по сравнению с предыдущим примером здесь в строке подключения указана база данных, в которой создается таблица: «mysql:host=localhost;dbname=testdb1»
И после успешного выполнения запрос мы увидим в браузере сообщение об создании таблицы:
PHP Create a MySQL Database
You will need special CREATE privileges to create or to delete a MySQL database.
Create a MySQL Database Using MySQLi and PDO
The CREATE DATABASE statement is used to create a database in MySQL.
The following examples create a database named «myDB»:
Example (MySQLi Object-oriented)
$servername = «localhost»;
$username = «username»;
$password = «password»;
?php
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) die(«Connection failed: » . $conn->connect_error);
>
// Create database
$sql = «CREATE DATABASE myDB»;
if ($conn->query($sql) === TRUE) echo «Database created successfully»;
> else echo «Error creating database: » . $conn->error;
>
Note: When you create a new database, you must only specify the first three arguments to the mysqli object (servername, username and password).
Tip: If you have to use a specific port, add an empty string for the database-name argument, like this: new mysqli(«localhost», «username», «password», «», port)
Example (MySQLi Procedural)
$servername = «localhost»;
$username = «username»;
$password = «password»;
?php
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) die(«Connection failed: » . mysqli_connect_error());
>
// Create database
$sql = «CREATE DATABASE myDB»;
if (mysqli_query($conn, $sql)) echo «Database created successfully»;
> else echo «Error creating database: » . mysqli_error($conn);
>
Note: The following PDO example create a database named «myDBPDO»:
Example (PDO)
$servername = «localhost»;
$username = «username»;
$password = «password»;
?php
try $conn = new PDO(«mysql:host=$servername», $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = «CREATE DATABASE myDBPDO»;
// use exec() because no results are returned
$conn->exec($sql);
echo «Database created successfully
«;
> catch(PDOException $e) echo $sql . «
» . $e->getMessage();
>
Tip: A great benefit of PDO is that it has exception class to handle any problems that may occur in our database queries. If an exception is thrown within the try < >block, the script stops executing and flows directly to the first catch() < >block. In the catch block above we echo the SQL statement and the generated error message.
mysql_create_db
This function was deprecated in PHP 4.3.0, and it and the entire original MySQL extension was removed in PHP 7.0.0. Instead, use either the actively developed MySQLi or PDO_MySQL extensions. See also the MySQL: choosing an API guide. Alternatives to this function include:
Description
mysql_create_db() attempts to create a new database on the server associated with the specified link identifier.
Parameters
The name of the database being created.
The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() had been called with no arguments. If no connection is found or established, an E_WARNING level error is generated.
Return Values
Returns true on success or false on failure.
Examples
Example #1 mysql_create_db() alternative example
The function mysql_create_db() is deprecated. It is preferable to use mysql_query() to issue an sql CREATE DATABASE statement instead.
$link = mysql_connect ( ‘localhost’ , ‘mysql_user’ , ‘mysql_password’ );
if (! $link ) die( ‘Could not connect: ‘ . mysql_error ());
>
?php
$sql = ‘CREATE DATABASE my_db’ ;
if ( mysql_query ( $sql , $link )) echo «Database my_db created successfully\n» ;
> else echo ‘Error creating database: ‘ . mysql_error () . «\n» ;
>
?>
The above example will output something similar to:
Database my_db created successfully
Notes
Note:
For backward compatibility, the following deprecated alias may be used: mysql_createdb()
Note:
This function will not be available if the MySQL extension was built against a MySQL 4.x client library.
See Also
User Contributed Notes
- MySQL Functions
- mysql_affected_rows
- mysql_client_encoding
- mysql_close
- mysql_connect
- mysql_create_db
- mysql_data_seek
- mysql_db_name
- mysql_db_query
- mysql_drop_db
- mysql_errno
- mysql_error
- mysql_escape_string
- mysql_fetch_array
- mysql_fetch_assoc
- mysql_fetch_field
- mysql_fetch_lengths
- mysql_fetch_object
- mysql_fetch_row
- mysql_field_flags
- mysql_field_len
- mysql_field_name
- mysql_field_seek
- mysql_field_table
- mysql_field_type
- mysql_free_result
- mysql_get_client_info
- mysql_get_host_info
- mysql_get_proto_info
- mysql_get_server_info
- mysql_info
- mysql_insert_id
- mysql_list_dbs
- mysql_list_fields
- mysql_list_processes
- mysql_list_tables
- mysql_num_fields
- mysql_num_rows
- mysql_pconnect
- mysql_ping
- mysql_query
- mysql_real_escape_string
- mysql_result
- mysql_select_db
- mysql_set_charset
- mysql_stat
- mysql_tablename
- mysql_thread_id
- mysql_unbuffered_query
Auto Creation of Database Tables and Insertion of Values in PHP Free Source Code
Hello! Greetings from Malawi the Warm Heart Of Africa. This is a simple demo project I just want to share with you so that you can learn how you create databases and tables automatically when the index.php or home.php is initiated. In this web application, the database data/tables will be automatically created when the application has been initiated or browse for the first time. In that case, you will learn how to create a web application that can be easy to deploy to a server.
Creating a simple file with your database creation script as well as tables has a number of advantages such as the following:
- You don’t have to export/import the database every time you want to share a project folder
- It is easy to make changes to the database tables during development
- Your database is always safe in case the server has been uninstalled from your machine
This project you will also learn how to insert data into tables using modal forms because they are awesome and make your system standout.
Sample Code
The code above is the database connection script that automatically created the database, tables, and columns if not existing yet. Below image is the result of the above script.
Web App Interface Snapshots
Subject Table Modal Form for Insertion
How to Run
- Download and Install any local web server such as XAMPP/WAMP.
- Download the provided source code zip file. (download button is located below)
- Open your XAMPP/WAMP’s Control Panel and start the Apache and MySQL .
- Extract the downloaded source code zip file.
- If you are using XAMPP, copy the extracted source code folder and paste it into the XAMPP’s «htdocs» directory. And If you are using WAMP, paste it into the «www» directory.
- Browse the Web App in a browser. i.e. http://localhost/Auto_Database_Creation .
DEMO
If you have any questions regarding this project or anything find me onwww.patrickmvuma.com and if you have a website that you own and you would love to know how many people visit your website per day use my web application on this address https://websitelistener.com
Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.
Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.
FOR YOUR OWN SAFETY, PLEASE:
1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe’s, .ocx’s, .dll’s etc.)—only run source code.Tags
Comments
Thank you for Tutorial
Very informative script. Makes it very easy to setup the database. How about doing same tutorial for SQLite? Thanks for sharing! Susan
SQLite Database Setup
Nice, thanks
Add new comment
Share Source Code or Tutorial
Do you have source code, articles, tutorials or thesis to share? Submit it here by clicking the link below