box-o-sand/PracticingPhp/web/html/wikipedia-tutorial/mysql.php

150 lines
3.6 KiB
PHP

<?php
$MYSQLCONN = new mysqli(
"localhost",
"learningphp",
"learningphp",
"learningphp"
);
if (mysqli_connect_errno()) {
printf("Could not connect to database: %s\n", mysqli_connect_error());
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("mysql!", '#aff');
?>
<body>
<?php
if ($ACTION == "create-tables") {
?><p>Creating tables...</p><pre><?php
$MYSQLCONN->query("DROP TABLE IF EXISTS customers");
$create_result = $MYSQLCONN->query("
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
");
if (!$create_result) {
printf("Failed to create tables: %s\n", $MYSQLCONN->error);
} else {
printf("%d Row inserted.\n", $MYSQLCONN->affected_rows);
print_r($MYSQLCONN->query("DESCRIBE customers"));
print_r($MYSQLCONN->query("SELECT * FROM customers"));
}
?></pre><?php
show_clear_link();
} elseif ($ACTION == "show-conn") {
?>
<!-- ======================================================= -->
<pre><?php
print "\$MYSQLCONN:\n";
print_r($MYSQLCONN);
?></pre><?php
} elseif ($ACTION == "add-customer") {
$add_customer = $MYSQLCONN->prepare(
"INSERT INTO customers (customer_id, name, email) VALUES (NULL, ?, ?)"
);
$add_customer->bind_param('ss', $_POST["name"], $_POST["email"]);
$result = $add_customer->execute();
if (!$result) {
?><p>Failed to create customer!: <?php echo $MYSQLCONN->error ?></p><?php
} else {
?><p><?php echo $MYSQLCONN->affected_rows; ?> Row inserted.</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 = $MYSQLCONN->query("SELECT * FROM customers");
while ($row = $results->fetch_array(MYSQLI_ASSOC)) {
print_r($row);
}
?></pre>
<?php
}
?>
</body>
</html>
<?php
$MYSQLCONN->close();
?>