Connecting and Writing to MySQL with PHP

March 2, 2016
Category: TIL
Tags: PHP and SQL

Today I learned:

Connecting to MySQL with PHP

<?php
$server = "localhost";
$username = "username";
$password = "password";
$db = "dbname";

//connect
$connect = new mysqli($server, $username, $password, $db);

//Check Connection
if ($connect->connect_error) {
	die("The connection failed: " . $connect->connect_error);
}

Check if a table exists and create it if not

This checks for a table called scorecard_test and creates it if it doesn’t exist. The SQL parameters for the columns are:

  • An integer called ID that is the primary key and auto increments
  • A username that can’t be NULL
  • A column called counter that has a default value of 1 if there is nothing passed, and the length can’t be longer than one digit
  • A column that holds the current timestamp.
<?php
// SQL syntax
$sql = "CREATE TABLE IF NOT EXISTS scorecard_test (
id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
username varchar(255) NOT NULL,
counter int(1) NOT NULL DEFAULT 1,
time TIMESTAMP
)";

// Connecting, sending query, showing errors, and closing connection
if ($connect->query($sql) === TRUE) {
	echo "Done!";
} else {
	echo "Error: " . $connect->error;
}

$connect->close();

Find this post useful?

Buy me a coffeeBuy me a coffee