note 127607 added to class.pdo

From: Date: Fri, 09 Sep 2022 12:04:03 +0000
Subject: note 127607 added to class.pdo
Groups: php.notes 
Request: Send a blank email to php-notes+get-219550@lists.php.net to get a copy of this message
<?php //# 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; ?> <?php //### Sources //This code example has been sourced from snippets published under the source below. Comments were added and relevant sections chosen and ordered in a meaningful way. //PHP MySQL Database. (w3schools). Retrieved September 9, 2022, from w3schools/Php/php_mysql_intro and subsequent pages ?> ---- Server IP: 45.112.84.4 Probable Submitter: 185.85.3.173 (proxied: 85.10.51.3) ---- Manual Page -- https://php.net/manual/en/class.pdo.php Edit -- https://main.php.net/note/edit/127607 Del: integrated -- https://main.php.net/note/delete/127607/integrated Del: useless -- https://main.php.net/note/delete/127607/useless Del: bad code -- https://main.php.net/note/delete/127607/bad+code Del: spam -- https://main.php.net/note/delete/127607/spam Del: non-english -- https://main.php.net/note/delete/127607/non-english Del: in docs -- https://main.php.net/note/delete/127607/in+docs Del: other reasons-- https://main.php.net/note/delete/127607 Reject -- https://main.php.net/note/reject/127607 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#219550) next »