Skip to content

Instantly share code, notes, and snippets.

@gswallow
Created June 12, 2018 19:30
Show Gist options
  • Save gswallow/abcba9f4bb2e02a6901c8a466cc75501 to your computer and use it in GitHub Desktop.
Save gswallow/abcba9f4bb2e02a6901c8a466cc75501 to your computer and use it in GitHub Desktop.
PHP mysqli example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Creating HR Database and Interviews Table</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
</head>
<body>
<?php
$DBHost = "localhost";
$DBUser = "gswallow";
$DBPass = "gswallow";
$DBName = "gswallow_human_resources";
$TableName = "interviews";
$TableDef = <<<EOD
InterviewID SMALLINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
interviewer VARCHAR(40),
position VARCHAR(90),
interview_date DATE,
candidate VARCHAR(40),
communication LONGTEXT,
appearance LONGTEXT,
computer_skills LONGTEXT,
business_knowledge LONGTEXT,
comments LONGTEXT
EOD;
$conn = new mysqli($DBHost, $DBUser, $DBPass);
echo "Connecting to MySQL<p>";
if ($conn->connect_errno) {
echo "Couldn't connect!<p>";
echo "Error: " . $conn->connect_error . "\n";
} else {
if ($conn->select_db($DBName) === FALSE) {
echo "Creating database \"$DBName\"<p>";
$sql = "CREATE DATABASE $DBName";
if ($conn->query($sql) === FALSE) {
echo "Couldn't create database \"$DBName\"<p>";
$conn->close();
exit;
} else {
echo "Created database \"$DBName\"<p>";
$conn->select_db($DBName);
}
}
echo "Selected database \"$DBName\"<p>";
$sql = "SELECT * FROM information_schema.tables WHERE TABLE_SCHEMA=\"$DBName\" AND TABLE_NAME=\"$TableName\"";
$result = $conn->query($sql);
if ($result->num_rows === 0) {
echo "Creating table \"$TableName\"<p>";
$sql = "CREATE TABLE $TableName ($TableDef)";
if($conn->query($sql) === FALSE) {
echo "Could not create table \"$TableName\"<p>";
echo $conn->error . "<p>";
} else {
echo "Created table \"$TableName\"<p>";
}
} else {
echo "Table \"$TableName\" already exists.<p>";
}
}
?>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment