Difference between revisions of "PHP MySQL"
(→Inserting Data) |
(→Inserting Data) |
||
Line 29: | Line 29: | ||
You need to put in your own table name, field names and values. The values should be in the same order as the field names, i.e. value1 will go into field1 etc. | You need to put in your own table name, field names and values. The values should be in the same order as the field names, i.e. value1 will go into field1 etc. | ||
+ | |||
This method can also be used to delete, update etc with the appropriate SQL. | This method can also be used to delete, update etc with the appropriate SQL. |
Revision as of 16:33, 31 December 2016
Connection
The easiest way to do this is to create a file and save it as connection.php. Your connection file should have the following information inside it:
<?php
$link = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');
?>
Obviously, fill in your own MySQL user, password and database name! Then, whenever you need to connect to the database in a program, use the line:
<?php require_once(“connection.php”); ?>
This will grab the contents of the connection.php file and insert it into the page so that you can use the $link variable as the connection you’ve already set up.
Inserting Data
Assuming you have already included your connection file, this is the basic format for a query
// Create the query
$query = “INSERT INTO tablename(field1, field2, field3) VALUES (‘value1’, ‘value2’, ‘value3’)”;
// Execute the query
$result = mysqli_query($link, $query);
You need to put in your own table name, field names and values. The values should be in the same order as the field names, i.e. value1 will go into field1 etc.
This method can also be used to delete, update etc with the appropriate SQL.
Selecting Data
Here is a general example of how to write a SELECT query to get data from your database:
// Write the query
$query = “SELECT fieldname FROM tablename”;
// Execute the query
$result = mysqli_query($link, $query);
// If anything was found, get the results
while($data = mysqli_fetch_assoc($result)){
print $data[‘fieldname’];
}
In this example, you specify which fields you would like from which table, when you write the query. In this example, the results are put one by one into an array called $data:
$data = mysqli_fetch_assoc($result);
You can then reference each field by its name e.g. if you had a field called username you could use:
print $data[‘username’];
if you had a field called dateofbirth you could use:
print $data[‘dateofbirth’];