Connecting and Writing to MySQL with PHP

Today I learned:

Connecting to MySQL with 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.
 // 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();


Comments

Leave a Reply

Webmentions

If you've written a response on your own site, you can enter that post's URL to reply with a Webmention.

The only requirement for your mention to be recognized is a link to this post in your post's content. You can update or delete your post and then re-submit the URL in the form to update or remove your response from this page.

Learn more about Webmentions.