[フレーム]

SQL Tutorial

SQL HOME SQL Intro SQL Syntax SQL Select SQL Select Distinct SQL Where SQL Order By SQL And SQL Or SQL Not SQL Insert Into SQL Null Values SQL Update SQL Delete SQL Select Top SQL Aggregate Functions SQL Min() SQL Max() SQL Count() SQL Sum() SQL Avg() SQL Like SQL Wildcards SQL In SQL Between SQL Aliases SQL Joins SQL Inner Join SQL Left Join SQL Right Join SQL Full Join SQL Self Join SQL Union SQL Union All SQL Group By SQL Having SQL Exists SQL Any SQL All SQL Select Into SQL Insert Into Select SQL Case SQL Null Functions SQL Stored Procedures SQL Comments SQL Operators

SQL Database

SQL Create DB SQL Drop DB SQL Backup DB SQL Create Table SQL Drop Table SQL Alter Table SQL Constraints SQL Not Null SQL Unique SQL Primary Key SQL Foreign Key SQL Check SQL Default SQL Create Index SQL Auto Increment SQL Dates SQL Views SQL Injection SQL Parameters SQL Prepared Statements SQL Hosting

SQL Cert

SQL Certificate

SQL References

SQL Data Types SQL Keywords MySQL Functions
String Functions: ASCII CHAR_LENGTH CHARACTER_LENGTH CONCAT CONCAT_WS FIELD FIND_IN_SET FORMAT INSERT INSTR LCASE LEFT LENGTH LOCATE LOWER LPAD LTRIM MID POSITION REPEAT REPLACE REVERSE RIGHT RPAD RTRIM SPACE STRCMP SUBSTR SUBSTRING SUBSTRING_INDEX TRIM UCASE UPPER Numeric Functions: ABS ACOS ASIN ATAN ATAN2 AVG CEIL CEILING COS COT COUNT DEGREES DIV EXP FLOOR GREATEST LEAST LN LOG LOG10 LOG2 MAX MIN MOD PI POW POWER RADIANS RAND ROUND SIGN SIN SQRT SUM TAN TRUNCATE Date Functions: ADDDATE ADDTIME CURDATE CURRENT_DATE CURRENT_TIME CURRENT_TIMESTAMP CURTIME DATE DATEDIFF DATE_ADD DATE_FORMAT DATE_SUB DAY DAYNAME DAYOFMONTH DAYOFWEEK DAYOFYEAR EXTRACT FROM_DAYS HOUR LAST_DAY LOCALTIME LOCALTIMESTAMP MAKEDATE MAKETIME MICROSECOND MINUTE MONTH MONTHNAME NOW PERIOD_ADD PERIOD_DIFF QUARTER SECOND SEC_TO_TIME STR_TO_DATE SUBDATE SUBTIME SYSDATE TIME TIME_FORMAT TIME_TO_SEC TIMEDIFF TIMESTAMP TO_DAYS WEEK WEEKDAY WEEKOFYEAR YEAR YEARWEEK Advanced Functions: BIN BINARY CASE CAST COALESCE CONNECTION_ID CONV CONVERT CURRENT_USER DATABASE IF IFNULL ISNULL LAST_INSERT_ID NULLIF SESSION_USER SYSTEM_USER USER VERSION
SQL Server Functions MS Access Functions SQL Quick Ref

SQL Examples

SQL Examples SQL Editor SQL Quiz SQL Exercises SQL Server SQL Syllabus SQL Study Plan SQL Training

SQL Prepared Statements


SQL Prepared Statements - Prevent SQL Injection

SQL prepared statements can be used to protect a web site from SQL injections.

Prepared statements seperates the query structure (the SQL) from the actual data (user input).

Prepared statements basically work like this:

  1. Prepare: An SQL query template with placeholders is sent to the server. The data values are not sent. Example: INSERT INTO MyGuests VALUES(?, ?, ?). Then, the server parses, compiles, and optimizes the SQL query template, without executing it
  2. Execute: At a later time, the application binds the values to the parameters, and the database executes the query. The application may execute the query as many times as it wants with different values

Prepared statements have four main advantages:

  • Reduced parsing time - as the preparation on the query is done only once (although the statement is executed multiple times)
  • Minimize bandwidth - Bound parameters minimize bandwidth to the server as you need send only the parameters each time, and not the whole query
  • Security - Prepared statements are very useful against SQL injections, because parameter values, which are transmitted later using a different protocol, need not be correctly escaped. If the original statement template is not derived from external input, SQL injection cannot occur
  • Cleaner code - by seperating data from SQL commands

Prepared Statements in MySQL

The following example is taken from PHP MySQL Prepared Statements, and uses prepared statements in MySQL:

Example - MySQL with Prepared Statements

<?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 query template
$sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)";

// Prepare the SQL query template
if($stmt = $conn->prepare($sql)) {
// Bind parameters
$stmt->bind_param("sss", $firstname, $lastname, $email);

// Set parameters and execute
$firstname = "John";
$lastname = "Doe";
$email = "john@example.com";
$stmt->execute();

$firstname = "Mary";
$lastname = "Moe";
$email = "mary@example.com";
$stmt->execute();

$firstname = "Julie";
$lastname = "Dooley";
$email = "julie@example.com";
$stmt->execute();
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

$stmt->close();
$conn->close();
?>

Code Explanation

In the SQL, the question marks (?) are placeholders for firstname, lastname, and email values:

"INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)"

Now, look at the bind_param() function. This function bind variables to the placeholders in the SQL query. The placeholders (?) will be replaced by the actual values held in the variables at the time of execution. The "sss" argument lists the type of data each parameter is. The s character tells mysql that the parameter is a string. We must define one of these for EACH parameter. By telling mysql what type of data to expect, we minimize the risk of SQL injections:

$stmt->bind_param("sss", $firstname, $lastname, $email);

The type argument can be one of four types:

  • i - integer (whole number)
  • d - double (floating point number)
  • s - string (text)
  • b - binary (image, PDF, etc.)

Note: If we want to insert data from external sources (like user input), it is very important that the data is sanitized and validated.




New

W3Schools Adventure App

Coding fundamentals as a game. Bite-sized lessons and challenges.

Ready to start your journey? Your streak is waiting.
+60 XP
W3Schools Adventure tutor
W3Schools Adventure map
×

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

FORUM ABOUT ACADEMY
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 our terms of use, cookies and privacy policy.

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

AltStyle によって変換されたページ (->オリジナル) /