SELECT queries should use getOne, getRow or getRows.
public query ( $sql ) : resource | false | ||
return | resource | false |
$dsn = 'mysql:host=localhost;dbname=db_name'; $username = 'user_name'; $password = 'user_password'; try { $pdo = new PDO($dsn, $username, $password); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Retrieve data from the database $query = "SELECT * FROM table_name"; $stmt = $pdo->query($query); $result = $stmt->fetchAll(PDO::FETCH_ASSOC); // Display the data print_r($result); } catch (PDOException $e) { echo 'Connection failed: ' . $e->getMessage(); }
$dsn = 'pgsql:host=localhost;port=5432;dbname=db_name'; $username = 'user_name'; $password = 'user_password'; try { $pdo = new PDO($dsn, $username, $password); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Update data in the database $query = "UPDATE table_name SET column_name = :value WHERE id = :id"; $stmt = $pdo->prepare($query); $stmt->bindParam(':value', $value); $stmt->bindParam(':id', $id); $stmt->execute(); } catch (PDOException $e) { echo 'Connection failed: ' . $e->getMessage(); }In this example, we are connecting to a PostgreSQL database using PDO and updating a record in a table using a prepared statement. The values of the placeholders are bound before the statement is executed, preventing SQL injection attacks. Both of these examples use the PDO library to interact with the database. PDO is a PHP extension that provides a consistent interface for working with different database engines. It supports prepared statements, multiple database connections, and error handling.
public query ( $sql ) : resource | false | ||
return | resource | false |