添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
libxml_set_external_entity_loader() libxml_set_streams_context() libxml_use_internal_errors() PHP Mail ezmlm_hash() mail() PHP Math abs() acos() acosh() asin() asinh() atan() atan2() atanh() base_convert() bindec() ceil() cos() cosh() decbin() dechex() decoct() deg2rad() exp() expm1() floor() fmod() getrandmax() hexdec() hypot() intdiv() is_finite() is_infinite() is_nan() lcg_value() log() log10() log1p() max() min() mt_getrandmax() mt_rand() mt_srand() octdec() pow() rad2deg() rand() round() sin() sinh() sqrt() srand() tan() tanh() PHP Misc connection_aborted() connection_status() connection_timeout() constant() define() defined() die() eval() exit() get_browser() __halt_compiler() highlight_file() highlight_string() hrtime() ignore_user_abort() pack() php_strip_whitespace() show_source() sleep() sys_getloadavg() time_nanosleep() time_sleep_until() uniqid() unpack() usleep() PHP MySQLi affected_rows autocommit change_user character_set_name close commit connect connect_errno connect_error data_seek debug dump_debug_info errno error error_list fetch_all fetch_array fetch_assoc fetch_field fetch_field_direct fetch_fields fetch_lengths fetch_object fetch_row field_count field_seek get_charset get_client_info get_client_stats get_client_version get_connection_stats get_host_info get_proto_info get_server_info get_server_version insert_id more_results multi_query next_result options prepare query real_connect real_escape_string real_query reap_async_query refresh rollback select_db set_charset set_local_infile_handler sqlstate ssl_set stmt_init thread_id thread_safe use_result warning_count PHP Network checkdnsrr() closelog() dns_check_record() dns_get_mx() dns_get_record() fsockopen() gethostbyaddr() gethostbyname() gethostbynamel() gethostname() getmxrr() getprotobyname() getprotobynumber() getservbyname() getservbyport() header_register_callback() header_remove() header() headers_list() headers_sent() http_response_code() inet_ntop() inet_pton() ip2long() long2ip() openlog() pfsockopen() setcookie() setrawcookie() socket_get_status() socket_set_blocking() socket_set_timeout() syslog() PHP Output Control flush() ob_clean() ob_end_clean() ob_end_flush() ob_flush() ob_get_clean() ob_get_contents() ob_get_flush() ob_get_length() ob_get_level() ob_gzhandler() ob_implicit_flush() ob_list_handlers() ob_start() output_add_rewrite_var() output_reset_rewrite_vars() PHP RegEx preg_filter() preg_grep() preg_last_error() preg_match() preg_match_all() preg_replace preg_replace_callback preg_replace_callback_array preg_split preg_quote PHP SimpleXML __construct() __tostring() addAttribute() addChild() asXML() attributes() children() count() getDocNamespaces() getName() getNamespaces() registerXPathNamespace() saveXML() simplexml_import_dom() simplexml_load_file() simplexml_load_string() xpath() current() getchildren() haschildren() key() next() rewind() valid() PHP Stream PHP 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 Handling boolval() debug_zval_dump() doubleval() is_countable() empty() floatval() get_defined_vars() get_resource_type() gettype() intval() is_array() is_bool() is_callable() is_double() is_float() is_int() is_integer() is_iterable() is_long() is_null() is_numeric() is_object() is_real() is_resource() is_scalar() is_string() isset() print_r() serialize() settype() strval() unserialize() unset() var_dump() var_export() PHP XML Parser utf8_decode() utf8_encode() xml_error_string() xml_get_current_byte_index() xml_get_current_column_number() xml_get_current_line_number() xml_get_error_code() xml_parse() xml_parse_into_struct() xml_parser_create_ns() xml_parser_create() xml_parser_free() xml_parser_get_option() xml_parser_set_option() xml_set_character_data_handler() xml_set_default_handler() xml_set_element_handler() xml_set_end_namespace_decl_handler() xml_set_external_entity_ref_handler() xml_set_notation_decl_handler() xml_set_object() xml_set_processing_instruction_handler() xml_set_start_namespace_decl_handler() xml_set_unparsed_entity_decl_handler() PHP Zip zip_close() zip_entry_close() zip_entry_compressedsize() zip_entry_compressionmethod() zip_entry_filesize() zip_entry_name() zip_entry_open() zip_entry_read() zip_open() zip_read() PHP Timezones

Prepared Statements and Bound Parameters

A prepared statement is a feature used to execute the same (or similar) SQL statements repeatedly with high efficiency.

Prepared statements basically work like this:

  • Prepare: An SQL statement template is created and sent to the database. Certain values are left unspecified, called parameters (labeled "?"). Example: INSERT INTO MyGuests VALUES(?, ?, ?)
  • The database parses, compiles, and performs query optimization on the SQL statement template, and stores the result without executing it
  • Execute: At a later time, the application binds the values to the parameters, and the database executes the statement. The application may execute the statement as many times as it wants with different values
  • Compared to executing SQL statements directly, prepared statements have three main advantages:

  • Prepared statements reduce parsing time as the preparation on the query is done only once (although the statement is executed multiple times)
  • Bound parameters minimize bandwidth to the server as you need send only the parameters each time, and not the whole query
  • 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.
  • Prepared Statements in MySQLi

    The following example uses prepared statements and bound parameters in MySQLi:

    Example (MySQLi 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);
    }

    // prepare and bind
    $stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
    $stmt->bind_param("sss", $firstname, $lastname, $email);

    // set parameters and execute
    $firstname = "John";
    $lastname = "Doe";
    $email = "[email protected]";
    $stmt->execute();

    $firstname = "Mary";
    $lastname = "Moe";
    $email = "[email protected]";
    $stmt->execute();

    $firstname = "Julie";
    $lastname = "Dooley";
    $email = "[email protected]";
    $stmt->execute();

    echo "New records created successfully";

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

    Code lines to explain from the example above:

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

    In our SQL, we insert a question mark (?) where we want to substitute in an integer, string, double or blob value.

    Then, have a look at the bind_param() function:

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

    This function binds the parameters to the SQL query and tells the database what the parameters are. The "sss" argument lists the types of data that the parameters are. The s character tells mysql that the parameter is a string.

    The argument may be one of four types:

  • i - integer
  • d - double
  • string
  • b - BLOB

    We must have one of these for each parameter.

    By telling mysql what type of data to expect, we minimize the risk of SQL injections.

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

    Prepared Statements in PDO

    The following example uses prepared statements and bound parameters in PDO:

    Example (PDO with Prepared Statements)

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

    // prepare sql and bind parameters
    $stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email)
    VALUES (:firstname, :lastname, :email)");
    $stmt->bindParam(':firstname', $firstname);
    $stmt->bindParam(':lastname', $lastname);
    $stmt->bindParam(':email', $email);

    // insert a row
    $firstname = "John";
    $lastname = "Doe";
    $email = "[email protected]";
    $stmt->execute();

    // insert another row
    $firstname = "Mary";
    $lastname = "Moe";
    $email = "[email protected]";
    $stmt->execute();

    // insert another row
    $firstname = "Julie";
    $lastname = "Dooley";
    $email = "[email protected]";
    $stmt->execute();

    echo "New records created successfully";
    } catch(PDOException $e)   echo "Error: " . $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:
    [email protected]

    Report Error

    If you want to report an error, or if you want to make a suggestion, send us an e-mail:
    [email protected]

    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 , cookie and privacy policy .

    W3Schools is Powered by W3.CSS .

  •