Skip to main content

MySQL Databases PDO

PHP MySQL Use The ORDER BY Clause Select and Order Data From a MySQL Database The ORDER BY clause is used to sort the result-set in ascending or descending order. The ORDER BY clause sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword. SELECT column_name(s) FROM table_name ORDER BY column_name(s) ASC|DESC To learn more about SQL, please visit our SQL tutorial. Select and Order Data With MySQLi The following example selects the id, firstname and lastname columns from the MyGuests table. The records will be ordered by the lastname column: Example (MySQLi Object-oriented) connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "SELECT id, firstname, lastname FROM MyGuests ORDER BY lastname"; $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"]. "
"; } } else { echo "0 results"; } $conn->close(); ?> Code lines to explain from the example above: First, we set up the SQL query that selects the id, firstname and lastname columns from the MyGuests table. The records will be ordered by the lastname column. 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) 0) { // output data of each row while($row = mysqli_fetch_assoc($result)) { echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "
"; } } else { echo "0 results"; } mysqli_close($conn); ?> You can also put the result in an HTML table: Example (MySQLi Object-oriented) connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "SELECT id, firstname, lastname FROM MyGuests ORDER BY lastname"; $result = $conn->query($sql); if ($result->num_rows > 0) { echo ""; // output data of each row while($row = $result->fetch_assoc()) { echo ""; } echo "
IDName
".$row["id"]."".$row["firstname"]." ".$row["lastname"]."
"; } else { echo "0 results"; } $conn->close(); ?> Select Data With PDO (+ Prepared Statements) The following example uses prepared statements. Here we select the id, firstname and lastname columns from the MyGuests table. The records will be ordered by the lastname column, and it will be displayed in an HTML table: Example (PDO) "; echo "IdFirstnameLastname"; class TableRows extends RecursiveIteratorIterator { function __construct($it) { parent::__construct($it, self::LEAVES_ONLY); } function current() { return "" . parent::current(). ""; } function beginChildren() { echo ""; } function endChildren() { echo "" . "\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 ORDER BY lastname"); $stmt->execute(); // 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 ""; ?> PHP MySQL Delete Data 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 john@example.com 2014-10-22 14:26:15 2 Mary Moe mary@example.com 2014-10-23 10:22:30 3 Julie Dooley julie@example.com 2014-10-26 10:48:23 The following examples delete the record with id=3 in the "MyGuests" table: Example (MySQLi Object-oriented) 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) Example (PDO) 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 . "
" . $e->getMessage(); } $conn = null; ?> After the record is deleted, the table will look like this: id firstname lastname email reg_date 1 John Doe john@example.com 2014-10-22 14:26:15 2 Mary Moe mary@example.com 2014-10-23 10:22:30 PHP MySQL Update Data 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 john@example.com 2014-10-22 14:26:15 2 Mary Moe mary@example.com 2014-10-23 10:22:30 The following examples update the record with id=2 in the "MyGuests" table: Example (MySQLi Object-oriented) connect_error) { die("Connection failed: " . $conn->connect_error); } $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) Example (PDO) 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 . "
" . $e->getMessage(); } $conn = null; ?> After the record is updated, the table will look like this: id firstname lastname email reg_date 1 John Doe john@example.com 2014-10-22 14:26:15 2 Mary Doe mary@example.com 2014-10-23 10:22:30 PHP MySQL Limit Data Selections Limit Data Selections From a MySQL Database MySQL provides a LIMIT clause that is used to specify the number of records to return. 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.

Comments

Popular posts from this blog

PHP OOP

PHP - What is OOP? From PHP5, you can also write PHP code in an object-oriented style. Object-Oriented programming is faster and easier to execute. PHP What is OOP? OOP stands for Object-Oriented Programming. Procedural programming is about writing procedures or functions that perform operations on the data, while object-oriented programming is about creating objects that contain both data and functions. Object-oriented programming has several advantages over procedural programming: OOP is faster and easier to execute OOP provides a clear structure for the programs OOP helps to keep the PHP code DRY "Don't Repeat Yourself", and makes the code easier to maintain, modify and debug OOP makes it possible to create full reusable applications with less code and shorter development time Tip: The "Don't Repeat Yourself" (DRY) principle is about reducing the repetition of code. You should extract out the codes that are common for the applicatio

PHP - AJAX

PHP - AJAX Introduction AJAX is about updating parts of a web page, without reloading the whole page. What is AJAX? AJAX = Asynchronous JavaScript and XML. AJAX is a technique for creating fast and dynamic web pages. AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page. Classic web pages, (which do not use AJAX) must reload the entire page if the content should change. Examples of applications using AJAX: Google Maps, Gmail, Youtube, and Facebook tabs. How AJAX Works AJAX AJAX is Based on Internet Standards AJAX is based on internet standards, and uses a combination of: XMLHttpRequest object (to exchange data asynchronously with a server) JavaScript/DOM (to display/interact with the information) CSS (to style the data) XML (often used as the format for transferring data) AJAX applications are browse