Creating MySQL Table

MySQL — Select Query

The SQL SELECT command is used to fetch data from the MySQL database. You can use this command at mysql> prompt as well as in any script like PHP.

Syntax

Here is generic SQL syntax of SELECT command to fetch data from the MySQL table −

SELECT field1, field2. fieldN FROM table_name1, table_name2. [WHERE Clause] [OFFSET M ][LIMIT N]
  • You can use one or more tables separated by comma to include various conditions using a WHERE clause, but the WHERE clause is an optional part of the SELECT command.
  • You can fetch one or more fields in a single SELECT command.
  • You can specify star (*) in place of fields. In this case, SELECT will return all the fields.
  • You can specify any condition using the WHERE clause.
  • You can specify an offset using OFFSET from where SELECT will start returning records. By default, the offset starts at zero.
  • You can limit the number of returns using the LIMIT attribute.

Fetching Data from a Command Prompt

This will use SQL SELECT command to fetch data from the MySQL table tutorials_tbl.

Example

The following example will return all the records from the tutorials_tbl table −

root@host# mysql -u root -p password; Enter password:******* mysql> use TUTORIALS; Database changed mysql> SELECT * from tutorials_tbl +-------------+----------------+-----------------+-----------------+ | tutorial_id | tutorial_title | tutorial_author | submission_date | +-------------+----------------+-----------------+-----------------+ | 1 | Learn PHP | John Poul | 2007-05-21 | | 2 | Learn MySQL | Abdul S | 2007-05-21 | | 3 | JAVA Tutorial | Sanjay | 2007-05-21 | +-------------+----------------+-----------------+-----------------+ 3 rows in set (0.01 sec) mysql>

Fetching Data Using a PHP Script

PHP uses mysqli query() or mysql_query() function to select records from a MySQL table. This function takes two parameters and returns TRUE on success or FALSE on failure.

Читайте также:  Номер телефона regex java

Syntax

Required — SQL query to select records from a MySQL table.

Optional — Either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT depending on the desired behavior. By default, MYSQLI_STORE_RESULT is used.

Example

Try the following example to select a record from a table −

