// 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); ?> 98
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. PHP Create MySQL Tables A database table has its own unique name and consists of columns and rows. Create a MySQL Table Using MySQLi and PDO The CREATE TABLE statement is used to create a table in MySQL. 99
We will create a table named \"MyGuests\", with five columns: \"id\", \"firstname\", \"lastname\", \"email\" and \"reg_date\": CREATE TABLE MyGuests ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, firstname VARCHAR(30) NOT NULL, lastname VARCHAR(30) NOT NULL, email VARCHAR(50), reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ) Notes on the table above: The data type specifies what type of data the column can hold. For a complete reference of all the available data types, go to our Data Types reference. After the data type, you can specify other optional attributes for each column: NOT NULL - Each row must contain a value for that column, null values are not allowed DEFAULT value - Set a default value that is added when no other value is passed UNSIGNED - Used for number types, limits the stored data to positive numbers and zero AUTO INCREMENT - MySQL automatically increases the value of the field by 1 each time a new record is added PRIMARY KEY - Used to uniquely identify the rows in a table. The column with PRIMARY KEY setting is often an ID number, and is often used with AUTO_INCREMENT Each table should have a primary key column (in this case: the \"id\" column). Its value must be unique for each record in the table. The following examples shows how to create the table in PHP: Example (MySQLi Object-oriented) <?php $servername = \"localhost\"; $username = \"username\"; $password = \"password\"; $dbname = \"myDB\"; // Create connection 100
$conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die(\"Connection failed: \" . $conn->connect_error); } // sql to create table $sql = \"CREATE TABLE MyGuests ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, firstname VARCHAR(30) NOT NULL, lastname VARCHAR(30) NOT NULL, email VARCHAR(50), reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP )\"; if ($conn->query($sql) === TRUE) { echo \"Table MyGuests created successfully\"; } else { echo \"Error creating table: \" . $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 to create table $sql = \"CREATE TABLE MyGuests ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, firstname VARCHAR(30) NOT NULL, 101
lastname VARCHAR(30) NOT NULL, email VARCHAR(50), reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP )\"; if (mysqli_query($conn, $sql)) { echo \"Table MyGuests created successfully\"; } else { echo \"Error creating table: \" . 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 to create table $sql = \"CREATE TABLE MyGuests ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, firstname VARCHAR(30) NOT NULL, lastname VARCHAR(30) NOT NULL, email VARCHAR(50), reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP )\"; // use exec() because no results are returned $conn->exec($sql); echo \"Table MyGuests created successfully\"; 102
} catch(PDOException $e) { echo $sql . \"<br>\" . $e->getMessage(); } $conn = null; ?> PHP Insert Data Into MySQL 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 our SQL 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\"; 103
// 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', '[email protected]')\"; 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', '[email protected]')\"; if (mysqli_query($conn, $sql)) { echo \"New record created successfully\"; } else { echo \"Error: \" . $sql . \"<br>\" . mysqli_error($conn); 104
} 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', '[email protected]')\"; // 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; ?> 6.2 Get Last ID and Insert Multiple Data PHP Get ID of Last Inserted Record Get ID of The Last Inserted Record If we perform an INSERT or UPDATE on a table with an AUTO_INCREMENT field, we can get the ID of the last inserted/updated record immediately. In the table \"MyGuests\", the \"id\" column is an AUTO_INCREMENT field: 105
CREATE TABLE MyGuests ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, firstname VARCHAR(30) NOT NULL, lastname VARCHAR(30) NOT NULL, email VARCHAR(50), reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ) The following examples are equal to the examples from the previous page (PHP Insert Data Into MySQL), except that we have added one single line of code to retrieve the ID of the last inserted record. We also echo the last inserted ID: 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', '[email protected]')\"; if ($conn->query($sql) === TRUE) { $last_id = $conn->insert_id; echo \"New record created successfully. Last inserted ID is: \" . $last_id; } else { echo \"Error: \" . $sql . \"<br>\" . $conn->error; } $conn->close(); ?> 106
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', '[email protected]')\"; if (mysqli_query($conn, $sql)) { $last_id = mysqli_insert_id($conn); echo \"New record created successfully. Last inserted ID is: \" . $last_id; } 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', '[email protected]')\"; 107
// use exec() because no results are returned $conn->exec($sql); $last_id = $conn->lastInsertId(); echo \"New record created successfully. Last inserted ID is: \" . $last_id; } catch(PDOException $e) { echo $sql . \"<br>\" . $e->getMessage(); } $conn = null; ?> Insert Multiple Records Into MySQL Using MySQLi and PDO Multiple SQL statements must be executed with the mysqli_multi_query() function. The following examples add three new records 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', '[email protected]');\"; $sql .= \"INSERT INTO MyGuests (firstname, lastname, email) VALUES ('Mary', 'Moe', '[email protected]');\"; $sql .= \"INSERT INTO MyGuests (firstname, lastname, email) VALUES ('Julie', 'Dooley', '[email protected]')\"; if ($conn->multi_query($sql) === TRUE) { echo \"New records created successfully\"; } else { 108
echo \"Error: \" . $sql . \"<br>\" . $conn->error; } $conn->close(); ?> Note that each SQL statement must be separated by a semicolon. 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', '[email protected]');\"; $sql .= \"INSERT INTO MyGuests (firstname, lastname, email) VALUES ('Mary', 'Moe', '[email protected]');\"; $sql .= \"INSERT INTO MyGuests (firstname, lastname, email) VALUES ('Julie', 'Dooley', '[email protected]')\"; if (mysqli_multi_query($conn, $sql)) { echo \"New records created successfully\"; } else { echo \"Error: \" . $sql . \"<br>\" . mysqli_error($conn); } mysqli_close($conn); ?> The PDO way is a little bit different: 109
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); // begin the transaction $conn->beginTransaction(); // our SQL statements $conn->exec(\"INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', '[email protected]')\"); $conn->exec(\"INSERT INTO MyGuests (firstname, lastname, email) VALUES ('Mary', 'Moe', '[email protected]')\"); $conn->exec(\"INSERT INTO MyGuests (firstname, lastname, email) VALUES ('Julie', 'Dooley', '[email protected]')\"); // commit the transaction $conn->commit(); echo \"New records created successfully\"; } catch(PDOException $e) { // roll back the transaction if something failed $conn->rollback(); echo \"Error: \" . $e->getMessage(); } $conn = null; ?> 6.3 MySQL Prepared PHP Prepared Statements 110
Prepared statements are very useful against SQL injections. 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: 1. 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(?, ?, ?) 2. The database parses, compiles, and performs query optimization on the SQL statement template, and stores the result without executing it 3. 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\"; 111
// 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. 112
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 s - 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) 113
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; ?> 6.4 Select, Delete, Update and Limit Data PHP Select Data From MySQL Select Data From a MySQL Database The SELECT statement is used to select data from one or more tables: SELECT column_name(s) FROM table_name 114
or we can use the * character to select ALL columns from a table: SELECT * FROM table_name To learn more about SQL, please visit our SQL tutorial. Select Data With MySQLi The following example selects the id, firstname and lastname columns from the MyGuests table and displays it on the page: 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 = \"SELECT id, firstname, lastname FROM MyGuests\"; $result = $conn->query($sql); if ($result->num_rows > 0) { // output data of each row while($row = $result->fetch_assoc()) { echo \"id: \" . $row[\"id\"]. \" - Name: \" . $row[\"firstname\"]. \" \" . $row[\"lastname\"]. \"<br>\"; } } else { echo \"0 results\"; } $conn->close(); ?> Code lines to explain from the example above: 115
First, we set up an SQL query that selects the id, firstname and lastname columns from the MyGuests table. The next line of code runs the query and puts the resulting data into a variable called $result. Then, the function num_rows() checks if there are more than zero rows returned. If there are more than zero rows returned, the function fetch_assoc() puts all the results into an associative array that we can loop through. The while() loop loops through the result set and outputs the data from the id, firstname and lastname columns. The following example shows the same as the example above, in the MySQLi procedural way: 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 = \"SELECT id, firstname, lastname FROM MyGuests\"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { // output data of each row while($row = mysqli_fetch_assoc($result)) { echo \"id: \" . $row[\"id\"]. \" - Name: \" . $row[\"firstname\"]. \" \" . $row[\"lastname\"]. \"<br>\"; } } else { echo \"0 results\"; } mysqli_close($conn); ?> 116
Run example » You can also put the result in an HTML 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 = \"SELECT id, firstname, lastname FROM MyGuests\"; $result = $conn->query($sql); if ($result->num_rows > 0) { echo \"<table><tr><th>ID</th><th>Name</th></tr>\"; // output data of each row while($row = $result->fetch_assoc()) { echo \"<tr><td>\".$row[\"id\"].\"</td><td>\".$row[\"firstname\"].\" \".$row[\"lastname\"].\"</td></tr>\"; } echo \"</table>\"; } else { echo \"0 results\"; } $conn->close(); ?> Run example » 117
Select Data With PDO (+ Prepared Statements) The following example uses prepared statements. It selects the id, firstname and lastname columns from the MyGuests table and displays it in an HTML table: Example (PDO) <?php echo \"<table style='border: solid 1px black;'>\"; echo \"<tr><th>Id</th><th>Firstname</th><th>Lastname</th></tr>\"; class TableRows extends RecursiveIteratorIterator { function __construct($it) { parent::__construct($it, self::LEAVES_ONLY); } function current() { return \"<td style='width:150px;border:1px solid black;'>\" . parent::current(). \"</td>\"; } function beginChildren() { echo \"<tr>\"; } function endChildren() { echo \"</tr>\" . \"\\n\"; } } $servername = \"localhost\"; $username = \"username\"; $password = \"password\"; $dbname = \"myDBPDO\"; try { $conn = new PDO(\"mysql:host=$servername;dbname=$dbname\", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $conn->prepare(\"SELECT id, firstname, lastname FROM MyGuests\"); $stmt->execute(); 118
// set the resulting array to associative $result = $stmt->setFetchMode(PDO::FETCH_ASSOC); foreach(new TableRows(new RecursiveArrayIterator($stmt- >fetchAll())) as $k=>$v) { echo $v; } } catch(PDOException $e) { echo \"Error: \" . $e->getMessage(); } $conn = null; echo \"</table>\"; ?> PHP Delete Data From MySQL Delete Data From a MySQL Table Using MySQLi and PDO The DELETE statement is used to delete records from a table: DELETE FROM table_name WHERE some_column = some_value Notice the WHERE clause in the DELETE syntax: The WHERE clause specifies which record or records that should be deleted. If you omit the WHERE clause, all records will be deleted! To learn more about SQL, please visit our SQL tutorial. Let's look at the \"MyGuests\" table: id firstname lastname email reg_date 1 John Doe [email protected] 22/10/2014 2 Mary Moe [email protected] 14:26 3 Julie Dooley [email protected] 23/10/2014 10:22 26/10/2014 10:48 The following examples delete the record with id=3 in the \"MyGuests\" table: Example (MySQLi Object-oriented) <?php $servername = \"localhost\"; $username = \"username\"; 119
$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 to delete a record $sql = \"DELETE FROM MyGuests WHERE id=3\"; if ($conn->query($sql) === TRUE) { echo \"Record deleted successfully\"; } else { echo \"Error deleting record: \" . $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 to delete a record $sql = \"DELETE FROM MyGuests WHERE id=3\"; if (mysqli_query($conn, $sql)) { echo \"Record deleted successfully\"; 120
} else { echo \"Error deleting record: \" . 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 to delete a record $sql = \"DELETE FROM MyGuests WHERE id=3\"; // use exec() because no results are returned $conn->exec($sql); echo \"Record deleted successfully\"; } catch(PDOException $e) { echo $sql . \"<br>\" . $e->getMessage(); } $conn = null; ?> After the record is deleted, the table will look like this: id firstname lastname email reg_date 1 John Doe [email protected] 22/10/2014 14:26 2 Mary Moe [email protected] 23/10/2014 10:22 121
PHP Update Data in MySQL Update Data In a MySQL Table Using MySQLi and PDO The UPDATE statement is used to update existing records in a table: UPDATE table_name SET column1=value, column2=value2,... WHERE some_column=some_value Notice the WHERE clause in the UPDATE syntax: The WHERE clause specifies which record or records that should be updated. If you omit the WHERE clause, all records will be updated! To learn more about SQL, please visit our SQL tutorial. Let's look at the \"MyGuests\" table: id firstname lastname email reg_date 1 John Doe [email protected] 22/10/2014 14:26 2 Mary Moe [email protected] 23/10/2014 10:22 The following examples update the record with id=2 in 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); } 122
$sql = \"UPDATE MyGuests SET lastname='Doe' WHERE id=2\"; if ($conn->query($sql) === TRUE) { echo \"Record updated successfully\"; } else { echo \"Error updating record: \" . $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 = \"UPDATE MyGuests SET lastname='Doe' WHERE id=2\"; if (mysqli_query($conn, $sql)) { echo \"Record updated successfully\"; } else { echo \"Error updating record: \" . mysqli_error($conn); } mysqli_close($conn); ?> Example (PDO) <?php $servername = \"localhost\"; $username = \"username\"; 123
$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 = \"UPDATE MyGuests SET lastname='Doe' WHERE id=2\"; // Prepare statement $stmt = $conn->prepare($sql); // execute the query $stmt->execute(); // echo a message to say the UPDATE succeeded echo $stmt->rowCount() . \" records UPDATED successfully\"; } catch(PDOException $e) { echo $sql . \"<br>\" . $e->getMessage(); } $conn = null; ?> After the record is updated, the table will look like this: id firstname lastname email reg_date 1 John Doe [email protected] 22/10/2014 14:26 2 Mary Doe [email protected] 23/10/2014 10:22 Limit Data Selections From a MySQL Database MySQL provides a LIMIT clause that is used to specify the number of records to return. 124
The LIMIT clause makes it easy to code multi page results or pagination with SQL, and is very useful on large tables. Returning a large number of records can impact on performance. Assume we wish to select all records from 1 - 30 (inclusive) from a table called \"Orders\". The SQL query would then look like this: $sql = \"SELECT * FROM Orders LIMIT 30\"; When the SQL query above is run, it will return the first 30 records. What if we want to select records 16 - 25 (inclusive)? Mysql also provides a way to handle this: by using OFFSET. The SQL query below says \"return only 10 records, start on record 16 (OFFSET 15)\": $sql = \"SELECT * FROM Orders LIMIT 10 OFFSET 15\"; You could also use a shorter syntax to achieve the same result: $sql = \"SELECT * FROM Orders LIMIT 15, 10\"; Notice that the numbers are reversed when you use a comma. 125
7.0 PHP FUNCTION AND PARAMETER 7.1 Function The real power of PHP comes from its functions; it has more than 1000 built-in functions. PHP User Defined Functions Besides the built-in PHP functions, we can create our own functions. A function is a block of statements that can be used repeatedly in a program. A function will not execute immediately when a page loads. A function will be executed by a call to the function. Create a User Defined Function in PHP A user-defined function declaration starts with the word function: Syntax function functionName() { code to be executed; } Note: A function name can start with a letter or underscore (not a number). Tip: Give the function a name that reflects what the function does! Function names are NOT case-sensitive. In the example below, we create a function named \"writeMsg()\". The opening curly brace ( { ) indicates the beginning of the function code, and the closing curly brace ( } ) indicates the end of the function. The function outputs \"Hello world!\". To call the function, just write its name followed by brackets (): Example <?php function writeMsg() { 126
echo \"Hello world!\"; } writeMsg(); // call the function ?> Try it Yourself » 7.2 Function Parameter PHP Function Arguments Information can be passed to functions through arguments. An argument is just like a variable. Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma. The following example has a function with one argument ($fname). When the familyName() function is called, we also pass along a name (e.g. Jani), and the name is used inside the function, which outputs several different first names, but an equal last name: Example <?php function familyName($fname) { echo \"$fname Refsnes.<br>\"; } familyName(\"Jani\"); familyName(\"Hege\"); familyName(\"Stale\"); familyName(\"Kai Jim\"); familyName(\"Borge\"); ?> Try it Yourself » The following example has a function with two arguments ($fname and $year): 127
Example <?php function familyName($fname, $year) { echo \"$fname Refsnes. Born in $year <br>\"; } familyName(\"Hege\", \"1975\"); familyName(\"Stale\", \"1978\"); familyName(\"Kai Jim\", \"1983\"); ?> Try it Yourself » PHP is a Loosely Typed Language In the example above, notice that we did not have to tell PHP which data type the variable is. PHP automatically associates a data type to the variable, depending on its value. Since the data types are not set in a strict sense, you can do things like adding a string to an integer without causing an error. In PHP 7, type declarations were added. This gives us an option to specify the data type expected when declaring a function, and by enabling the strict requirement, it will throw a \"Fatal Error\" on a type mismatch. In the following example we try to add a number and a string with without the strict requirement: Example <?php function addNumbers(int $a, int $b) { return $a + $b; } echo addNumbers(5, \"5 days\"); // since strict is NOT enabled \"5 days\" is changed to int(5), and it will return 10 ?> Try it Yourself » 128
In the following example we try to add a number and a string with with the strict requirement: Example <?php declare(strict_types=1); // strict requirement function addNumbers(int $a, int $b) { return $a + $b; } echo addNumbers(5, \"5 days\"); // since strict is enabled and \"5 days\" is not an integer, an error will be thrown ?> Try it Yourself » To specify strict we need to set declare(strict_types=1);. This must be on the very first line of the PHP file. Declaring strict specifies that function calls made in that file must strictly adhere to the specified data types The strict declaration can make code easier to read, and it forces things to be used in the intended way. Going forward in this tutorial, we will use the strict requirement. PHP Default Argument Value The following example shows how to use a default parameter. If we call the function setHeight() without arguments it takes the default value as argument: Example <?php declare(strict_types=1); // strict requirement function setHeight(int $minheight = 50) { echo \"The height is : $minheight <br>\"; } setHeight(350); setHeight(); // will use the default value of 50 setHeight(135); setHeight(80); ?> 129
Try it Yourself » PHP Functions - Returning values To let a function return a value, use the return statement: Example <?php declare(strict_types=1); // strict requirement function sum(int $x, int $y) { $z = $x + $y; return $z; } echo \"5 + 10 = \" . sum(5, 10) . \"<br>\"; echo \"7 + 13 = \" . sum(7, 13) . \"<br>\"; echo \"2 + 4 = \" . sum(2, 4); ?> Try it Yourself » PHP Return Type Declarations PHP 7 also supports Type Declarations for the return statement. Like with the type declaration for function arguments, by enabling the strict requirement, it will throw a \"Fatal Error\" on a type mismatch. To declare a type for the function return, add a colon ( : ) and the type right before the opening curly ( { )bracket when declaring the function. In the following example we specify the return type for the function: Example <?php declare(strict_types=1); // strict requirement function addNumbers(float $a, float $b) : float { return $a + $b; } echo addNumbers(1.2, 5.2); ?> Try it Yourself » 130
You can specify a different return type, than the argument types, but make sure the return is the correct type: Example <?php declare(strict_types=1); // strict requirement function addNumbers(float $a, float $b) : int { return (int)($a + $b); } echo addNumbers(1.2, 5.2); ?> Try it Yourself » 131
8.0 PHP REFERENCES 8.1 Array PHP Array Introduction The array functions allow you to access and manipulate arrays. Simple and multi-dimensional arrays are supported. Installation The array functions are part of the PHP core. There is no installation needed to use these functions. PHP Array Functions Function Description Creates an array array() Changes all keys in an array to lowercase or uppercase array_change_key_case() Splits an array into chunks of arrays array_chunk() Returns the values from a single column in the input array array_column() Creates an array by using the elements from one \"keys\" array and one \"values\" array array_combine() Counts all the values of an array array_count_values() Compare arrays, and returns the differences (compare values only) array_diff() Compare arrays, and returns the differences (compare keys and values) array_diff_assoc() Compare arrays, and returns the differences (compare keys only) array_diff_key() Compare arrays, and returns the differences (compare keys and values, using a user- defined key comparison function) array_diff_uassoc() Compare arrays, and returns the differences (compare keys only, using a user-defined key comparison function) array_diff_ukey() Fills an array with values Fills an array with values, specifying keys array_fill() Filters the values of an array using a callback function array_fill_keys() Flips/Exchanges all keys with their associated values in an array array_filter() Compare arrays, and returns the matches (compare values only) array_flip() Compare arrays and returns the matches (compare keys and values) array_intersect() Compare arrays, and returns the matches (compare keys only) array_intersect_assoc() array_intersect_key() 132
Compare arrays, and returns the matches (compare keys and values, using a user- array_intersect_uassoc() defined key comparison function) array_intersect_ukey() Compare arrays, and returns the matches (compare keys only, using a user-defined key comparison function) array_key_exists() Checks if the specified key exists in the array array_keys() Returns all the keys of an array array_map() Sends each value of an array to a user-made function, which returns new values array_merge() Merges one or more arrays into one array array_merge_recursive() Merges one or more arrays into one array recursively array_multisort() Sorts multiple or multi-dimensional arrays array_pad() Inserts a specified number of items, with a specified value, to an array array_pop() Deletes the last element of an array array_product() Calculates the product of the values in an array array_push() Inserts one or more elements to the end of an array array_rand() Returns one or more random keys from an array array_reduce() Returns an array as a string, using a user-defined function array_replace() Replaces the values of the first array with the values from following arrays array_replace_recursive() Replaces the values of the first array with the values from following arrays recursively array_reverse() Returns an array in the reverse order array_search() Searches an array for a given value and returns the key array_shift() Removes the first element from an array, and returns the value of the removed element array_slice() Returns selected parts of an array array_splice() Removes and replaces specified elements of an array array_sum() Returns the sum of the values in an array array_udiff() Compare arrays, and returns the differences (compare values only, using a user-defined key comparison function) array_udiff_assoc() Compare arrays, and returns the differences (compare keys and values, using a built-in function to compare the keys and a user-defined function to compare the values) array_udiff_uassoc() Compare arrays, and returns the differences (compare keys and values, using two user- defined key comparison functions) array_uintersect() Compare arrays, and returns the matches (compare values only, using a user-defined key comparison function) Compare arrays, and returns the matches (compare keys and values, using a built-in array_uintersect_assoc() function to compare the keys and a user-defined function to compare the values) Compare arrays, and returns the matches (compare keys and values, using two user- array_uintersect_uassoc() defined key comparison functions) array_unique() Removes duplicate values from an array array_unshift() Adds one or more elements to the beginning of an array 133
array_values() Returns all the values of an array array_walk() Applies a user function to every member of an array array_walk_recursive() Applies a user function recursively to every member of an array arsort() Sorts an associative array in descending order, according to the value asort() Sorts an associative array in ascending order, according to the value compact() Create array containing variables and their values count() Returns the number of elements in an array current() Returns the current element in an array each() Deprecated from PHP 7.2. Returns the current key and value pair from an array end() Sets the internal pointer of an array to its last element extract() Imports variables into the current symbol table from an array in_array() Checks if a specified value exists in an array key() Fetches a key from an array krsort() Sorts an associative array in descending order, according to the key ksort() Sorts an associative array in ascending order, according to the key list() Assigns variables as if they were an array natcasesort() Sorts an array using a case insensitive \"natural order\" algorithm natsort() Sorts an array using a \"natural order\" algorithm next() Advance the internal array pointer of an array pos() prev() Alias of current() range() reset() Rewinds the internal array pointer rsort() Creates an array containing a range of elements shuffle() Sets the internal pointer of an array to its first element sizeof() Sorts an indexed array in descending order sort() Shuffles an array uasort() uksort() Alias of count() usort() Sorts an indexed array in ascending order Sorts an array by values using a user-defined comparison function Sorts an array by keys using a user-defined comparison function Sorts an array using a user-defined comparison function 8.2 Calendar PHP Calendar Functions 134
PHP Calendar Introduction The calendar extension contains functions that simplifies converting between different calendar formats. It is based on the Julian Day Count, which is a count of days starting from January 1st, 4713 B.C. Note: To convert between calendar formats, you must first convert to Julian Day Count, then to the calendar of your choice. Note: The Julian Day Count is not the same as the Julian Calendar! Installation For these functions to work, you have to compile PHP with --enable-calendar. The Windows version of PHP has built-in support for this extension. PHP Calendar Functions Function Description cal_days_in_month() Returns the number of days in a month for a specified year and calendar cal_from_jd() Converts a Julian Day Count into a date of a specified calendar cal_info() Returns information about a specified calendar cal_to_jd() Converts a date in a specified calendar to Julian Day Count easter_date() Returns the Unix timestamp for midnight on Easter of a specified year Returns the number of days after March 21, that the Easter Day is in a easter_days() specified year Converts a French Republican date to a Julian Day Count frenchtojd() Converts a Gregorian date to a Julian Day Count gregoriantojd() Returns the day of the week jddayofweek() Returns a month name jdmonthname() Converts a Julian Day Count to a French Republican date jdtofrench() Converts a Julian Day Count to a Gregorian date jdtogregorian() Converts a Julian Day Count to a Jewish date jdtojewish() Converts a Julian Day Count to a Julian date jdtojulian() Converts Julian Day Count to Unix timestamp jdtounix() Converts a Jewish date to a Julian Day Count jewishtojd() Converts a Julian date to a Julian Day Count juliantojd() unixtojd() Converts Unix timestamp to Julian Day Count 135
PHP Predefined Calendar Constants Constant Type PHP Version CAL_GREGORIAN Integer PHP 4 CAL_JULIAN Integer PHP 4 CAL_JEWISH Integer PHP 4 CAL_FRENCH Integer PHP 4 CAL_NUM_CALS Integer PHP 4 CAL_DOW_DAYNO Integer PHP 4 CAL_DOW_SHORT Integer PHP 4 CAL_DOW_LONG Integer PHP 4 CAL_MONTH_GREGORIAN_SHORT Integer PHP 4 CAL_MONTH_GREGORIAN_LONG Integer PHP 4 CAL_MONTH_JULIAN_SHORT Integer PHP 4 CAL_MONTH_JULIAN_LONG Integer PHP 4 CAL_MONTH_JEWISH Integer PHP 4 CAL_MONTH_FRENCH Integer PHP 4 CAL_EASTER_DEFAULT Integer PHP 4.3 CAL_EASTER_ROMAN Integer PHP 4.3 CAL_EASTER_ALWAYS_GREGORIAN Integer PHP 4.3 CAL_EASTER_ALWAYS_JULIAN Integer PHP 4.3 CAL_JEWISH_ADD_ALAFIM_GERESH Integer PHP 5.0 CAL_JEWISH_ADD_ALAFIM Integer PHP 5.0 CAL_JEWISH_ADD_GERESHAYIM Integer PHP 5.0 8.3 Date PHP Date/Time Functions The date/time functions allow you to get the date and time from the server where your PHP script runs. You can then use the date/time functions to format the date and time in several ways. Note: These functions depend on the locale settings of your server. Remember to take daylight saving time and leap years into consideration when working with these functions. 136
Installation The PHP date/time functions are part of the PHP core. No installation is required to use these functions. Runtime Configuration The behavior of these functions is affected by settings in php.ini: Name Description Default PHP Version date.timezone The default timezone (used by all date/time functions) \"\" PHP 5.1 date.default_latitude The default latitude (used by date_sunrise() and date_sunset()) \"31.7667\" date.default_longitude The default longitude (used by date_sunrise() and date_sunset()) \"35.2333\" PHP 5.0 date.sunrise_zenith The default sunrise zenith (used by date_sunrise() and date_sunset()) \"90.83\" date.sunset_zenith The default sunset zenith (used by date_sunrise() and date_sunset()) \"90.83\" PHP 5.0 PHP 5.0 PHP 5.0 PHP Date/Time Functions Function Description checkdate() date_add() Validates a Gregorian date date_create_from_format() date_create() Adds days, months, years, hours, minutes, and seconds to a date date_date_set() Returns a new DateTime object formatted according to a date_default_timezone_get() specified format date_default_timezone_set() Returns a new DateTime object date_diff() date_format() Sets a new date date_get_last_errors() date_interval_create_from_date_string() Returns the default timezone used by all date/time functions date_interval_format() date_isodate_set() Sets the default timezone used by all date/time functions date_modify() date_offset_get() Returns the difference between two dates date_parse_from_format() Returns a date formatted according to a specified format date_parse() Returns the warnings/errors found in a date string date_sub() Sets up a DateInterval from the relative parts of the string date_sun_info() Formats the interval date_sunrise() date_sunset() Sets the ISO date date_time_set() Modifies the timestamp Returns the timezone offset Returns an associative array with detailed info about a specified date, according to a specified format Returns an associative array with detailed info about a specified date Subtracts days, months, years, hours, minutes, and seconds from a date Returns an array containing info about sunset/sunrise and twilight begin/end, for a specified day and location Returns the sunrise time for a specified day and location Returns the sunset time for a specified day and location Sets the time 137
date_timestamp_get() Returns the Unix timestamp date_timestamp_set() Sets the date and time based on a Unix timestamp date_timezone_get() Returns the time zone of the given DateTime object date_timezone_set() Sets the time zone for the DateTime object date() Formats a local date and time Returns date/time information of a timestamp or the current getdate() local date/time Returns the current time gettimeofday() Formats a GMT/UTC date and time gmdate() Returns the Unix timestamp for a GMT date gmmktime() Formats a GMT/UTC date and time according to locale settings gmstrftime() Formats a local time/date as integer idate() Returns the local time localtime() Returns the current Unix timestamp with microseconds microtime() Returns the Unix timestamp for a date mktime() Formats a local time and/or date according to locale settings strftime() Parses a time/date generated with strftime() strptime() Parses an English textual datetime into a Unix timestamp strtotime() Returns the current time as a Unix timestamp time() Returns an associative array containing dst, offset, and the timezone name timezone_abbreviations_list() Returns an indexed array with all timezone identifiers Returns location information for a specified timezone timezone_identifiers_list() Returns the timezone name from abbreviation timezone_location_get() Returns the name of the timezone timezone_name_from_ abbr() Returns the timezone offset from GMT timezone_name_get() Creates new DateTimeZone object timezone_offset_get() Returns all transitions for the timezone timezone_open() timezone_transitions_get() Returns the version of the timezonedb timezone_version_get() PHP Predefined Date/Time Constants Constant Description DATE_ATOM Atom (example: 2019-01-18T14:13:03+00:00) DATE_COOKIE HTTP Cookies (example: Fri, 18 Jan 2019 14:13:03 UTC) DATE_ISO8601 ISO-8601 (example: 2019-01-18T14:13:03+0000) DATE_RFC822 RFC 822 (example: Fri, 18 Jan 2019 14:13:03 +0000) DATE_RFC850 RFC 850 (example: Friday, 18-Jan-19 14:13:03 UTC) DATE_RFC1036 RFC 1036 (example: Friday, 18-Jan-19 14:13:03 +0000) DATE_RFC1123 RFC 1123 (example: Fri, 18 Jan 2019 14:13:03 +0000) DATE_RFC2822 RFC 2822 (example: Fri, 18 Jan 2019 14:13:03 +0000) DATE_RFC3339 Same as DATE_ATOM (since PHP 5.1.3) RFC3339 Extended format (since PHP 7.0.0) (example: 2019-01- DATE_RFC3339_EXTENDED 18T16:34:01.000+00:00) 138
DATE_RSS RSS (Fri, 18 Jan 2019 14:13:03 +0000) DATE_W3C World Wide Web Consortium (example: 2019-01-18T14:13:03+00:00) SUNFUNCS_RET_TIMESTAMP Timestamp (since PHP 5.1.2) SUNFUNCS_RET_STRING Hours:minutes (example: 09:41) (since PHP 5.1.2) SUNFUNCS_RET_DOUBLE Hours as a floating point number (example: 9.75) (since PHP 5.1.2) 8.4 Directory The directory functions allow you to retrieve information about directories and their contents. Installation The PHP directory functions are part of the PHP core. No installation is required to use these functions. PHP Directory Functions Function Description Changes the current directory chdir() Changes the root directory chroot() Closes a directory handle closedir() Returns an instance of the Directory class dir() Returns the current working directory getcwd() Opens a directory handle opendir() Returns an entry from a directory handle readdir() Resets a directory handle rewinddir() Returns an array of files and directories of a specified directory scandir() 8.5 Error PHP Error Functions The error functions are used to deal with error handling and logging. The error functions allow us to define own error handling rules, and modify the way the errors can be logged. The logging functions allow us to send messages directly to other machines, emails, or system logs. 139
The error reporting functions allow us to customize what level and kind of error feedback is given. Installation The PHP error functions are part of the PHP core. No installation is required to use these functions. Runtime Configuration The behavior of the error functions is affected by settings in php.ini. Errors and logging configuration options: Name Defaul Description Changeable error_reporting t PHP_INI_ALL NULL Sets the error reporting level (either an integer display_errors \"1\" or named constants) PHP_INI_ALL Specifies whether errors should be printed to the display_startup_errors \"0\" screen, or if they should be hidden from the user. PHP_INI_ALL Note: This feature should never be used on log_errors \"0\" production systems (only to support your PHP_INI_ALL development) log_errors_max_len \"1024\" Even when display_errors is on, errors that occur PHP_INI_ALL during PHP's startup sequence are not displayed ignore_repeated_error \"0\" Note: It is strongly recommended to keep PHP_INI_ALL s display_startup_errors off, except for debugging ignore_repeated_sourc \"0\" Defines whether script error messages should be PHP_INI_ALL e \"1\" logged to the server's error log or error_log. report_memleaks \"0\" Note: It is strongly advised to use error logging PHP_INI_ALL track_errors \"1\" instead of error displaying on production web sites PHP_INI_ALL html_errors \"0\" Sets the maximum length of log_errors in bytes. The PHP_INI_ALL xmlrpc_errors \"0\" value \"0\" can be used to not apply any maximum PHP_INI_SYSTE xmlrpc_error_number \"\" length at all. This length is applied to logged errors, M in PHP <= docref_root displayed errors, and also to $php_errormsg 4.2.3. (available since PHP 4.3) PHP_INI_SYSTE Specifies whether to log repeated error messages. M When set to \"1\" it will not log errors with repeated PHP_INI_ALL errors from the same file on the same line (available PHP_INI_ALL since PHP 4.3) Specifies whether to log repeated error messages. When set to \"1\" it will not log errors with repeated errors from different files or source lines (available since PHP 4.3) If set to \"1\" (the default), this parameter will show a report of memory leaks detected by the Zend memory manager (available since PHP 4.3) If set to \"1\", the last error message will always be present in the variable $php_errormsg Turns off HTML tags in error messages Turns off normal error reporting and formats errors as XML-RPC error message (available since PHP 4.1) Used as the value of the XML-RPC faultCode element (available since PHP 4.1) (available since PHP 4.3) 140
docref_ext \"\" (available since PHP 4.3.2) PHP_INI_ALL error_prepend_string NULL PHP_INI_ALL error_append_string NULL Specifies a string to output before an error message PHP_INI_ALL error_log NULL Specifies a string to output after an error message PHP_INI_ALL Specifies the name of the file where script errors should be logged. The file should be writable by the web server's user. If the special value syslog is used, the errors are sent to the system logger instead PHP Error and Logging Functions Function Description debug_backtrace() Generates a backtrace debug_print_backtrace() Prints a backtrace error_clear_last() Clears the last error error_get_last() Returns the last error that occurred error_log() Sends an error message to a log, to a file, or to a mail account error_reporting() Specifies which errors are reported restore_error_handler() Restores the previous error handler restore_exception_handler() Restores the previous exception handler set_error_handler() Sets a user-defined error handler function set_exception_handler() Sets a user-defined exception handler function trigger_error() Creates a user-level error message user_error() Alias of trigger_error() PHP Predefined Error and Logging Constants Value Constant Description 1 E_ERROR 2 E_WARNING Fatal run-time errors. Errors that cannot be recovered from. Execution of the script 4 E_PARSE is halted 8 E_NOTICE Run-time warnings (non-fatal errors). Execution of the script is not halted 16 E_CORE_ERROR 32 E_CORE_WARNING Compile-time parse errors. Parse errors should only be generated by the parser 64 E_COMPILE_ERROR Run-time notices. The script found something that might be an error, but could also 128 E_COMPILE_WARNING happen when running a script normally Fatal errors at PHP startup. This is like E_ERROR, except it is generated by the core 256 E_USER_ERROR of PHP Non-fatal errors at PHP startup. This is like E_WARNING, except it is generated by the 512 E_USER_WARNING core of PHP Fatal compile-time errors. This is like E_ERROR, except it is generated by the Zend Scripting Engine Non-fatal compile-time errors. This is like E_WARNING, except it is generated by the Zend Scripting Engine Fatal user-generated error. This is like E_ERROR, except it is generated in PHP code by using the PHP function trigger_error() Non-fatal user-generated warning. This is like E_WARNING, except it is generated in PHP code by using the PHP function trigger_error() 141
1024 E_USER_NOTICE User-generated notice. This is like E_NOTICE, except it is generated in PHP code by 2048 E_STRICT using the PHP function trigger_error() 4096 E_RECOVERABLE_ERROR Enable to have PHP suggest changes to your code which will ensure the best 8192 E_DEPRECATED interoperability and forward compatibility of your code (Since PHP 5 but not included 16384 E_USER_DEPRECATED in E_ALL until PHP 5.4) 32767 E_ALL Catchable fatal error. Indicates that a probably dangerous error occurred, but did not leave the Engine in an unstable state. If the error is not caught by a user defined handle, the application aborts as it was an E_ERROR (Since PHP 5.2) Run-time notices. Enable this to receive warnings about code that will not work in future versions (Since PHP 5.3) User-generated warning message. This is like E_DEPRECATED, except it is generated in PHP code by using the PHP function trigger_error() (Since PHP 5.3) Enable all PHP errors and warnings (except E_STRICT in versions < 5.4) 8.6 Files System PHP Filesystem Functions The filesystem functions allow you to access and manipulate the filesystem. Installation The filesystem functions are part of the PHP core. There is no installation needed to use these functions. Unix / Windows Compatibility When specifying a path on Unix platforms, a forward slash (/) is used as directory separator. On Windows platforms, both forward slash (/) and backslash (\\) can be used. Runtime Configuration The behavior of the filesystem functions is affected by settings in php.ini. Name Defau Description Changeable allow_url_fopen lt Allows fopen()-type functions to work with URLs PHP_INI_SYS TEM \"1\" PHP_INI_SYS TEM allow_url_include \"0\" (available since PHP 5.2) PHP_INI_ALL user_agent NULL Defines the user agent for PHP to send (available since PHP PHP_INI_ALL \"60\" 4.3) default_socket_time Sets the default timeout, in seconds, for socket based PHP_INI_ALL out streams (available since PHP 4.3) Defines the email address to be used on unauthenticated PHP_INI_ALL from \"\" FTP connections and in the From header for HTTP connections when using ftp and http wrappers auto_detect_line_e \"0\" When set to \"1\", PHP will examine the data read by fgets() ndings and file() to see if it is using Unix, MS-Dos or Mac line- ending characters (available since PHP 4.3) 142
sys_temp_dir \"\" (available since PHP 5.5) PHP_INI_SYS TEM PHP Filesystem Functions Function Description basename() Returns the filename component of a path chgrp() Changes the file group chmod() Changes the file mode chown() Changes the file owner clearstatcache() Clears the file status cache copy() Copies a file delete() dirname() See unlink() or unset() disk_free_space() Returns the directory name component of a path disk_total_space() Returns the free space of a filesystem or disk diskfreespace() Returns the total size of a filesystem or disk fclose() Alias of disk_free_space() feof() Closes an open file Checks if the \"end-of-file\" (EOF) has been reached for an fflush() open file fgetc() Flushes buffered output to an open file fgetcsv() Returns a single character from an open file fgets() Returns a line from an open CSV file Returns a line from an open file fgetss() Deprecated from PHP 7.3. Returns a line from an open file - stripped from HTML and PHP tags file() Reads a file into an array file_exists() Checks whether or not a file or directory exists file_get_contents() Reads a file into a string file_put_contents() Writes data to a file fileatime() Returns the last access time of a file filectime() Returns the last change time of a file filegroup() Returns the group ID of a file fileinode() Returns the inode number of a file filemtime() Returns the last modification time of a file fileowner() Returns the user ID (owner) of a file fileperms() Returns the file's permissions filesize() Returns the file size filetype() Returns the file type flock() Locks or releases a file fnmatch() Matches a filename or string against a specified pattern fopen() Opens a file or URL 143
fpassthru() Reads from the current position in a file - until EOF, and fputcsv() writes the result to the output buffer Formats a line as CSV and writes it to an open file fputs() Alias of fwrite() fread() Reads from an open file (binary-safe) Parses input from an open file according to a specified fscanf() format Seeks in an open file fseek() fstat() Returns information about an open file ftell() ftruncate() Returns the current position in an open file fwrite() Truncates an open file to a specified length glob() Writes to an open file (binary-safe) is_dir() Returns an array of filenames / directories matching a is_executable() specified pattern is_file() Checks whether a file is a directory is_link() is_readable() Checks whether a file is executable is_uploaded_file() is_writable() Checks whether a file is a regular file Checks whether a file is a link Checks whether a file is readable Checks whether a file was uploaded via HTTP POST Checks whether a file is writable is_writeable() Alias of is_writable() lchgrp() Changes the group ownership of a symbolic link lchown() Changes the user ownership of a symbolic link link() Creates a hard link linkinfo() Returns information about a hard link lstat() Returns information about a file or symbolic link mkdir() Creates a directory move_uploaded_file() Moves an uploaded file to a new location parse_ini_file() Parses a configuration file parse_ini_string() Parses a configuration string pathinfo() Returns information about a file path pclose() Closes a pipe opened by popen() popen() Opens a pipe readfile() Reads a file and writes it to the output buffer readlink() Returns the target of a symbolic link realpath() Returns the absolute pathname realpath_cache_get() Returns realpath cache entries realpath_cache_size() Returns realpath cache size rename() Renames a file or directory rewind() Rewinds a file pointer rmdir() Removes an empty directory Alias of stream_set_write_buffer(). Sets the buffer size for set_file_buffer() write operations on the given file 144
stat() Returns information about a file symlink() Creates a symbolic link tempnam() Creates a unique temporary file tmpfile() Creates a unique temporary file touch() Sets access and modification time of a file umask() Changes file permissions for files unlink() Deletes a file 8.7 Filter PHP Filter Functions PHP Filter Introduction This PHP filters is used to validate and filter data coming from insecure sources, like user input. Installation From PHP 5.2.0, the filter functions are enabled by default. There is no installation needed to use these functions. Runtime Configurations The behavior of these functions is affected by settings in php.ini: Name Description Default Changeable filter.default Filter all $_GET, $_POST, $_COOKIE, $_REQUEST and \"unsafe_r PHP_INI_PE $_SERVER data by this filter. Accepts the name of the filter aw\" RDIR filter.default_ you like to use by default. See the filter list for the list of the flags filter names NULL PHP_INI_PE Default flags to apply when the default filter is set. This is set RDIR to FILTER_FLAG_NO_ENCODE_QUOTES by default for backwards compatibility reasons 145
Name Description Default Changeable filter.default Filter all $_GET, $_POST, $_COOKIE, \"unsafe_raw\" PHP_INI_PERDIR $_REQUEST and $_SERVER data by this filter. Accepts the name of the filter you like to use by default. See the filter list for the list of the filter names filter.default_flags Default flags to apply when the NULL PHP_INI_PERDIR default filter is set. This is set to FILTER_FLAG_NO_ENCODE_QUOTES by default for backwards compatibility reasons PHP Filter Functions Function Description filter_has_var() Checks whether a variable of a specified input type exist filter_id() Returns the filter ID of a specified filter name filter_input() Gets an external variable (e.g. from form input) and optionally filters it filter_input_array() Gets external variables (e.g. from form input) and optionally filters them filter_list() Returns a list of all supported filter names filter_var() Filters a variable with a specified filter filter_var_array() Gets multiple variables and filter them PHP Predefined Filter Constants Constant Description INPUT_POST INPUT_GET POST variables INPUT_COOKIE INPUT_ENV GET variables INPUT_SERVER FILTER_DEFAULT COOKIE variables FILTER_FLAG_NONE FILTER_FLAG_ALLOW_OCTAL ENV variables FILTER_FLAG_ALLOW_HEX SERVER variables FILTER_FLAG_STRIP_LOW Do nothing, optionally strip/encode special characters. Equivalent FILTER_FLAG_STRIP_HIGH to FILTER_UNSAFE_RAW FILTER_FLAG_ENCODE_LOW Allows no flags Only for inputs that starts with a zero (0) as octal numbers. This only allows the succeeding digits to be 0-7 Only for inputs that starts with 0x/0X as hexadecimal numbers. This only allows succeeding characters to be a-fA-F0-9 Strip characters with ASCII value lower than 32 Strip characters with ASCII value greater than 127 Encode characters with ASCII value lower than 32 146
FILTER_FLAG_ENCODE_HIGH Encode characters with ASCII value greater than 127 FILTER_FLAG_ENCODE_AMP Encode & FILTER_FLAG_NO_ENCODE_QUOTE S Do not encode ' and \" FILTER_FLAG_EMPTY_STRING_NUL L Not in use FILTER_FLAG_ALLOW_FRACTION FILTER_FLAG_ALLOW_THOUSAND Allows a period (.) as a fractional separator in numbers FILTER_FLAG_ALLOW_SCIENTIFIC Allows a comma (,) as a thousands separator in numbers FILTER_FLAG_PATH_REQUIRED Allows an e or E for scientific notation in numbers FILTER_FLAG_QUERY_REQUIRED The URL must contain a path part FILTER_FLAG_IPV4 The URL must contain a query string FILTER_FLAG_IPV6 Allows the IP address to be in IPv4 format Allows the IP address to be in IPv6 format FILTER_FLAG_NO_RES_RANGE Fails validation for the reserved IPv4 ranges: 0.0.0.0/8, 169.254.0.0/16, 127.0.0.0/8 and 240.0.0.0/4, and for the reserved FILTER_FLAG_NO_PRIV_RANGE IPv6 ranges: ::1/128, ::/128, ::ffff:0:0/96 and fe80::/10 Fails validation for the private IPv4 ranges: 10.0.0.0/8, FILTER_FLAG_EMAIL_UNICODE 172.16.0.0/12 and 192.168.0.0/16, and for the IPv6 addresses starting with FD or FC FILTER_REQUIRE_SCALAR Allows the local part of the email address to contain Unicode FILTER_REQUIRE_ARRAY characters FILTER_FORCE_ARRAY The value must be a scalar FILTER_NULL_ON_FAILURE The value must be an array FILTER_VALIDATE_BOOLEAN Treats a scalar value as array with the scalar value as only element FILTER_VALIDATE_EMAIL Return NULL on failure for unrecognized boolean values FILTER_VALIDATE_FLOAT Validates a boolean FILTER_VALIDATE_INT Validates value as a valid e-mail address FILTER_VALIDATE_IP Validates value as float FILTER_VALIDATE_MAC Validates value as integer FILTER_VALIDATE_REGEXP Validates value as IP address FILTER_VALIDATE_URL Validates value as MAC address FILTER_SANITIZE_EMAIL Validates value against a regular expression FILTER_SANITIZE_ENCODED Validates value as URL FILTER_SANITIZE_MAGIC_QUOTES Removes all illegal characters from an e-mail address FILTER_SANITIZE_NUMBER_FLOAT Removes/Encodes special characters FILTER_SANITIZE_NUMBER_INT Apply addslashes() FILTER_SANITIZE_SPECIAL_CHARS Remove all characters, except digits, +- signs, and optionally .,eE FILTER_SANITIZE_STRING Removes all characters except digits and + - signs FILTER_SANITIZE_STRIPPED Removes special characters FILTER_SANITIZE_URL Removes tags/special characters from a string FILTER_UNSAFE_RAW Alias of FILTER_SANITIZE_STRING FILTER_CALLBACK Removes all illegal character from s URL Do nothing, optionally strip/encode special characters Call a user-defined function to filter data 147
Search
Read the Text Version
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
- 117
- 118
- 119
- 120
- 121
- 122
- 123
- 124
- 125
- 126
- 127
- 128
- 129
- 130
- 131
- 132
- 133
- 134
- 135
- 136
- 137
- 138
- 139
- 140
- 141
- 142
- 143
- 144
- 145
- 146
- 147
- 148
- 149
- 150
- 151
- 152
- 153
- 154
- 155
- 156
- 157
- 158
- 159
- 160
- 161
- 162
- 163
- 164
- 165
- 166
- 167
- 168
- 169
- 170
- 171
- 172
- 173
- 174
- 175
- 176
- 177
- 178
- 179