Show Menu

PHP PDO MYSL Cheat Sheet by

PHP PDO MYSL
php     pdo     mysl

Select résultat multiple

$id = 5;
try {
  $stmt = $conn->prepare('SELECT * FROM myTable WHERE id = :id');
  $stmt->bindParam(':id', $id, PDO::PARAM_INT);
  $stmt->execute();
 
  $result = $stmt->fetchAll();
 
  if ( count($result) ) {
    foreach($result as $row) {
      print_r($row);
    }
  } else {
    echo "No rows returned.";
  }
} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}

Insert

try {
  $stmt = $pdo->prepare('INSERT INTO someTable VALUES(:name)');
  $stmt->bindParam(':name', 'Justin Bieber', PDO::PARAM_STR);
  $stmt->execute();
 
  # Affected Rows?
  echo $stmt->rowCount(); // 1
} catch(PDOException $e) {
  echo 'Error: ' . $e->getMessage();
}

Update

$id = 5;
$name = "Joe the Plumber";
 
try {
 $stmt = $pdo->prepare('UPDATE someTable SET name = :name WHERE id = :id');
 $stmt->bindParam(':id', $id, PDO::PARAM_INT);
 $stmt->bindParam(':name', $name, PDO::PARAM_STR);
 $stmt->execute();
   
  echo $stmt->rowCount(); // 1
} catch(PDOException $e) {
  echo 'Error: ' . $e->getMessage();
}

Delete

$id = 5;
 
try {
  $stmt = $pdo->prepare('DELETE FROM someTable WHERE id = :id');
  $stmt->bindParam(':id', $id);
  $stmt->execute();
   
  echo $stmt->rowCount(); // 1
} catch(PDOException $e) {
  echo 'Error: ' . $e->getMessage();
}

Connexion

try {
    $conn = new PDO('mysql:host=[SERVEUR];dbname=[BASE]', "[IDENTIFIANT]", "[MOT DE PASSE]");
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}

Select résultat unique

$id = 5;
try {
    $stmt = $conn->prepare('SELECT * FROM myTable WHERE id = :id');
    $stmt->bindParam(':id', $id, PDO::PARAM_INT);
    $stmt->execute();
 
    while($row = $stmt->fetch()) {
        print_r($row);
    }
} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}

Download the PHP PDO MYSL Cheat Sheet

2 Pages
//media.cheatography.com/storage/thumb/arnaudritti_php-pdo-mysl.750.jpg

PDF (recommended)

Alternative Downloads

Share This Cheat Sheet!

Like this cheat sheet? Check out our sponsors!

Readability-Score.com is a collection of tools to make your writing better. More readabile content means higher conversion rates and better reader engagement. Measure website and document readability, measure keyword density and more!

Click Here To Get Started!

 

Comments

No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

          PHP Cheat Sheet
          MySQL Cheat Sheet
          PHP-FIG PSR Standards Cheat Sheet