note 127606 added to class.pdo

From: Date: Fri, 09 Sep 2022 11:11:46 +0000
Subject: note 127606 added to class.pdo
Groups: php.notes 
Request: Send a blank email to php-notes+get-219549@lists.php.net to get a copy of this message
//# Simple Example of PDO connection <?php $servername = "localhost"; $username = "username"; $password = "password"; $dbName = "myDB"; //## create connection try { $conn = new PDO("mysql:host=$servername;dbname=$dbName", $username, $password); // set the PDO error mode to exception $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); echo "Connected successfully"; //## create database $sql = "CREATE DATABASE myDBPDO"; // use exec() because no results are returned $conn->exec($sql); echo "Database created successfully<br>"; //## create table $sql = "CREATE TABLE MyGuests ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, firstname VARCHAR(30) NOT NULL, lastname VARCHAR(30) NOT NULL, email VARCHAR(50), reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP )"; $conn->exec($sql); echo "Table MyGuests created successfully"; //## insert data $sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com')"; $conn->exec($sql); echo "New record created successfully"; //## prepared statement // prepare sql and bind parameters $stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (:firstname, :lastname, :email)"); $stmt->bindParam(':firstname', $firstname); $stmt->bindParam(':lastname', $lastname); $stmt->bindParam(':email', $email); // insert a row $firstname = "John"; $lastname = "Doe"; $email = "john@example.com"; $stmt->execute(); // insert another row $firstname = "Mary"; $lastname = "Moe"; $email = "mary@example.com"; $stmt->execute(); } catch(PDOException $e) { echo "Connection failed: " . $e->getMessage(); } //## close connection $conn = null; ?> //### Sources //This code example has been sourced from snippets published under the source below. //PHP MySQL Database. (w3schools). Retrieved September 9, 2022, from https://www.w3schools.com/Php/php_mysql_intro.asp and subsequent pages ---- Server IP: 45.112.84.4 Probable Submitter: 185.85.3.173 (proxied: 185.210.219.194) ---- Manual Page -- https://php.net/manual/en/class.pdo.php Edit -- https://main.php.net/note/edit/127606 Del: integrated -- https://main.php.net/note/delete/127606/integrated Del: useless -- https://main.php.net/note/delete/127606/useless Del: bad code -- https://main.php.net/note/delete/127606/bad+code Del: spam -- https://main.php.net/note/delete/127606/spam Del: non-english -- https://main.php.net/note/delete/127606/non-english Del: in docs -- https://main.php.net/note/delete/127606/in+docs Del: other reasons-- https://main.php.net/note/delete/127606 Reject -- https://main.php.net/note/reject/127606 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#219549) next »