Copy and paste the following example as mysql_example.php −

    connect_errno ) < printf("Connect failed: %s
", $mysqli->connect_error); exit(); > printf('Connected successfully.
'); $sql = "SELECT tutorial_id, tutorial_title, tutorial_author, submission_date FROM tutorials_tbl"; $result = $mysqli->query($sql); if ($result->num_rows > 0) < while($row = $result->fetch_assoc()) < printf("Id: %s, Title: %s, Author: %s, Date: %d
", $row["tutorial_id"], $row["tutorial_title"], $row["tutorial_author"], $row["submission_date"]); > > else < printf('No record found.
'); > mysqli_free_result($result); $mysqli->close(); ?>

Output

Access the mysql_example.php deployed on apache web server and verify the output. Here we’ve entered multiple records in the table before running the select script.

Connected successfully. Id: 1, Title: MySQL Tutorial, Author: Mahesh, Date: 2021 Id: 2, Title: HTML Tutorial, Author: Mahesh, Date: 2021 Id: 3, Title: PHP Tutorial, Author: Mahesh, Date: 2021 Id: 4, Title: Java Tutorial, Author: Mahesh, Date: 2021 Id: 5, Title: Apache Tutorial, Author: Suresh, Date: 2021

Источник

MySQLi — Select Query

The SQL SELECT command is used to fetch data from the MySQL database. You can use this command at mysql> prompt as well as in any script like PHP.

Syntax

Here is generic SQL syntax of SELECT command to fetch data from the MySQL table −

SELECT field1, field2. fieldN FROM table_name1, table_name2. [WHERE Clause] [OFFSET M ][LIMIT N]
  • You can use one or more tables separated by comma to include various conditions using a WHERE clause, but the WHERE clause is an optional part of the SELECT command.
  • You can fetch one or more fields in a single SELECT command.
  • You can specify star (*) in place of fields. In this case, SELECT will return all the fields.
  • You can specify any condition using the WHERE clause.
  • You can specify an offset using OFFSET from where SELECT will start returning records. By default, the offset starts at zero.
  • You can limit the number of returns using the LIMIT attribute.

Fetching Data from a Command Prompt

This will use SQL SELECT command to fetch data from the MySQL table tutorials_tbl.

Example

The following example will return all the records from the tutorials_tbl table −

root@host# mysql -u root -p password; Enter password:******* mysql> use TUTORIALS; Database changed mysql> SELECT * from tutorials_tbl +-------------+----------------+-----------------+-----------------+ | tutorial_id | tutorial_title | tutorial_author | submission_date | +-------------+----------------+-----------------+-----------------+ | 1 | Learn PHP | John Poul | 2007-05-21 | | 2 | Learn MySQL | Abdul S | 2007-05-21 | | 3 | JAVA Tutorial | Sanjay | 2007-05-21 | +-------------+----------------+-----------------+-----------------+ 3 rows in set (0.01 sec) mysql>

Fetching Data Using a PHP Script

PHP uses mysqli query() or mysql_query() function to select records from a MySQL table. This function takes two parameters and returns TRUE on success or FALSE on failure.

Syntax

Required — SQL query to select records from a MySQL table.

Optional — Either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT depending on the desired behavior. By default, MYSQLI_STORE_RESULT is used.

Example

Try the following example to select a record from a table −

Copy and paste the following example as mysql_example.php −

    ", $mysqli→connect_error); exit(); > printf('Connected successfully.
'); $sql = "SELECT tutorial_id, tutorial_title, tutorial_author, submission_date FROM tutorials_tbl"; $result = $mysqli->query($sql); if ($result->num_rows > 0) < while($row = $result->fetch_assoc()) < printf("Id: %s, Title: %s, Author: %s, Date: %d
", $row["tutorial_id"], $row["tutorial_title"], $row["tutorial_author"], $row["submission_date"]); > > else < printf('No record found.
'); > mysqli_free_result($result); $mysqli→close(); ?>

Output

Access the mysql_example.php deployed on apache web server and verify the output. Here we’ve entered multiple records in the table before running the select script.

Connected successfully. Id: 1, Title: MySQL Tutorial, Author: Mahesh, Date: 2021 Id: 2, Title: HTML Tutorial, Author: Mahesh, Date: 2021 Id: 3, Title: PHP Tutorial, Author: Mahesh, Date: 2021 Id: 4, Title: Java Tutorial, Author: Mahesh, Date: 2021 Id: 5, Title: Apache Tutorial, Author: Suresh, Date: 2021

Источник

Выборка записей при SQL запросе к базе в PHP

В тестовом коде вы уже видели команду SELECT , выполняющую выборку данных из БД. Давайте теперь подробнее разберемся с ее синтаксисом. Вот он:

Как вы видите, после имени таблицы можно еще дописать команду WHERE, в которой можно писать ограничение на выбираемые записи. В условии допустимы следующие операции сравнения: = , != , <> , , > , , >= .

Давайте посмотрим их применение на примерах.

Пример

Выберем юзера с id , равным 2 :

Пример

Выберем юзеров с id , большим 2 :

Пример

Выберем юзеров с id , большим или равным 2 :

Пример

Выберем юзеров с id , не равным 2 :

Пример

Вместо команды != можно писать команду <> :

Пример

Выберем юзеров возрастом 23 года:

Пример

Выберем юзеров с зарплатой 500 :

Пример

Выберем юзера с именем ‘user1’ . Здесь нас поджидает важный нюанс: так как имя является строкой, то его необходимо взять в кавычки:

Пример

Если команда WHERE отсутствует, то выберутся все записи из таблицы. Давайте выберем всех работников:

Практические задачи

Выберите юзера с id , равным 3 .

Выберите юзеров с зарплатой 900 .

Выберите юзеров в возрасте 23 года.

Выберите юзеров с зарплатой более 400 .

Выберите юзеров с зарплатой равной или большей 500 .

Выберите юзеров с зарплатой НЕ равной 500 .

Выберите юзеров с зарплатой равной или меньшей 500 .

Источник

Оцените статью