PHP and MySQL Connection

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 36

PHP and MySQL Connection

Communicating with the MySQL Backend via PHP


MySQL Connect

To establishing a connection between an application or


program and a MySQL database.

This connection allows the application to interact with


the database, such as querying data, inserting records,
updating information, or deleting data.
MySQL Connect

• Programming languages like Python, PHP, Java, etc., "MySQL connect"


typically involves using a library or module provided by the language to
establish a connection to a MySQL database server.

• This connection is usually established by providing connection parameters


such as host, port, username, password, and database name.
MySQL Connect

Once the connection is established, the application can


perform various operations like
querying data to retrieve information,
inserting new records,
updating existing records, and
deleting data as necessary.
PHP MySQL Connect

Since PHP 5.5, mysql_connect() extension is deprecated.

Now it is recommended to use one of the 2 alternatives.

mysqli_connect()
PDO::__construct()
PHP mysqli_connect()
PHP mysqli_connect() function is used to connect with MySQL
database.

It returns resource if connection is established or null.

Syntax

resource mysqli_connect (server, username, password)


PHP mysqli_close()
PHP mysqli_close() function is used to disconnect with MySQL database.

It returns true if connection is closed or false.

Syntax
bool mysqli_close(resource $resource_link)
PHP MySQL
<?php
Connect Example
Output:
$host = 'localhost:3306';
$user = ''; Connected successfully
$pass = '';
$conn = mysqli_connect($host, $user, $pass);
if(! $conn )
{
die('Could not connect: ' . mysqli_error());
}
echo 'Connected successfully';
mysqli_close($conn);
?>
MySQL PDO (PHP Data Objects)
<?php
$servername = "localhost";
$username = "username";
$password = "password";

