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

PHPMySQL Insert Data


Insert Data Into MySQL Using MySQLi and PDO

After a database and a table have been created, we can start adding data in them.

Here are some syntax rules to follow:

  • The SQL query must be quoted in PHP
  • String values inside the SQL query must be quoted
  • Numeric values must not be quoted
  • The word NULL must not be quoted

The INSERT INTO statement is used to add new records to a MySQL table:

INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)

To learn more about SQL, please visit ourSQL tutorial.

In the previous chapter we created an empty table named "MyGuests" with five columns: "id", "firstname", "lastname", "email" and "reg_date". Now, let us fill the table with data.

Note: If a column is AUTO_INCREMENT (like the "id" column) or TIMESTAMP with default update of current_timesamp (like the "reg_date" column), it is no need to be specified in the SQL query; MySQL will automatically add the value.

The following examples add a new record to the "MyGuests" table:

Example (MySQLi Object-oriented)

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

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";

if ($conn->query($sql) === TRUE) {
  echo "New record created successfully";
} else {
  echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>



Example (MySQLi Procedural)

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

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
  die("Connection failed: " . mysqli_connect_error());
}

$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";

if (mysqli_query($conn, $sql)) {
  echo "New record created successfully";
} else {
  echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

mysqli_close($conn);
?>

Example (PDO)

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

try {
  $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
  // set the PDO error mode to exception
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  $sql = "INSERT INTO MyGuests (firstname, lastname, email)
  VALUES ('John', 'Doe', 'john@example.com')";
  // use exec() because no results are returned
  $conn->exec($sql);
  echo "New record created successfully";
} catch(PDOException $e) {
  echo $sql . "<br>" . $e->getMessage();
}

$conn = null;
?>



×

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