Php-mysql Course

When the database has some records in it, you can retrieve the stored information with the SELECT statement.
A SELECT query returns rows selected from one or more tables.

  - Syntax:
SELECT column_name(s) FROM table_name
- "column_name(s)" - is the name of the column (or columns) you want to select.
To select multiple columns, add them separated by a comma:
                SELECT column1, column2, column3 FROM table_name
To sellect all columns, just put an asterisk (*):
                SELECT * FROM table_name

To send the SQL statement to the MySQL database and retrieve the data returned, use the query() method of the mysqli object.
When is used with SELECT queries, this method returns a result object that stores the rows of data, or False on error.
To provide one row of data at a time, you can use a method of the result object called fetch_assoc.
The fetch_assoc() method returns an associative array that corresponds to the fetched row, the keys of the elements are the name of the columns. With a while() loop we can get the data of each row stored in that array.
To get the numbers of rows returned by a SELECT query, use the num_rows method, applied to the result object.

  - The fallowing example selects and displays the data stored in the "id", "name" and "pass" columns in the "users" table.
<?php
// connect to the "tests" database
$conn = new mysqli('localhost', 'root', 'pass', 'tests');

// check connection
if (mysqli_connect_errno()) {
  exit('Connect failed: '. mysqli_connect_error());
}

// SELECT sql query
$sql = "SELECT `id`, `name`, `pass` FROM `users`"; 

// perform the query and store the result
$result = $conn->query($sql);

// if the $result contains at least one row
if ($result->num_rows > 0) {
  // output data of each row from $result
  while($row = $result->fetch_assoc()) {
    echo '<br /> id: '. $row['id']. ' - name: '. $row['name']. ' - pass: '. $row['pass'];
  }
}
else {
  echo '0 results';
}

$conn->close();
?>
- This example stores the data (the result object) returned by the query() method in the $result variable, uses the "num_rows" method to check if $result contains at least one row. Then, with a while() loop loops through all the records in the result object, using the "fetch_assoc()" method to store the data of each row in an Array in the $row variable.
Each call to fetch_assoc() returns the next row in the recordset.
To print the value of each row, we use the PHP $row variable and the key of each column ($row['id'], ...).
The code above will output:
id: 1 - name: Marius - pass: faith
id: 2 - name: MarPlo - pass: peace
id: 3 - name: I_AM - pass: love
id: 4 - name: PloMar - pass: love_light

The asterisk (*) can be used to select all column: "SELECT * FROM table_name", but is better to be explicit about which columns are selected. The selecting process can be faster if only the columns you will use are fetched.

The LIMIT option

With the LIMIT option you can determine the number of records that MySQL will return.
  - Syntax:
SELECT column_names FROM table_name LIMIT skip_count, show_count
"skip_count" is optional, it tells the database how many rows to skip from results.
"show_count" sets the maximum number of records to return.
  - Example:
<?php
// connect to the "tests" database
$conn = new mysqli('localhost', 'root', 'pass', 'tests');

// check connection
if (mysqli_connect_errno()) {
  exit('Connect failed: '. mysqli_connect_error());
}

// SELECT sql query
$sql = "SELECT `id`, `name`, `pass` FROM `users` LIMIT 2"; 

// perform the query and store the result
$result = $conn->query($sql);

// if the $result contains at least one row
if ($result->num_rows > 0) {
  // output data of each row from $result
  while($row = $result->fetch_assoc()) {
    echo '<br /> id: '. $row['id']. ' - name: '. $row['name']. ' - pass: '. $row['pass'];
  }
}
else {
  echo '0 results';
}

$conn->close();
?>
The "LIMIT 2" option tells MySQL to return only the firs 2 rows in result.
This example will output:
id: 1 - name: Marius - pass: faith
id: 2 - name: MarPlo - pass: peace

ORDER BY

ORDER BY specifies the sort order of the results.
  - Syntax:
SELECT column_names FROM table_name ORDER BY col_name ASC|DESC
"col_name" can be a single column, a comma separated list of columns, or an expression such as RAND(), which randomizes the order.
When ordering by more than one column, the second column is only used if the values in the first column are equal.
The default sort order is ascending (ASC) (a–z, 0–9), and ASC option can be omitted. DESC (descending) reverses the order.
  - Example:
<?php
// connect to the "tests" database
$conn = new mysqli('localhost', 'root', 'pass', 'tests');

// check connection
if (mysqli_connect_errno()) {
  exit('Connect failed: '. mysqli_connect_error());
}

// SELECT sql query
$sql = "SELECT `id`, `name`, `pass` FROM `users` ORDER BY `name`"; 

// perform the query and store the result
$result = $conn->query($sql);

// if the $result contains at least one row
if ($result->num_rows > 0) {
  // output data of each row from $result
  while($row = $result->fetch_assoc()) {
    echo '<br /> id: '. $row['id']. ' - name: '. $row['name']. ' - pass: '. $row['pass'];
  }
}
else {
  echo '0 results';
}

$conn->close();
?>
- This code selects all the data stored in the "users" table, and sorts the result in alphabetical order by the "name" column.
This example above will output:
id: 3 - name: I_AM - pass: love
id: 1 - name: Marius - pass: faith
id: 2 - name: MarPlo - pass: peace
id: 4 - name: PloMar - pass: love_light

• You can use ORDER BY with LIMIT option.
                Example:       "SELECT `id`, `name`, `pass` FROM `users` ORDER BY `name` LIMIT 2"

• To eliminate duplicate rows from the results, use the DISTINCT option:
               
SELECT DISTINCT column_names FROM table_name

- If you want to learn how to select values from two MySQL tables with a single query, see the tutorial: Select in two MySQL tables.

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which tag is used in <table> to create table header cell?
<thead> <th> <td>
<table><tr>
  <th>Title 1</th>
  <th>Title 2</th>
</tr></table>
Which CSS property sets the distance between lines?
line-height word-spacing margin
.some_class {
  line-height: 150%;
}
Which function opens a new browser window.
alert() confirm() open()
document.getElementById("id_button").onclick = function(){
  window.open("http://coursesweb.net/");
}
Indicate the PHP function that returns an array with names of the files and folders inside a directory.
mkdir() scandir() readdir()
$ar_dir = scandir("dir_name");
var_export($ar_dir);
PHP MySQL - SELECT, ORDER BY

Last accessed pages

  1. Line and Text (1347)
  2. Validate radio and checkbox buttons (10078)
  3. CSS Content (425)
  4. Animated Tooltip with HTML and CSS (284)
  5. MySQLDumper - Backup MySQL Database (1782)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (543)
  2. The Mastery of Love (65)
  3. CSS cursor property - Custom Cursors (63)
  4. Read Excel file data in PHP - PhpExcelReader (59)
  5. PHP-MySQL free course, online tutorials PHP MySQL code (44)