How to create a database using PHP and MySQL ?

 

  • Database is a collection of inter-related data which helps in insertion, retrieval and deletion of data from database and organizes the data in the form of views, tables, reports, schemas etc.
  • For example, institute database organizes the data about students, admin, faculty, and staff etc. which helps in insertion, efficient retrieval and deletion of data from it.
  • In MySQL we need to create a database to execute a query.
  • MySQL is an open-source relational database management system and it is distributed, supported and developed by Oracle Corporation.
  • MySQL is a database system that runs on a server and it is ideal for both small and large applications.
  • From PHP script establish a connection to MySQL server.
  • Write a SQL query to create a database and store it in a string variable then execute the queries.
  • Using Object-oriented procedure, we can use the query () function of MySQLi class to execute our query.
  • Using procedural procedure, we can use the mysqli_query () function of PHP to execute our query.
  • Using PDO procedure then we can execute our query.

Sample Code

[pastacode lang=”php” manual=”%3C%3Fphp%0A%24servername%20%3D%20%22localhost%22%3B%0A%24username%20%3D%20%22username%22%3B%0A%24password%20%3D%20%22password%22%3B%0A%0A%2F%2F%20Creating%20a%20connection%0A%24conn%20%3D%20new%20mysqli(%24servername%2C%20%24username%2C%20%24password)%3B%0A%2F%2F%20Check%20connection%0Aif%20(%24conn-%3Econnect_error)%20%7B%0A%20%20%20%20die(%22Connection%20failed%3A%20%22%20.%20%24conn-%3Econnect_error)%3B%0A%7D%20%0A%2F%2F%20Creating%20a%20database%20named%20newDB%0A%24sql%20%3D%20%22CREATE%20DATABASE%20newDB%22%3B%0Aif%20(%24conn-%3Equery(%24sql)%20%3D%3D%3D%20TRUE)%20%7B%0A%20%20%20%20echo%20%22Database%20created%20successfully%20with%20the%20name%20newDB%22%3B%0A%7D%20else%20%7B%0A%20%20%20%20echo%20%22Error%20creating%20database%3A%20%22%20.%20%24conn-%3Eerror%3B%0A%7D%0A%0A%2F%2F%20closing%20connection%0A%24conn-%3Eclose()%3B%0A%3F%3E%0A” message=”” highlight=”” provider=”manual”/]

Output

Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like