Last active
April 9, 2017 14:49
-
-
Save antoniojps/d91a515fdeb61d7678b34c1c086b8b80 to your computer and use it in GitHub Desktop.
PHP - PDO Connect e prepared statements
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
///////////////////// | |
// Connect | |
try { | |
$host = "localhost"; | |
$database = "learning_pdo"; | |
$db = new PDO("mysql:host=$host;dbname=$database;charset=utf8","antonio","123"); | |
} | |
catch(Exception $e){ | |
echo "Something went wrong"; | |
} | |
///////////////////// | |
// Prepared statements | |
// MYSQL SELECT | |
$names = [ 'Maria', 'Andy' ]; | |
$stmt = $db->prepare( "SELECT * FROM names WHERE firstname LIKE :firstname" ); | |
forEach ( $names as $name ) { | |
$stmt->bindParam( ':firstname', $name); | |
$stmt->execute(); | |
while ( $row = $stmt->fetch( PDO::FETCH_ASSOC ) ) { | |
echo htmlentities( $row['firstname'] ) . " " . htmlentities( $row['lastname'] ) . " " . htmlentities( $row['postcode'] ), "<br>"; | |
//var_dump($row); | |
} | |
} | |
// close connections | |
$stmt = null; | |
// MYSQL UPDATE | |
$stmt = $db->prepare("UPDATE names SET postcode = :postcode WHERE firstname = :firstname"); | |
$stmt->bindValue(':firstname','Joana'); | |
$stmt->bindValue(':postcode','69XDAWM'); | |
$stmt->execute(); | |
// MYSQL INSERT | |
$stmt = $db->prepare("INSERT INTO names (firstname,lastname,postcode) VALUES (:firstname,:lastname,:postcode)"); | |
$stmt->bindValue(':firstname','Joana'); | |
$stmt->bindValue(':lastname','Albertina'); | |
$stmt->bindValue(':postcode','DWAXD231'); | |
$stmt->execute(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment