PHP Notes
PHP Notes
On clicking desktop shortcut W icon should change to Orange & finally to Green.
If it remains in Orange, Apache is not started Port 80 may be used by another
application
In Windows 10, SQL Server is using that port. To solve the problem
Type Services in Windows key (search)
Right click properties of SQL Server Agent, SQL Server Analysis Services, SQL
Server Browser, SQL Server Reporting Services, SQL Server VSS Writer & Disable
them.
On clicking desktop shortcut W icon should change to Orange & finally to Green.
If required click W icon -> Apache-> Service Administration->Install Service
PHP Basics
<?php
?>
<!DOCTYPE html>
<html>
<body>
<?php
function myTest() {
static $x = 0;
echo $x;
$x++;
}
myTest();
echo "<br>";
myTest();
echo "<br>";
myTest();
?>
</body>
</html>
Output:
0
1
2
echo statement can be used with or without parentheses: echo or echo().
echo and print are more or less the same. They are both used to output data to the screen.
The differences are small: echo has no return value while print has a return value of 1 so it
can be used in expressions. echo can take multiple parameters (although such usage is rare)
while print can take one argument. echo is marginally faster than print.
Data Types
<?php
$a = "Hello world!";
$b = 'Hello world!';
echo $a;
echo "<br>";
echo $b;
$x = 5985;
var_dump($x);
$y = 10.365;
var_dump($y);
?>
Output:
Hello world!
Hello world!
int(5985)
float(10.365)
Arrays
<!DOCTYPE html>
<html>
<body>
<?php
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
?>
</body>
</html>
Output:
array(3) { [0]=> string(5) "Volvo" [1]=> string(3) "BMW" [2]=> string(6) "Toyota" }
Objects
An object is a data type which stores data and information on how to process that data.
In PHP, an object must be explicitly declared.
First we must declare a class of object. For this, we use the class keyword.
<?php
class Car {
function Car() {
$this->model = "VW";
}
}
// create an object
$herbie = new Car();
Output:
VW
NULL Value
Null is a special data type which can have only one value: NULL.
A variable of data type NULL is a variable that has no value assigned to it.
<!DOCTYPE html>
<html>
<body>
<?php
$x = "Hello world!";
$x = null;
var_dump($x);
?>
</body>
</html>
Output:
NULL
String Functions
<?php
echo strlen("Hello world!"); // outputs 12
echo str_word_count("Hello world!"); // outputs 2
echo strrev("Hello world!"); // outputs !dlrow olleH
echo strpos("Hello world!", "world"); // outputs 6
echo substr("Hello world",6); // outputs world
echo str_replace("world", "Dolly", "Hello world!"); // outputs Hello
Dolly!
echo strtolower("Hello WORLD!", "world"); // outputs hello world!
echo strtoupper("Hello world!", "world"); // outputs HELLO WORLD
?>
chunk_split() Function
<?php
$str = "Hello world!";
echo chunk_split($str,1,".");
?>
Output:
H.e.l.l.o. .w.o.r.l.d.!.
explode() Function
<?php
$str = "Hello world. It's a beautiful day.";
print_r (explode(" ",$str));
?>
Output:
Array ( [0] => Hello [1] => world. [2] => It's [3] => a [4] => beautiful [5] => day. )
Output:
ltrim() Function
<?php
$str = " Hello World!";
echo "Without ltrim: " . $str;
echo "<br>";
echo "With ltrim: " . ltrim($str);
?>
Output:
Parse_str() Function
<?php
parse_str("name=Peter&age=43");
echo $name."<br>";
echo $age;
?>
Output:
Peter
43
<?php
parse_str("name=Peter&age=43",$myArray);
print_r($myArray);
?>
Output:
similar_text() Function
<?php
echo similar_text("Hello World","Hello Peter");
?>
Output:
<?php
similar_text("Hello World","Hello Peter",$percent);
echo $percent;
?>
Output:
63.636363636364
str_replace() Function
<?php
echo str_replace("world","Peter","Hello world!");
?>
Output:
Hello Peter!
str_split() Function
<?php
print_r(str_split("Hello"));
?>
Output:
Array ( [0] => H [1] => e [2] => l [3] => l [4] => o )
<?php
print_r(str_split("Hello",3));
?>
Output:
str_repeat() Function
<?php
echo str_repeat(".",13);
?>
Output:
.............
<?php
echo strcmp("Hello world!","Hello world!"); // outputs 0
echo strcmp("Hello world!","Hello World!"); // outputs -1
echo strcmp("Hello world!","Hello")."<br>"; // outputs 7
echo strcmp("Hello world!","Hello world! Hello!")."<br>"; // outputs -7
?>
Return Value:
CONSTANTS
<?php
define("GREETING", "Welcome to W3Schools.com!");
echo GREETING;
?>
ARITHMETIC OPERATORS
+ - * / % **(exponentiation)
LOGICAL OPERATORS
&& || !
STRING OPERATORS
. concatenation
If
elseif
else
switch ($n)
{
case red:
echo Red;
break;
default:
echo
}
Foreach example
<?php
$colors = array("red", "green", "blue", "yellow");
<?php
function familyName($fname) {
echo "$fname Refsnes.<br>";
}
familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName("Kai Jim");
familyName("Borge");
?>
<?php
function familyName($fname, $year) {
echo "$fname Refsnes. Born in $year <br>";
}
familyName("Hege", "1975");
familyName("Stale", "1978");
familyName("Kai Jim", "1983");
?>
<?php
function setHeight($minheight = 50) {
echo "The height is : $minheight <br>";
}
setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);
?>
Returning values
<?php
function sum($x, $y) {
$z = $x + $y;
return $z;
}
ARRAYS
INDEXED ARRAYS
(or)
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
Length of Array
echo count($cars);
<?php
$cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);
(or)
$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
MULTIDIMENSIONAL ARRAYS
Two-Dimensional Array
$cars = array
(
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
Now the two-dimensional $cars array contains four arrays, and it has two indices: row and
column.
To get access to the elements of the $cars array we must point to the two indices (row and
column):
<?php
echo $cars[0][0].": In stock: ".$cars[0][1].", sold:
".$cars[0][2].".<br>";
echo $cars[1][0].": In stock: ".$cars[1][1].", sold:
".$cars[1][2].".<br>";
echo $cars[2][0].": In stock: ".$cars[2][1].", sold:
".$cars[2][2].".<br>";
echo $cars[3][0].": In stock: ".$cars[3][1].", sold:
".$cars[3][2].".<br>";
?>
Output:
<?php
for ($row = 0; $row < 4; $row++) {
echo "<p><b>Row number $row</b></p>";
echo "<ul>";
for ($col = 0; $col < 3; $col++) {
echo "<li>".$cars[$row][$col]."</li>";
}
echo "</ul>";
}
?>
Output:
Row number 0
Volvo
22
18
Row number 1
BMW
15
13
Row number 2
Saab
5
2
Row number 3
Land Rover
17
15
$GLOBALS
$_SERVER
$_REQUEST
$_POST
$_GET
$_FILES
$_ENV
$_COOKIE
$_SESSION
$_REQUEST
PHP $_REQUEST is used to collect data after submitting an HTML form
<!DOCTYPE html>
<html>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Name: <input type="text" name="fname">
<input type="submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = $_REQUEST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
}
?>
</body>
</html>
PHP $_POST
PHP $_POST is widely used to collect form data after submitting an HTML form with
method="post". $_POST is also widely used to pass variables.
<html>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Name: <input type="text" name="fname">
<input type="submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = $_POST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
}
?>
</body>
</html>
PHP $_GET
PHP $_GET can also be used to collect form data after submitting an HTML form with
method="get".
<html>
< body>
< /body>
< /html>
When a user clicks on the link "Test $GET", the parameters "subject" and "web" are sent to
"test_get.php", and you can then access their values in "test_get.php" with $_GET.
<html>
<body>
<?php
echo "Study " . $_GET['subject'] . " at " . $_GET['web'];
?>
</body>
</html>
FORM HANDLING
<html>
<body>
</body>
</html>
When the user fills out the form above and clicks the submit button, the form data is sent for
processing to a PHP file named "welcome.php". The form data is sent with the HTTP POST
method.
To display the submitted data you could simply echo all the variables. The "welcome.php"
looks like this:
<html>
< body>
< /body>
< /html>
The same result could also be achieved using the HTTP GET method
Both GET and POST create an array (e.g. array( key => value, key2 => value2, key3 =>
value3, ...)). This array holds key/value pairs, where keys are the names of the form controls
and values are the input data from the user.
Both GET and POST are treated as $_GET and $_POST. These are superglobals, which
means that they are always accessible, regardless of scope - and you can access them from
any function, class or file without having to do anything special.
$_GET is an array of variables passed to the current script via the URL parameters.
$_POST is an array of variables passed to the current script via the HTTP POST method.
When to use GET?
Information sent from a form with the GET method is visible to everyone (all variable names
and values are displayed in the URL). GET also has limits on the amount of information to
send. The limitation is about 2000 characters. However, because the variables are displayed
in the URL, it is possible to bookmark the page. This can be useful in some cases.
Note: GET should NEVER be used for sending passwords or other sensitive information!
Information sent from a form with the POST method is invisible to others (all names/values
are embedded within the body of the HTTP request) and has no limits on the amount of
information to send.
Moreover POST supports advanced functionality such as support for multi-part binary input
while uploading files to server.
However, because the variables are not displayed in the URL, it is not possible to bookmark
the page.
VALIDATION
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
}
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
</body>
</html>
Validating Name, Mail id, Website & Required Field
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
// check if URL address syntax is valid
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-
9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<?php
echo "Today is " . date("Y/m/d") . "<br>";
// outputs Today is 2016/10/20
echo "Today is " . date("Y.m.d") . "<br>";
// outputs Today is 2016.10.20
echo "Today is " . date("Y-m-d") . "<br>";
// outputs Today is 2016-10-20
echo "Today is " . date("l"); // outputs Today is Thursday
© 2010-echo date("Y"); // outputs 2010-2016
echo "The time is " . date("h:i:sa");// outputs The time is 02:51:12am
date_default_timezone_set("America/New_York");
echo "The time is " . date("h:i:sa");
// outputs The time is 02:51:12am
$d=strtotime("+3 Months");
echo date("Y-m-d h:i:sa", $d) . "<br>";
// 2017-01-20 03:04:42am
$startdate = strtotime("Saturday");
$enddate = strtotime("+6 weeks", $startdate);
// Oct 22
Oct 29
Nov 05
Nov 12
Nov 19
Nov 26
$d1=strtotime("July 04");
$d2=ceil(($d1-time())/60/60/24);
echo "There are " . $d2 ." days until 4th of July.";
?>
</body>
</html>
INCLUDE
<!DOCTYPE html>
<html>
<body>
<div class="menu">
<?php include 'menu.php';?>
</div>
</body>
</html>
Output
Some text.
The require statement is also used to include a file into the PHP code.
However, there is one big difference between include and require; when a file is included
with the include statement and PHP cannot find it, the script will continue to execute
Use include when the file is not required and application should continue when file is not
found.
FILE UPLOAD
In your "php.ini" file, search for the file_uploads directive, and set it to On:
file_uploads = On
HTML File
<!DOCTYPE html>
<html>
<body>
</body>
</html>
Without the requirements above, the file upload will not work.
The type="file" attribute of the <input> tag shows the input field as a file-select
control, with a "Browse" button next to the input control
The form above sends data to a file called "upload.php", which we will create next.
Upload.php
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType !=
"jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],
$target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). "
has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
$target_dir = "uploads/" - specifies the directory where the file is going to be placed
$target_file specifies the path of the file to be uploaded
$uploadOk=1 is not used yet (will be used later)
$imageFileType holds the file extension of the file
Next, check if the image file is an actual image or a fake image
Note: You will need to create a new directory called "uploads" in the directory where
"upload.php" file resides. The uploaded files will be saved there.
COOKIE
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); //
86400 = 1 day
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
SESSION
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
</html>
Another Method
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
print_r($_SESSION);
?>
</body>
</html>
Modify Session
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// to change a session variable, just overwrite it
$_SESSION["favcolor"] = "yellow";
print_r($_SESSION);
?>
</body>
</html>
Destroy Session
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// remove all session variables
session_unset();
</body>
</html>
MYSQL
MySQLi Object-Oriented
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
Note: on the object-oriented example above: $connect_error was broken until PHP 5.2.9 and
5.3.0. If you need to ensure compatibility with PHP versions prior to 5.2.9 and 5.3.0, use the
following code instead:
// Check connection
if (mysqli_connect_error()) {
die("Database connection failed: " . mysqli_connect_error());
}
MySQLi Procedural
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
PDO
<?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();
}
?>
The connection will be closed automatically when the script ends. To close the connection
before, use the following:
MySQLi Object-Oriented
$conn->close();
MySQLi Procedural
mysqli_close($conn);
PDO
$conn = null;
INSERTING MULTIPLE RECORDS
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
?>
PREPARED STATEMENTS
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$firstname = "Mary";
$lastname = "Moe";
$email = "mary@example.com";
$stmt->execute();
$firstname = "Julie";
$lastname = "Dooley";
$email = "julie@example.com";
$stmt->execute();
$stmt->close();
$conn->close();
?>
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// insert a row
$firstname = "John";
$lastname = "Doe";
$email = "john@example.com";
$stmt->execute();
MySQLi Object-oriented
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
MySQLi Procedural
<?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());
}
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);
?>
MySQLi Object-oriented
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($result->num_rows > 0) {
echo "<table><tr><th>ID</th><th>Name</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["id"]."</td><td>".$row["firstname"]."
".$row["lastname"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
Example (PDO)
<?php
echo "<table style='border: solid 1px black;'>";
echo "<tr><th>Id</th><th>Firstname</th><th>Lastname</th></tr>";
function current() {
return "<td style='width:150px;border:1px solid black;'>" . parent::current(). "</td>";
}
function beginChildren() {
echo "<tr>";
}
function endChildren() {
echo "</tr>" . "\n";
}
}
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT id, firstname, lastname FROM MyGuests");
$stmt->execute();
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
?>
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
Example (PDO)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn = null;
?>