PHP PDO MYSL Cheat Sheet

A Programming › PHP cheat sheet in English and français (French) by arnaudritti

PHP PDO MYSL

20,556 views 5,731 downloads 4 Dec 2014 History
4.2 avg · 3 ratings

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

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

Badges

Good Cheat Sheet Nice Cheat Sheet Downloaded from Unusual Locations × 4

Comments

No comments yet.

Cheatography n. The art of mapping complex subjects into clear, instantly navigable reference guides.