PHP mysqli_query Function
Let us explore.
The following snippet below illustrates the function syntax in procedural format.
The function accepts the following parameters:
- mysql – this defines a mysqli object returned from the mysqli_connect or mysqli_init() functions.
- query – this defines a query string executed on the target database. PHP recommends using parameterized prepared statements if the query contains any variable input. Alternatively, the input must be properly formatted, and strings escaped to prevent SQL Injections.
- result_mode – this parameter defines the result mode defining how the result will be returned from the server. The accepted parameters include the following:
- MYSQLI_STORE_RESULT – returns the result as a mysqli_result object with a buffered result set.
- MYSQLI_USE_RESULT – returns the result as an unbuffered mysqli_result object.
- MYSQLI_ASYNC – this performs the defined query asynchronously, and no result is returned immediately. Instead, the function performs the query and then uses the mysqli_poll() function to return all the results from the query.
The function returns false on failure. If successful, the function performs the actions defined in the query, such as SELECT, SHOW, DESCRIBE, etc.
Example Function Usage
The following shows an example of usage of the mysqli_query function. Start by creating a sample database, table, and data as shown in the queries below:
Example – Using PHP mysqli_query() Function to Fetch Records
The example below illustrates how to use the function to fetch the records from the table:
In this case, the function above connects to the database and then uses the mysqli_function to fetch the rows from the stack_mapping table.
Finally, we determine the number of returned rows using the mysqli_num_rows function. The resulting output is as shown:
NOTE: If you have a large amount of data to fetch, use the MYSQLI_USE_RESULT result mode.
In this post, we discussed how to use the mysqli_fetch function in PHP to perform a given query to a database.
Thanks for reading!!