ccc

BD: mysql PDO

Crear config.php:
try{
    $cnn = new PDO('mysql:host=localhost;dbname=colegio', "root", "");
    $cnn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e){
    echo "ERROR:" .$e->getMessage();
    die();
}

listar.php
require("config.php");

// mostrar en modo asociativo
$stmt = $cnn->prepare("select * from users");
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$stmt->execute();

while ($row = $stmt->fetch()){
    echo "User: ".$row["username"]."<br>";
    echo "Email: ".$row["email"]."<hr>";
}

// mostrar en modo normal
$stmt = $cnn->prepare("select * from users");
$stmt->execute();

while($row = $stmt->fetch(PDO::FETCH_OBJ)){
    echo "User: " . $row->username."<br>";
    echo "Email: " . $row->email. "<hr>";
}

// usando query directamente (no es aconsejable pq se pueden colar así ataques SQL Injection)
$stmt = $cnn->query("select * from users");
$users = $stmt->fetchAll(PDO::FETCH_OBJ);
foreach ($users as $user) {
    echo $user->username . "<br>";
}

insert.php:
require("config.php");

try {
$sql = "INSERT INTO users(username,email,password) VALUES (:username,:email,:password)";
$stmt = $cnn->prepare($sql);

$username = "cuatro";
$email = "cuatro@gmail.com";
$password = md5(444);

    $stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);

if($stmt->execute()) {
$newId = $cnn->lastInsertId();
echo "Se ha dado de alta correctamente, el ID insertado es: ".$newId;
}
}
catch(PDOException $e) {
    echo "ERROR:" .$e->getMessage();
    die();
}

update.php:
require("config.php");

try {

$sql = "UPDATE users SET
username = :username,
            email = :email
            WHERE id = :id";
$stmt = $cnn->prepare($sql);

$username = "tres";
$email = "tres@gmail.com";
$id = 2;

$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
if($stmt->execute()) {
echo "Se ha actualizado correctamente";
}
}
catch(PDOException $e) {
    echo "ERROR:" .$e->getMessage();
    die();
}

delete.php:
require("config.php");

try {
$sql = "delete from users where id =  :id";
$stmt = $cnn->prepare($sql);
$id = 2;
$stmt->bindParam(':id', $id, PDO::PARAM_INT); 
if($stmt->execute()) {
echo "borrado correctamente";
}
}
catch(PDOException $e) {
    echo "ERROR:" .$e->getMessage();
    die();
}

No hay comentarios:

Publicar un comentario