note 130106 added to class.pdo

From: Date: Sat, 01 Mar 2025 13:53:13 +0000
Subject: note 130106 added to class.pdo
Groups: php.notes 
Request: Send a blank email to php-notes+get-221932@lists.php.net to get a copy of this message
This is how I use PDO to connect to my database: <?php // Access to DB $host = "db"; $db = "mydatabase"; $dsn = "mysql:host=$host;dbname=$db;charset=utf8mb4"; $options = [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC ]; // Defining credentials $user = "user"; $passwd = "password"; try { $pdo = new PDO($dsn, $user, $passwd, $options); // Catching any error } catch (PDOException $e) { error_log("Connection failed " . $e->getMessage()); die(json_encode(["error" => "Failed to connect to database: " . $e->getMessage()])); } // Example of a query with PDO: $input = json_decode(file_get_contents('php://input'), true); $product_name = $input['product']; try { $query = " INSERT INTO List (product_name) VALUES (:product) "; $stmt = $pdo->prepare($query); $stmt->execute(['product' => $product_name]); http_response_code(201); echo json_encode(["success" => "Product added"]); } catch (Exception $e) { http_response_code(500); echo json_encode(["error" => "SQL error " . $e->getMessage()]); ?> ---- Server IP: 45.112.84.4 Probable Submitter: 45.112.84.18 (proxied: 142.137.164.104) ---- Manual Page -- https://php.net/manual/en/class.pdo.php Edit -- https://main.php.net/note/edit/130106 Del: integrated -- https://main.php.net/note/delete/130106/integrated Del: useless -- https://main.php.net/note/delete/130106/useless Del: bad code -- https://main.php.net/note/delete/130106/bad+code Del: spam -- https://main.php.net/note/delete/130106/spam Del: non-english -- https://main.php.net/note/delete/130106/non-english Del: in docs -- https://main.php.net/note/delete/130106/in+docs Del: other reasons-- https://main.php.net/note/delete/130106 Reject -- https://main.php.net/note/reject/130106 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#221932) next »