How to run query in PHP?

by tressie.damore , in category: PHP General , 9 months ago

How to run query in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by cali_green , 3 months ago


To run a query in PHP, you can use the mysqli_query() function. This function takes two arguments: a connection to the database, and the query that you want to run.

Here is an example:

$connection = mysqli_connect('localhost', 'user', 'password', 'database_name');

$query = 'SELECT * FROM users';

$result = mysqli_query($connection, $query);

This code connects to the database, then runs a SELECT query to get all rows from the users table. The result of the query is stored in the $result variable.

You can then use the mysqli_fetch_assoc() function to retrieve the rows from the result one at a time, like this:

while ($row = mysqli_fetch_assoc($result)) {

This code will loop through the rows in the $result variable and print each row to the screen.

Keep in mind that this is just an example, and you will need to adjust it to fit your specific needs. For example, you may want to use different database connection settings, or a different query. You should also make sure to handle any errors that may occur, such as if the database connection fails or the query is invalid.

I hope this helps! Let me know if you have any other questions.