Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- // Args
- $dsn = 'mysql:host=myHostname;dbname=myDbName';
- $username = 'some_username';
- $password = 'some_password';
- // Database, as PDO object
- $db = new \PDO($dsn, $username, $password);
- // SELECT example
- // =============================
- // A SELECT query
- $sql = 'SELECT name, email FROM users WHERE id = :id';
- // Prepare the query
- $statement = $db->prepare($sql);
- $statement->bindValue(':id', (integer) $_GET['id'], \PDO::PARAM_INT);
- // Run
- $statement->execute();
- // Collect and return the user data, if present
- if ($result = $statement->fetch(\PDO::FETCH_ASSOC)) {
- return $result;
- }
- // INSERT example
- // =============================
- // An INSERT query
- $sql = 'INSERT INTO users (name, email) VALUES (:name, :email)';
- // Begin a transaction, to retrieve the last insert id
- $db->beginTransaction();
- try {
- // Prepare the query
- $statement = $db->prepare($sql);
- $statement->bindValue(':name', (string) $_POST['name'], \PDO::PARAM_STR);
- $statement->bindValue(':email', (string) $_POST['email'], \PDO::PARAM_STR);
- // Run
- $statement->execute();
- // Query to retrieve the last insert id
- $sql = 'SELECT MAX(id) FROM users';
- // Prepare the query
- $statement = $db->prepare($sql);
- // Run
- $statement->execute();
- // Collect the data
- $result = $statement->fetch(\PDO::FETCH_NUM));
- // Commit
- $db->commit();
- // Last ID
- $last_insert_id = $result[0];
- } catch (\PDOException $e) {
- // Undo everything
- $db->rollback();
- // Last ID
- $last_insert_id = null;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement