Show Menu
Cheatography

PHP PDO MYSL Cheat Sheet by

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();
}
       

Help Us Go Positive!

We offset our carbon usage with Ecologi. Click the link below to help us!

We offset our carbon footprint via Ecologi
 

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