box-o-sand/php-practice/web/html/wikipedia-tutorial/pdo.php

153 lines
3.6 KiB
PHP

<?php
$PDOCONN = null;
try {
$PDOCONN = new PDO(
"mysql:host=localhost;dbname=learningphp",
"learningphp",
"learningphp"
);
} catch(PDOException $e) {
printf("Could not connect to database: %s\n", $e->getMessage());
exit();
}
$ACTION = "";
if (array_key_exists("action", $_POST)) {
$ACTION = $_POST["action"];
}
require_once("_head.php");
function show_clear_link() {
?>
<a href="<?php echo $_SERVER['PHP_SELF']; ?>">clear</a>
<?php
}
mkheader("pdo!", '#aff');
?>
<body>
<?php
if ($ACTION == "create-tables") {
?><p>Creating tables...</p><pre><?php
$PDOCONN->exec("DROP TABLE IF EXISTS customers");
try {
$nrows = $PDOCONN->exec("
CREATE TABLE customers (
customer_id MEDIUMINT NOT NULL AUTO_INCREMENT,
name VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL,
PRIMARY KEY(customer_id)
) ENGINE=InnoDB
");
printf("%d Row inserted.\n", $nrows);
} catch (PDOException $e) {
printf("Failed to create tables: \n%s\n", $e->getMessage());
}
?></pre><?php
show_clear_link();
} elseif ($ACTION == "show-conn") {
?>
<!-- ======================================================= -->
<pre><?php
print "\$PDOCONN:\n";
print_r($PDOCONN);
?></pre><?php
} elseif ($ACTION == "add-customer") {
try {
$add_customer = $PDOCONN->prepare(
"INSERT INTO customers (customer_id, name, email) VALUES (NULL, :name, :email)"
);
$add_customer->bindParam(':name', $_POST["name"], PDO::PARAM_STR, 12);
$add_customer->bindParam(':email', $_POST["email"], PDO::PARAM_STR, 12);
$nrows = $add_customer->execute();
?><p><?php echo $nrows; ?> Row inserted.</p><?php
} catch(PDOException $e) {
?><p>Failed to create customer!: <?php echo $e->getMessage() ?></p><?php
}
show_clear_link();
} else {
?>
<form name="database_admin" action="" method="POST">
<fieldset>
<legend>Database Admin</legend>
<span class="block">
<input type="radio" id="action-create-tables" name="action" value="create-tables" />
<label for="action-create-tables">create tables</label>
</span>
<span class="block">
<input type="radio" id="action-show-conn" name="action" value="show-conn" />
<label for="action-show-conn">show connection info</label>
</span>
<input type="submit" name="submit" value="Do Stuff" />
</fieldset>
</form>
<form name="add_customer" action="" method="POST">
<fieldset><legend>Add Customer</legend>
<input type="hidden" name="action" value="add-customer" />
<label class="block" for="customer-name">Name:</label>
<input type="text" id="customer-name" name="name" />
<label class="block" for="customer-email">Email:</label>
<input type="email" name="email" />
<input class="block" type="submit" name="submit" value="Add Customer" />
</fieldset>
</form>
<pre id="customer-listing"><?php
$results = $PDOCONN->query("SELECT * FROM customers");
while ($row = $results->fetchAll()) {
print_r($row);
}
?></pre>
<?php
}
?>
</body>
</html>
<?php
$PDOCONN = null;
?>