Module 4
Module 4
Module 4
What is MySQL?
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = newmysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
The connection will be closed automatically when the script ends. To close
the connection before, use the following:
Example
$conn->close();
NOT NULL - Each row must contain a value for that column, null
values are not allowed
DEFAULT value - Set a default value that is added when no other
value is passed
UNSIGNED - Used for number types, limits the stored data to positive
numbers and zero
AUTO INCREMENT - MySQL automatically increases the value of the
field by 1 each time a new record is added
PRIMARY KEY - Used to uniquely identify the rows in a table. The
column with PRIMARY KEY setting is often an ID number, and is
often used with AUTO_INCREMENT
EXAMPLE
Example
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " .
$row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
7. DELETE Command
The DELETE statement is used to delete records from a table:
Example :
// sql to delete a record
$sql = "DELETE FROM MyGuests WHERE id=3";
8. UPDATE
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value
Example
$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";