Movatterモバイル変換


[0]ホーム

URL:


Menu
×
See More 
Sign In
+1 Get Certified Upgrade For Teachers Spaces Get Certified Upgrade For Teachers Spaces
   ❮     
     ❯   

PHP Tutorial

PHP HOMEPHP IntroPHP InstallPHP SyntaxPHP CommentsPHP VariablesPHP Echo / PrintPHP Data TypesPHP StringsPHP NumbersPHP CastingPHP MathPHP ConstantsPHP Magic ConstantsPHP OperatorsPHP If...Else...ElseifPHP SwitchPHP LoopsPHP FunctionsPHP ArraysPHP SuperglobalsPHP RegEx

PHP Forms

PHP Form HandlingPHP Form ValidationPHP Form RequiredPHP Form URL/E-mailPHP Form Complete

PHP Advanced

PHP Date and TimePHP IncludePHP File HandlingPHP File Open/ReadPHP File Create/WritePHP File UploadPHP CookiesPHP SessionsPHP FiltersPHP Filters AdvancedPHP Callback FunctionsPHP JSONPHP Exceptions

PHP OOP

PHP What is OOPPHP Classes/ObjectsPHP ConstructorPHP DestructorPHP Access ModifiersPHP InheritancePHP ConstantsPHP Abstract ClassesPHP InterfacesPHP TraitsPHP Static MethodsPHP Static PropertiesPHP NamespacesPHP Iterables

MySQL Database

MySQL DatabaseMySQL ConnectMySQL Create DBMySQL Create TableMySQL Insert DataMySQL Get Last IDMySQL Insert MultipleMySQL PreparedMySQL Select DataMySQL WhereMySQL Order ByMySQL Delete DataMySQL Update DataMySQL Limit Data

PHP XML

PHP XML ParsersPHP SimpleXML ParserPHP SimpleXML - GetPHP XML ExpatPHP XML DOM

PHP - AJAX

AJAX IntroAJAX PHPAJAX DatabaseAJAX XMLAJAX Live SearchAJAX Poll

PHP Examples

PHP ExamplesPHP CompilerPHP QuizPHP ExercisesPHP ServerPHP SyllabusPHP Study PlanPHP Certificate

PHP Reference

