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 renders as emphasized text, displaying the text oblique?
<strong> <pre> <em>
<p>Web development courses: <em>CoursesWeb.net</em></p>
Which CSS property defines the space between the element border and its content?
margin padding position
h3 {
  padding: 2px 0.2em;
}
Click on the method which returns the first element that matches a specified group of selectors.
getElementsByName() querySelector() querySelectorAll()
// gets first Div with class="cls", and shows its content
var elm = document.querySelector("div.cls");
alert(elm.innerHTML);
Indicate the PHP variable that contains data from a form sent with method="post".
$_SESSION $_GET $_POST
if(isset($_POST["field"])) {
  echo $_POST["field"];
}
PHP MySQL - SELECT, ORDER BY

Last accessed pages

  1. Zodiac Signs PHP code (7110)
  2. jQuery Drag and Drop Rows between two similar Tables (12788)
  3. SHA1 Encrypt data in JavaScript (35309)
  4. Upload Script for Gallery of Images and Audio files (9695)
  5. Read Excel file data in PHP - PhpExcelReader (96682)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (229)
  2. Read Excel file data in PHP - PhpExcelReader (83)
  3. PHP Unzipper - Extract Zip, Rar Archives (72)
  4. The Four Agreements (69)
  5. The Mastery of Love (59)