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 to add lists into <ul> and <ol> elements?
<dt> <dd> <li>
<ul>
 <li>http://coursesweb.net/html/</li>
 <li>http://coursesweb.net/css/</li>
</ul>
Which value of the "display" property creates a block box for the content and ads a bullet marker?
block list-item inline-block
.some_class {
  display: list-item;
}
Which instruction converts a JavaScript object into a JSON string.
JSON.parse() JSON.stringify eval()
var obj = {
 "courses": ["php", "javascript", "ajax"]
};
var jsonstr = JSON.stringify(obj);
alert(jsonstr);    // {"courses":["php","javascript","ajax"]}
Indicate the PHP class used to work with HTML and XML content in PHP.
stdClass PDO DOMDocument
$strhtml = '<body><div id="dv1">CoursesWeb.net</div></body>';
$dochtml = new DOMDocument();
$dochtml->loadHTML($strhtml);
$elm = $dochtml->getElementById("dv1");
echo $elm->nodeValue;    // CoursesWeb.net
PHP MySQL - SELECT, ORDER BY

Last accessed pages

  1. Get Mime Type of file or string content in PHP (6228)
  2. Get and Modify content of an Iframe (32346)
  3. Making DIV Contents Scroll Horizontally, with multiple Div`s inside (59589)
  4. querySelector and querySelectorAll (30124)
  5. sPBM - Simple PHP Backup Manager (3402)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (473)
  2. CSS cursor property - Custom Cursors (79)
  3. The Mastery of Love (70)
  4. PHP-MySQL free course, online tutorials PHP MySQL code (62)
  5. CSS3 2D transforms (46)