How to execute simple SQL query in PHP?

WBOY
Release: 2024-05-04 09:24:02
Original
942 people have browsed it

Steps to execute SQL query in PHP: Connect to the database (mysqli_connect) Execute the query (mysqli_query) Get the query results (mysqli_fetch_assoc)

How to execute simple SQL query in PHP?

How to execute a simple query in PHP SQL Query

Executing simple SQL queries in PHP is very easy. First, you need to connect to the database. This can be done through the mysqli_connect() function, where the four parameters correspond to the database server, username, password and database name. For example:

$db_host = 'localhost';
$db_username = 'root';
$db_password = 'password';
$db_name = 'database_name';
$mysqli = mysqli_connect($db_host, $db_username, $db_password, $db_name);
Copy after login

After establishing a database connection, you can use the mysqli_query() function to execute SQL queries. This function takes the query string as its first parameter and the connection object as its second parameter. It returns a result object containing the query results, or FALSE if the query fails. For example:

$query = "SELECT * FROM users";
$result = mysqli_query($mysqli, $query);
Copy after login

The result object can be used to obtain query results. The most commonly used method is mysqli_fetch_assoc(), which returns the current row in the result object as an associative array. For example:

while ($row = mysqli_fetch_assoc($result)) {
  echo $row['name'] . '<br>';
}
Copy after login

This loop will print out the name column for each row in the query results.

Practical case

The following is a sample code to obtain all user records in the database:

Copy after login

You need to remember that users must be authenticated before executing SQL queries Input to prevent SQL injection attacks.

The above is the detailed content of How to execute simple SQL query in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template