BeMu
BeMu

Reputation: 13

Setting up MySQL database for website

I am making a website that will use a MySQL database on a friend's web hosting service. It supports PHP and MySQL but I'm not sure what file I am meant to create the database and table in. I understand the syntax so I just need to know where and which files to do it in. I guess you don't put it in the website's html files because it only needs to be created once.

I have the following code:

<?php
$servername = "localhost";
$username   = "username";
$password   = "password";
$conn       = mysqli_connect($servername, $username, $password);
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
$sql = "CREATE DATABASE LeagueData";
if (mysqli_query($conn, $sql)) {
    echo "Database created successfully";
} else {
    echo "Error creating database: " . mysqli_error($conn);
}
mysqli_close($conn);
?>

Upvotes: 1

Views: 1273

Answers (2)

Sesh Sadasivam
Sesh Sadasivam

Reputation: 39

Adding on to Patrick's answer:

You need to create your database first, and not through PHP. mysqli allows you to connect to a particular database (which you need to specify in your code), and then execute queries on that database.

First, create a database. You should consult your web-hosting provider on how to do this. Most web-hosts allow you to create a database through one of the CPanel modules. (You'll also have to create a "user", and assign that user to the newly created database.)

Once you have created the database, you will be able to connect to it via PHP. Your code to connect to the database should look like:

$conn = mysqli_connect($servername, $username, $password, $database_name);

Upvotes: 0

Patrick
Patrick

Reputation: 19

You don't have to create a file. You have to create the DB and structure from within MySQL (or you can load a .sql file into MySQL).

If he has phpMyAdmin use that. It's much easier.

Creating a table from within MySQL: http://dev.mysql.com/doc/refman/5.7/en/creating-tables.html
Importing an .sql file from the commandline: mysql -u username -p database_name < file.sql

Upvotes: 1

Related Questions