Home > Backend Development > PHP Tutorial > PHP MySQL creates database and table examples

PHP MySQL creates database and table examples

ringa_lee
Release: 2023-02-28 20:20:02
Original
1256 people have browsed it


  1. //Create database

  2. $con = mysql_connect("localhost","peter","abc123");

  3. if ( !$con)

  4. {

  5. die('Could not connect: ' . mysql_error());

  6. }

  • if (mysql_query("CREATE D ATABASE my_db", $con))

  • { bbs.it-home.org

  • echo "Database created";

  • }

  • else

  • {

  • e cho "Error creating database : " . mysql_error();

  • }

  • mysql_close($con);

  • ?>

  • 2, create table CREATE TABLE is used to create a database table in MySQL.

    Grammar CREATE TABLE table_name ( column_name1 data_type, column_name2 data_type, column_name3 data_type, ....... ) In order to execute this command, I have to add a CREATE TABLE statement to the mysql_query() function.

    Example, create a table named "Persons" with three columns. The column names are "FirstName", "LastName" and "Age":




    1. $ con = mysql_connect("localhost ","peter","abc123");
    2. if (!$con)
    3. {
    4. die('Could not connect: ' . mysql_error());
    5. }
    6. D // Create database
    7. if (mysql_query ("Create DataBase My_db", $ Con) {bbs.it-home.org
  • echo "database created";
  • }
  • else
  • {
  • echo "Error creating database: " . mysql_error();
  • }
  • // Create table in my_db database
  • mysql_select_db ("my_db", $con);
  • $sql = "CREATE TABLE Persons
  • (
  • FirstName varchar(15),
  • LastName varchar(15),
  • Age int
  • )";
  • mysql_query($sql,$con);
  • mysql_close($con);
  • ?>
  • Copy code

  • Important: Before creating a table, you must first select the database. Select the database through the mysql_select_db() function.
  • Note: When you create a database field of varchar type, you must specify the maximum length of the field, for example: varchar(15).

    MySQL data types Various MySQL data types:
  • $sql = "CREATE TABLE Persons

  • (
    1. personID int NOT NULL AUTO_INCREMENT,
    2. PRIMARY KEY(personID) ,
    3. FirstName varchar(15),
    4. LastName varchar(15),
    5. Age int
    6. )";
    7. mysql_query($ sql,$con);
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template