Friday 13 July 2018

PHP MySQL: Querying Data from Database

PHP MySQL: Querying Data from Database?

Summaryin this tutorial, you will learn how to query data from MySQL database by using PHP PDO. You will also learn how to use PDO prepared statement to select data securely.

PHP MySQL Querying data using simple SELECT statement

To query data from the MySQL database, follow the steps below:
First, connect to a MySQL database. Check it out the connecting to MySQL database using PDO tutorial for detail information.
Then, construct a SELECT statement and execute it by using the query() method of the PDO object.
The query() method of the PDO object returns a PDOStatement object, or false on failure.
Next, set the PDO::FETCH_ASSOC fetch mode for the PDOStatement object by using the setFetchMode()method. The PDO::FETCH_ASSOC mode instructs the fetch() method to return a result set as an array indexed by column name.
After that, fetch each row from the result set until there is no row left by using the fetch() method of the PDOStatement object.
Putting it all together.

PHP MySQL Querying data using PDO prepared statement

In practice, we often pass the argument from PHP to the SQL statement e.g., get the employee whose last name ends with son . To do it securely and avoid SQL injection attack, you need to use the PDO prepared statement.
Let’s take a look at the following example:
How the script works.
  • First, we use a question mark (?) in the SELECT statement. PDO will replace the question mark in the query by the corresponding argument. The question mark is called positional placeholder.
  • Next, we call the prepare() method of the PDO object to prepare the SQL statement for the execution.
  • Then, we execute the statement by calling the execute() method of the PDOStatement object. In addition, we pass an argument as an array to replace the placeholder in the SELECT statement. By doing this, the SELECT statement will be translated as follows:
  • After that, we set the fetch mode for the PDOStatement object.
  • Finally, we fetch each row of the result set and display the last name field.
PHP provides you with another way to use placeholders in the prepared statement called named placeholder. The advantages of using the named placeholder are:
  • More descriptive.
  • If the SQL statement has multiple placeholders, it is easier pass the arguments to the execute()method.
Let’s take a look at the following example:
The :lname and :fname are the named placeholders. They are substituted by the corresponding argument in the associative array that we pass to the execute method.
In this tutorial, you have learned how to query data from MySQL database using PDO objects.

0 comments:

Post a Comment