How to run query in PHP?

by tressie.damore , in category: PHP General , 2 years ago

How to run query in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by cali_green , 2 years ago

@tressie.damore 

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:

1
2
3
4
5
$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:

1
2
3
while ($row = mysqli_fetch_assoc($result)) {
    print_r($row);
}


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.

by darrion.kuhn , a year ago

@tressie.damore 

To run a query in PHP, you can use the PDO or mysqli extension. Here's an example of running a query using PDO:

  1. Establish a database connection:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
$dsn = "mysql:host=localhost;dbname=your_database;charset=utf8mb4";
$username = "your_username";
$password = "your_password";

try {
    $pdo = new PDO($dsn, $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}


  1. Prepare and execute the query:
1
2
3
4
$sql = "SELECT * FROM your_table WHERE column = :value";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':value', $value);
$stmt->execute();


  1. Fetch and handle the results:
1
2
3
4
5
6
while ($row = $stmt->fetch()) {
    // Handle each row of the result
    $column1 = $row['column1'];
    $column2 = $row['column2'];
    // ...
}


Remember to replace your_database, your_username, your_password, your_table, column, and $value with your own values.


Note: This example uses parameterized queries to prevent SQL injection. It is recommended to always use parameterized queries or prepared statements for running queries in PHP to enhance security.