quote($_REQUEST['firstname']);
// $u_lastname = $dbh->quote($_REQUEST['lastname']);
// $u_email = $dbh->quote($_REQUEST['email']);
// SQL-Injection-Angriff (in letztes Feld eingeben)
// ');DELETE FROM user WHERE (u_email LIKE '%
// Insert new record into db
/* Prepared Statements senden SQL-Befehl und Daten in zwei getrennten Schritten an die Datenbank:
Prepare: Die Query-Struktur wird festgelegt und kompiliert.
Execute: Die Werte werden separat eingesetzt – nur noch als Daten, nie als SQL-Code.
Da die Struktur schon vor dem Einsetzen der Werte feststeht,
kann eine Benutzereingabe die Logik der Query nicht mehr verändern.*/
$stmt = $dbh->prepare(
"
INSERT INTO user VALUES (
NULL,
:input_1,
:input_2,
:input_3
);"
);
// bind with pindParam
// $stmt->bindParam(":input_1",$_REQUEST['firstname']);
// $stmt->bindParam(":input_2",$_REQUEST['lastname']);
// $stmt->bindParam(":input_3",$_REQUEST['email']);
// bind with associative array
$input = [
":input_1" => $_REQUEST['firstname'],
":input_2" => $_REQUEST['lastname'],
":input_3" => $_REQUEST['email']
];
try {
//if bound with pindParam
// $stmt->execute();
// if bind with associative array
$stmt->execute($input);
// echo "Insert succeded!
";
header('location:pdo_test_ok.php');
// Weiterleitung
}
catch(PDOException $e) {
$errMsg = $e->getMessage();
$errCode = $e->getCode();
// echo "Error-Message: $errMsg
";
// echo "Error-Code: $errCode
";
switch($errCode) {
case "23000": $custErrMsg = "Email-Adress already exists!
"; break;
default: $custErrMsg = "Oooops, something went wrong!
";
}
echo $custErrMsg;
}
// #######################################################
// Read records form db
// result consists of multiple rows and columns
/* In der Regel auch hier mit Try-Catch-Block */
$sql = "SELECT * FROM user";
// $res = $dbh->query($sql);
$res = $dbh->query($sql)->fetchAll(); // Converts result set into Array (multi-dim)
/*
echo "";
print_r($res);
echo "
";
*/
foreach($res as $row) {
echo "$row[0] | $row[1] | $row[2] | $row[3]
";
}
// result consists of one row and multiple columns
$sql = "SELECT * FROM user WHERE u_id = 24";
$res = $dbh->query($sql)->fetch();
/*
echo "";
print_r($res);
echo "
";
*/
echo "Searching User ID 24:
";
if($res) {
echo "User found: $row[1] $row[2]
";
}
else {
echo "No User found";
}
// result represents one cell
$sql = "SELECT u_firstname FROM user WHERE u_id = 24";
$firstname = $dbh->query($sql)->fetchColumn();
echo "Searching First Name of User ID 24:
";
echo "First Name of User found: $firstname
";
?>
Try again!