try {
$conn = new PDO("mysql:host=$servername;dbname=myDB",
$username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
Create a MySQL Database Using
<?php
MySQLi
$servername = "localhost"; $username = "username";
$password = "password";

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


if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "CREATE DATABASE myDB";
if (mysqli_query($conn, $sql)) {
echo "Database created successfully";
} else {
echo "Error creating database: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
PHP MySQL Create Table
Create a MySQL Table Using MySQLi
create a table named "MyGuests", with five columns: "id", "firstname", "lastname", "email" and "reg_date":

sql = "CREATE TABLE MyGuests (


<?php id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
$servername = "localhost"; firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
$username = "username"; email VARCHAR(50),
$password = "password"; reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE
$dbname = "myDB"; CURRENT_TIMESTAMP
)";

$conn = new mysqli($servername, $username,


if ($conn->query($sql) === TRUE) {
$password, $dbname); echo "Table MyGuests created successfully";
} else {
if ($conn->connect_error) { echo "Error creating table: " . $conn->error;
die("Connection failed: " . $conn- }
>connect_error);
$conn->close();
} ?>
Insert Multiple Records Into MySQL
Using MySQLi $sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com');";
<?php $sql .= "INSERT INTO MyGuests (firstname, lastname, email)
$servername = "localhost"; VALUES ('Mary', 'Moe', 'mary@example.com');";
$username = "username"; $sql .= "INSERT INTO MyGuests (firstname, lastname, email)
$password = "password"; VALUES ('Julie', 'Dooley', 'julie@example.com')";
$dbname = "myDB";
if (mysqli_multi_query($conn, $sql)) {
// Create connection echo "New records created successfully";
$conn = mysqli_connect($servername, $username, } else {
$password, $dbname); echo "Error: " . $sql . "<br>" . mysqli_error($conn);
// Check connection }
if (!$conn) {
die("Connection failed: " . mysqli_connect_error()); mysqli_close($conn);
} ?>
PHP MySQL Prepared Statements
A prepared statement is a feature used to execute the same (or similar) SQL
statements repeatedly with high efficiency.

Prepared statements basically work like this:

Prepare: An SQL statement template is created and sent to the database. Certain
values are left unspecified, called parameters (labeled "?"). Example: INSERT INTO
MyGuests VALUES(?, ?, ?)

The database parses, compiles, and performs query optimization on the SQL
statement template, and stores the result without executing it

Execute: At a later time, the application binds the values to the parameters, and
the database executes the statement. The application may execute the statement
as many times as it wants with different values
// prepare and bind
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES
(?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);
// set parameters and execute $firstname = "Mary";
$firstname = "John"; $lastname = "Moe";
$lastname = "Doe"; $email = "mary@example.com";
$email = "john@example.com"; $stmt->execute();
$stmt->execute();
$firstname = "Julie";
$lastname = "Dooley";
$email = "julie@example.com";
$stmt->execute();

echo "New records created successfully";

$stmt->close();
$conn->close();
?>
JavaScript JSON
What is JSON?

• JSON stands for JavaScript Object Notation


• JSON is a lightweight data interchange format
• JSON is language independent *
• JSON is "self-describing" and easy to understand
JSON

• JSON is a format for storing and transporting data.


• JSON is often used when data is sent from a server to a web page.

• The JSON syntax is derived from JavaScript object notation syntax, but the JSON
format is text only.
• Code for reading and generating JSON data can be written in any programming
language.
JSON Example

• {
• "employees":[
• {"firstName":"John", "lastName":"Doe"},
• {"firstName":"Anna", "lastName":"Smith"},
• {"firstName":"Peter", "lastName":"Jones"}
• ]
• }
This JSON syntax defines an employees object: an array of 3 employee records
(objects)
JSON Syntax Rules
• The JSON format is syntactically identical to the code for creating JavaScript objects.

• Because of this similarity, a JavaScript program can easily convert JSON data into native JavaScript
objects.
• JSON Syntax Rules
• Data is in name/value pairs
• Data is separated by commas
• Curly braces hold objects
• Square brackets hold arrays
JSON Data - A Name and a Value
• JSON data is written as name/value pairs, just like JavaScript object properties.

• A name/value pair consists of a field name (in double quotes), followed by a


colon, followed by a value:

• "firstName":"John"

JSON names require double quotes.


JavaScript names do not.
JSON Objects
• JSON objects are written inside curly braces.

• Just like in JavaScript, objects can contain multiple name/value pairs:

{"firstName":"John", "lastName":"Doe"}
JSON Arrays
• JSON arrays are written inside square brackets.

• Just like in JavaScript, an array can contain objects:

• "employees":[
• {"firstName":"John", "lastName":"Doe"},
• {"firstName":"Anna", "lastName":"Smith"},
• {"firstName":"Peter", "lastName":"Jones"}
• ]
Converting a JSON Text to a JavaScript Object
• A common use of JSON is to read data from a web server, and display the data in a web page.

• First, create a JavaScript string containing JSON syntax:


• let text = '{ "employees" : [' +
• '{ "firstName":"John" , "lastName":"Doe" },' +
• '{ "firstName":"Anna" , "lastName":"Smith" },' +
• '{ "firstName":"Peter" , "lastName":"Jones" } ]}';
• Then, use the JavaScript built-in function JSON.parse() to convert the string into a JavaScript
object:
• const obj = JSON.parse(text);
• Finally, use the new JavaScript object in your page:

• <p id="demo"></p>

• <script>
• document.getElementById("demo").innerHTML =
• obj.employees[1].firstName + " " + obj.employees[1].lastName;
• </script>
JSON vs XML
• Both JSON and XML can be used to receive data from a web server.
XML Example
<employees>
<employee>
JSON Example
<firstName>John</firstName> <lastName>Doe</lastName>
{"employees":[
</employee>
{ "firstName":"John", "lastName":"Doe" },
<employee>
{ "firstName":"Anna", "lastName":"Smith" },
<firstName>Anna</firstName>
{ "firstName":"Peter", "lastName":"Jones" }
<lastName>Smith</lastName>
]}
</employee>
<employee>
<firstName>Peter</firstName>
<lastName>Jones</lastName>
</employee>
</employees>
JSON is Like XML Because

• Both JSON and XML are "self describing" (human readable)


• Both JSON and XML are hierarchical (values within values)
• Both JSON and XML can be parsed and used by lots of programming languages
• Both JSON and XML can be fetched with an XMLHttpRequest
JSON is Unlike XML Because

• JSON doesn't use end tag


• JSON is shorter
• JSON is quicker to read and write
• JSON can use array
The biggest difference is:
• XML has to be parsed with an XML parser.
• JSON can be parsed by a standard JavaScript function.
Why JSON is Better Than XML
• XML is much more difficult to parse than JSON.
• JSON is parsed into a ready-to-use JavaScript object.

• For AJAX applications, JSON is faster and easier than XML:


Using XML
• Fetch an XML document
• Use the XML DOM to loop through the document
• Extract values and store in variables
Using JSON

• Fetch a JSON string


• JSON.Parse the JSON string
JSON Data Types
• In JSON, values must be one of the following data types:

• a string
• a number
• an object (JSON object)
• an array
• a boolean
• null
JSON.parse()

• A common use of JSON is to exchange data to/from a web server.

• When receiving data from a web server, the data is always a string.

• Parse the data with JSON.parse(), and the data becomes a JavaScript object.
Example - Parsing JSON
• Imagine we received this text from a web server:
• '{"name":"John", "age":30, "city":"New York"}'
• Use the JavaScript function JSON.parse() to convert text into a JavaScript object:
• const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}');
• <p id="demo"></p>
• <script>
• document.getElementById("demo").innerHTML = obj.name;
• </script>
JSON Server
• A common use of JSON is to exchange data to/from a web server.
• Sending Data
• If you have data stored in a JavaScript object, you can convert the object into JSON, and send it to a server:
• const myObj = {name: "John", age: 31, city: "New York"};
• const myJSON = JSON.stringify(myObj);
• window.location = "demo_json.php?x=" + myJSON;
• Receiving Data
• If you receive data in JSON format, you can easily convert it into a JavaScript object:
• const myJSON = '{"name":"John", "age":31, "city":"New York"}';
• const myObj = JSON.parse(myJSON);
• document.getElementById("demo").innerHTML = myObj.name;
JSON From a Server
• You can request JSON from the server by using an AJAX request

• As long as the response from the server is written in JSON format, you can parse the string into a
JavaScript object.
Example
• Use the XMLHttpRequest to get data from the server:

• const xmlhttp = new XMLHttpRequest();


• xmlhttp.onload = function() {
• const myObj = JSON.parse(this.responseText);
• document.getElementById("demo").innerHTML = myObj.name;
• };
• xmlhttp.open("GET", "json_demo.txt");
• xmlhttp.send();
• {
• "name":"John",
• "age":31,
• "pets":[
• { "animal":"dog", "name":"Fido" },
• { "animal":"cat", "name":"Felix" },
• { "animal":"hamster", "name":"Lightning" }
• ]
• }

You might also like