Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /* Connect to a MySQL database using driver invocation */
- $dsn = 'mysql:dbname=database;host=mysql-local.app;port=3306';
- $user = 'user';
- $password = 'password';
- try {
- $pdo = new PDO($dsn, $user, $password);
- $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
- $result = $pdo->query("SHOW TABLES LIKE 'contact'");
- $table = $result->fetchAll();
- if (!count($table)) {
- $pdo->exec(
- "CREATE TABLE contact(\n" .
- " id INT AUTO_INCREMENT NOT NULL,\n" .
- " firstName VARCHAR(250) NOT NULL,\n" .
- " lastName VARCHAR(250) NOT NULL,\n" .
- " email VARCHAR(250) NOT NULL,\n" .
- " PRIMARY KEY (id)\n" .
- ")");
- }
- $statement = $pdo->prepare("INSERT INTO contact (firstName, lastName, email) VALUES (:firstName, :lastName, :email)");
- $statement->bindParam(':firstName', $firstName);
- $statement->bindParam(':lastName', $lastName);
- $statement->bindParam(':email', $email);
- // insert a row
- $firstName = "John";
- $lastName = "Doe";
- $email = "john@example.com";
- $statement->execute();
- // insert another row
- $firstName = "Mary";
- $lastName = "Moe";
- $email = "mary@example.com";
- $statement->execute();
- // insert another row
- $firstName = "Julie";
- $lastName = "Dooley";
- $email = "julie@example.com";
- $statement->execute();
- echo '<pre>',
- json_encode(
- $pdo->query('SELECT id, firstName, lastName, email FROM contact')->fetchAll(PDO::FETCH_ASSOC),
- JSON_PRETTY_PRINT
- );
- } catch (PDOException $e) {
- echo 'Connection failed: ' . $e->getMessage();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement