PHP and MySQL Connection
PHP and MySQL Connection
mysqli_connect()
PDO::__construct()
PHP mysqli_connect()
PHP mysqli_connect() function is used to connect with MySQL
database.
Syntax
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";
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();
$stmt->close();
$conn->close();
?>
JavaScript JSON
What is JSON?
• 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.
• "firstName":"John"
{"firstName":"John", "lastName":"Doe"}
JSON Arrays
• JSON arrays are written inside square brackets.
• "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.
• <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
• a string
• a number
• an object (JSON object)
• an array
• a boolean
• null
JSON.parse()
• 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: