Showing posts with label database inphp. Show all posts
Showing posts with label database inphp. Show all posts

Tuesday

Create PHP Api for Android Application

PHP REST API backed up with a MySQL database is a very common schematic of an Enterprise mobile
application.
MySQL is uѕеd as a database at thе wеbѕеrvеr аnd PHP iѕ uѕеd to fеtсh dаtа frоm thе dаtаbаѕе.
Our аррliсаtiоn will communicate with the PHP раgе with necessary раrаmеtеrѕ and
PHP will соntасt MySQLdаtаbаѕе and will fetch the rеѕult and return the rеѕultѕ to uѕ.
Now we are going create a PHP RESTful service to read data from a (MySQL) database table.
we are calling the PHP REST API from an android application. In server side,
the API service reads data from the database and sends the response in JSON format


Creating a Dаtаbаѕе

First we need to create a database. MySQL dаtаbаѕе can be created еаѕilу using thiѕ simple script.
The CREATE DATABASE ѕtаtеmеnt сrеаtеѕ the dаtаbаѕе.


<?php
$conn=mysqli_connect("servername","username","password");
$sql="CREATE DATABASE my_db";
if (mysqli_query($conn,$sql))
{
 echo "Database my_db created successfully";
}
?>


Once the dаtаbаѕе is created, it is time to create ѕоmе tаblеѕ in the dаtаbаѕе.
The CREATE TABLE statement creates the dаtаbаѕе for store the values.


Creating Tables


<?php
$sql="CREATE TABLE data_tb(Username CHAR(30),Password CHAR(30),Role
CHAR(30))";
if (mysqli_query($conn,$sql))
{
echo "Table have been created successfully";
}
?>


Inѕеrting Vаluеѕ in Tаblеѕ

When the dаtаbаѕе and tables are created, it iѕ time to inѕеrt ѕоmе data into the tаblеѕ.
Thе Insert Intо statement сrеаtеѕ the database.


<?php
$sql="INSERT INTO data_tb(FirstName, LastName, Age) VALUES ('admin',
'admin',23)";
if (mysqli_query($conn,$sql))
{
echo "Values have been inserted successfully";
}
?>


PHP- GET Method

There is several methods in PHp but we Use only GET method because we need only data in application
and we will get the data using GET method. PHP iѕ аlѕо uѕеd to fetch the rесоrd frоm thе MySQL dаtаbаѕе once
it iѕ сrеаtеd.
In order to fetch record ѕоmе information muѕt bе раѕѕеd tоо PHP page regarding what rесоrd to be fetched.
The firѕt method to раѕѕ іnfоrmаtіоn iѕ thrоugh GET method in which $_GET command is used.
The vаriаblеѕ аrе раѕѕеd in the URL аnd thе record is fetched. Itѕ syntax is givеn below:


<?php
$con=mysqli_connect("servername","username","password","database name");
if (mysqli_connect_errno($conn))
{
 echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$username = $_GET['username'];
$password = $_GET['password'];
$result = mysqli_query($con,"SELECT Role FROM table1 where
Username='$username' and Password='$password'");
$row = mysqli_fetch_array($result);
$data = $row[0];
if($data > 0){
echo $data;
}
mysqli_close($con);
?>


Andrоid- Connecting MySQL


First we need to create the POJO or Model class and set and get method.
Then we get the data using HttpClient and HttpGet

Cоnnесting Via the Get Method

Thеrе аrе two ways to соnnесt to MYSQL via PHP раgе. Thе firѕt one iѕ called Gеt mеthоd.
Wе will use Httр Gеt and HttpClient сlаѕѕ tо соnnесt. Thеir syntax iѕ givеn below:

URL url = new URL(link);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(link));


Aftеr thаt уоu nееd tо call еxесutе method of HttpClient сlаѕѕ and receive it in a HttрRеѕроnѕе оbjесt.
After that you need to open streams to rесеivе the data.


HttpResponse response = client.execute(request);
BufferedReader in = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));


Cоnnесting Via Pоѕt Method
In the Pоѕt method, thе URLEncoder, URLCоnnесtiоn сlаѕѕ will bе uѕеd.
Thе urlencoder will еnсоdе the infоrmаtiоn оf thе раѕѕing variables. It's ѕуntаx iѕ given below:


URL url = new URL(link);
String data = URLEncoder.encode("username", "UTF-8")
+ "=" + URLEncoder.encode(username, "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8")
+ "=" + URLEncoder.encode(password, "UTF-8");
URLConnection conn = url.openConnection();


The last thing уоu nееd to do iѕ tо wrіtе thiѕ dаtа tо thе link.
After writing, you nееd tо open ѕtrеаm tо receive the response dаtа.


OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write( data );
BufferedReader reader = new BufferedReader(new
InputStreamReader(conn.getInputStream()));

Sunday

PHP: MySQL in PHP ( insert, fetch, update, delete and prepared Queries )


MySQL is the most popular database system used with PHP.

  • MySQL is a database system used on the web
  • MySQL is a database system that runs on a server
  • MySQL is ideal for both small and large applications
  • MySQL is very fast, reliable, and easy to use
  • MySQL uses standard SQL
  • MySQL compiles on a number of platforms
  • MySQL is free to download and use
  • MySQL is developed, distributed, and supported by Oracle Corporation
  • MySQL is named after co-founder Monty Widenius's daughter: My







Databases are useful for storing information categorically. A company may have a database with the following tables:

  • Employees
  • Products
  • Customers
  • Orders


If you don't have a PHP server with a MySQL Database, you can download it for free here: http://www.mysql.com

Connect to MySQL


PHP 5 and later can work with a MySQL database using:

  • MySQLi extension (the "i" stands for improved)
  • PDO (PHP Data Objects)


MySQLi Installation


For Linux and Windows: The MySQLi extension is automatically installed in most cases, when php5 mysql package is installed.
For installation details, go to: http://php.net/manual/en/mysqli.installation.php

PDO Installation


For installation details, go to: http://php.net/manual/en/pdo.installation.php

Check Connection to MySQL


<?php
$servername = "Localhost";
$username = "realants";
$password = "realants";
// $databasename = "db_name";
// Create connection
$link = mysqli_connect($servername, $username, $password);

// Check connection
if (!$link) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully....";
?>

The connection will be closed automatically when the script ends. To close the connection before use mysqli_close($conn);


Create a MySQL Database


<?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());
}

// Create database
$sql = "CREATE DATABASE my_db";
if (mysqli_query($conn, $sql)) {
echo "Database created successfully";
} else {
echo "Error creating database: " . mysqli_error($conn);
}

mysqli_close($conn);
?>

Create a MySQL Table


<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "my_db";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

// sql to create table
$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";

if (mysqli_query($conn, $sql)) {
echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . mysqli_error($conn);
}

mysqli_close($conn);
?>

Insert Data Into MySQL


The INSERT INTO statement is used to add new records to a MySQL table:
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "my_db";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES (‘Pk’, ‘Choudhary’, 'pk@example.com')";

if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

mysqli_close($conn);
?>


Get Inserted Data


<?php
$servername = "localhost";
$username = "root";
$password = "123";
$dbname = "my_db";

// Create connection
$conn = mysqli_connect($servername, $username, $password,$dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

$sql = "SELECT firstname, lastname ,email 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 "Name: " . $row["firstname"]. " " . $row["lastname"]. "Email " .$row["email"] ."<br>" ;
}
} else {
echo "0 results";
}


mysqli_close($conn);
?>

Insert Multiple Records Into MySQL


<?php
$servername = "localhost";
$username = "root";
$password = "123";
$dbname = "my_db";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES (‘Pk’, ‘Choudhary’, 'pk@example.com');";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Mary', 'Moe', 'mary@example.com');";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES (‘Lk’, ‘Choudhary’, 'kk@example.com');";

if (mysqli_multi_query($conn, $sql)) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

mysqli_close($conn);
?>

Prepared Statements and Bound Parameters


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

Compared to executing SQL statements directly, prepared statements have three main advantages:

  • Prepared statements reduce parsing time as the preparation on the query is done only once (although the statement is executed multiple times)
  • Bound parameters minimize bandwidth to the server as you need send only the parameters each time, and not the whole query
  • Prepared statements are very useful against SQL injections, because parameter values, which are transmitted later using a different protocol, need not be correctly escaped. If the original statement template is not derived from external input, SQL injection cannot occur.


<?php
$servername = "localhost";
$username = "root";
$password = "123";
$dbname = "my_db";

// Create connection
$conn = mysqli_connect($servername, $username, $password,$dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}




// 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 = "John";
$lastname = "Doe";
$email = "john@example.com";
$stmt->execute();

$firstname = "Mary";
$lastname = "Moe";
$email = "mary@example.com";
$stmt->execute();

$firstname = "Julie";
$lastname = "Dooley";
$email = "julie@example.com";
$stmt->execute();

echo "New records created successfully";

$stmt->close();

mysqli_close($conn);
?>