PHP OverviewPHP Array
array()array_change_key_case()array_chunk()array_column()array_combine()array_count_values()array_diff()array_diff_assoc()array_diff_key()array_diff_uassoc()array_diff_ukey()array_fill()array_fill_keys()array_filter()array_flip()array_intersect()array_intersect_assoc()array_intersect_key()array_intersect_uassoc()array_intersect_ukey()array_key_exists()array_keys()array_map()array_merge()array_merge_recursive()array_multisort()array_pad()array_pop()array_product()array_push()array_rand()array_reduce()array_replace()array_replace_recursive()array_reverse()array_search()array_shift()array_slice()array_splice()array_sum()array_udiff()array_udiff_assoc()array_udiff_uassoc()array_uintersect()array_uintersect_assoc()array_uintersect_uassoc()array_unique()array_unshift()array_values()array_walk()array_walk_recursive()arsort()asort()compact()count()current()each()end()extract()in_array()key()krsort()ksort()list()natcasesort()natsort()next()pos()prev()range()reset()rsort()shuffle()sizeof()sort()uasort()uksort()usort()
PHP CalendarPHP Date
checkdate()date_add()date_create_from_format()date_create()date_date_set()date_default_timezone_get()date_default_timezone_set()date_diff()date_format()date_get_last_errors()date_interval_create_from_date_string()date_interval_format()date_isodate_set()date_modify()date_offset_get()date_parse_from_format()date_parse()date_sub()date_sun_info()date_sunrise()date_sunset()date_time_set()date_timestamp_get()date_timestamp_set()date_timezone_get()date_timezone_set()date()getdate()gettimeofday()gmdate()gmmktime()gmstrftime()idate()localtime()microtime()mktime()strftime()strptime()strtotime()time()timezone_abbreviations_list()timezone_identifiers_list()timezone_location_get()timezone_name_from_abbr()timezone_name_get()timezone_offset_get()timezone_open()timezone_transitions_get()timezone_version_get()
PHP DirectoryPHP ErrorPHP ExceptionPHP Filesystem
basename()chgrp()chmod()chown()clearstatcache()copy()delete()dirname()disk_free_space()disk_total_space()diskfreespace()fclose()feof()fflush()fgetc()fgetcsv()fgets()fgetss()file()file_exists()file_get_contents()file_put_contents()fileatime()filectime()filegroup()fileinode()filemtime()fileowner()fileperms()filesize()filetype()flock()fnmatch()fopen()fpassthru()fputcsv()fputs()fread()fscanf()fseek()fstat()ftell()ftruncate()fwrite()glob()is_dir()is_executable()is_file()is_link()is_readable()is_uploaded_file()is_writable()is_writeable()lchgrp()lchown()link()linkinfo()lstat()mkdir()move_uploaded_file()parse_ini_file()parse_ini_string()pathinfo()pclose()popen()readfile()readlink()realpath()realpath_cache_get()realpath_cache_size()rename()rewind()rmdir()set_file_buffer()stat()symlink()tempnam()tmpfile()touch()umask()unlink()
PHP FilterPHP FTPPHP JSONPHP KeywordsPHP LibxmlPHP MailPHP MathPHP MiscPHP MySQLiPHP NetworkPHP Output ControlPHP RegExPHP SimpleXMLPHP StreamPHP String
addcslashes()addslashes()bin2hex()chop()chr()chunk_split()convert_cyr_string()convert_uudecode()convert_uuencode()count_chars()crc32()crypt()echo()explode()fprint()get_html_translation_table()hebrev()hebrevc()hex2bin()html_entity_decode()htmlentities()htmlspecialchars_decode()htmlspecialchars()implode()join()lcfirst()levenshtein()localeconv()ltrim()md5()md5_file()metaphone()money_format()nl_langinfo()nl2br()number_format()ord()parse_str()print()printf()quoted_printable_decode()quoted_printable_encode()quotemeta()rtrim()setlocale()sha1()sha1_file()similar_text()soundex()sprintf()sscanf()str_getcsv()str_ireplace()str_pad()str_repeat()str_replace()str_rot13()str_shuffle()str_split()str_word_count()strcasecmp()strchr()strcmp()strcoll()strcspn()strip_tags()stripcslashes()stripslashes()stripos()stristr()strlen()strnatcasecmp()strnatcmp()strncasecmp()strncmp()strpbrk()strpos()strrchr()strrev()strripos()strrpos()strspn()strstr()strtok()strtolower()strtoupper()strtr()substr()substr_compare()substr_count()substr_replace()trim()ucfirst()ucwords()vfprintf()vprintf()vsprintf()wordwrap()
PHP Variable HandlingPHP XML ParserPHP ZipPHP Timezones

PHPCreate a MySQL Database


A database consists of one or more tables.

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)

<?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);
}

// Create database
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
  echo "Database created successfully";
} else {
  echo "Error creating database: " . $conn->error;
}

$conn->close();
?>

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)

<?php
$servername = "localhost";
$username = "username";
$password = "password";

// 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);
}

mysqli_close($conn);
?>

Note: The following PDO example create a database named "myDBPDO":

Example (PDO)

<?php
$servername = "localhost";
$username = "username";
$password = "password";

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<br>";
} catch(PDOException $e) {
  echo $sql . "<br>" . $e->getMessage();
}

$conn = null;
?>

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.



×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness
of all content. While using W3Schools, you agree to have read and accepted ourterms of use,cookies andprivacy policy.

Copyright 1999-2025 by Refsnes Data. All Rights Reserved.W3Schools is Powered by W3.CSS.


[8]ページ先頭

©2009-2025 Movatter.jp