PHP MySQL code to extract data from MySQL table and display as JSON

MySQL -> PHP -> JSON Layer -> JS/HTML

To prevent database password sniffing you must not get a direct access to database (sending database access datas).
The best way is to call a PHP engine and after, the PHP engine will render simple JSON data structure.
In the end you can use JScript to write, on the fly, the final HTML code.

json structure

We need store this simple datas:

Users:

Andrea Tonin January, 12 2012
Riccardo Santato April, 28 2010

We will create this json structure:

{"users":[
        {
            "firstName":"Andrea",
            "lastName":"Tonin",
            "joined": {
                "month":"January",
                "day":12,
                "year":2012
            }
        },
        {
            "firstName":"Riccardo",
            "lastName":"Santato",
            "joined": {
                "month":"April",
                "day":28,
                "year":2010
            }
        }
]}

Create database

Open phpMyAdmin

On the top localhost> mydatabase

Use phpMyAdmin to create:

Left Column> ‘Crea tabella’> MyISAM

Table name: ‘users’

PhpMyAdmin> In Alto> linguetta Struttura> aggiungere i campi

Campo: id
Tipo: INT
Lunghezza: 20
Predefinito: Nessuno
Null: deselezionato
Indice: PRIMARY
AUTO_INCREMENT: selezionato

Campo: firstName
Tipo: VARCHAR
Lunghezza: 255
Predefinito: Nessuno
Null: deselezionato
Indice: nessuno
AUTO_INCREMENT: deselezionato

Campo: lastName
Tipo: VARCHAR
Lunghezza: 255
Predefinito: Nessuno
Null: deselezionato
Indice: nessuno
AUTO_INCREMENT: deselezionato

Campo: month
Tipo: VARCHAR
Lunghezza: 20
Predefinito: Nessuno
Null: deselezionato
Indice: nessuno
AUTO_INCREMENT: deselezionato

Campo: day
Tipo: INT
Lunghezza: 2
Predefinito: Nessuno
Null: deselezionato
Indice: nessuno
AUTO_INCREMENT: deselezionato

Campo: year
Tipo: INT
Lunghezza: 4
Predefinito: Nessuno
Null: deselezionato
Indice: nessuno
AUTO_INCREMENT: deselezionato

The final result inside phpMyAdmin:

mysql-0009

PhpMyAdmin> In Alto> linguetta Inserisci>

Aggiungere i campi:

Andrea Tonin January, 12 2012
Riccardo Santato April, 28 2010

colonna di sinistra PhpMyAdmin> click su ‘users’>

mysql-0010

PHP json translator – php-json.php

<?php
$host="localhost"; //lasciare com'è se utilizzate bluehost
$username="lucedigi_user"; 
$password="mypassword"; 
$db_name="lucedigi_testphp"; // database name
$tbl_name="users"; //indicate la tabella presente nel database a cui si deve collegare 
  
// Connetti al server e seleziona il database
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("DB non connesso");
 
// JSON TRANSLATOR CODE START ###################################
 
$sql = "select * from users"; //indicate la tabella presente nel database a cui si deve collegare 
$result = mysql_query($sql);
$json = array();
if(mysql_num_rows($result)){
while($row=mysql_fetch_row($result)){
$json['users'][]=$row;  //indicate la tabella presente nel database a cui si deve collegare 
}
}
mysql_close($db_name);
echo json_encode($json); // json_encode() PHP Function
 
// JSON TRANSLATOR CODE END ####################################
?> 

Notice:

echo json_encode($json); // json_encode() PHP Function

If you execute php-json.php, you will see:

{“users”:[[“1″,”Andrea”,”Tonin”,”January”,”12″,”2012″],[“3″,”Riccardo”,”Santato”,”April”,”28″,”2010″]]}

JScript Render – js-json.php

<!DOCTYPE html>
 
<html>
<head> 
</head>
 
<body>

    <!-- Write with PHP include function -->
    Write with PHP include function: <br>
    <?php include("php-json.php"); ?>
     
    <script>
	// Write with Javascript
	var jsoncontent='<?php include("phpjson.php"); ?>';
	document.write('<br>Write with JavaScript - simple variable:<br>');
	document.write(jsoncontent);
    </script>
	
</body>
 
</html>

If you execute js-json.php, you will see:

Write with PHP include function:
{“users”:[[“1″,”Andrea”,”Tonin”,”January”,”12″,”2012″],[“3″,”Riccardo”,”Santato”,”April”,”28″,”2010″]]}
Write with JavaScript – simple variable:
{“users”:[[“1″,”Andrea”,”Tonin”,”January”,”12″,”2012″],[“3″,”Riccardo”,”Santato”,”April”,”28″,”2010″]]}

You can store the data inside a javascript object:

<!DOCTYPE html>
  
<html>
<head> 
</head>
  
<body> 
    <script>
    // Write with Javascript
    var jsoncontent='<?php include("php-json.php"); ?>';
    var obj = JSON.parse(jsoncontent);
    alert(JSON.stringify(obj, null, 4));
    </script>   
</body>
  
</html>

Notice: JSON.stringify function to print out Javascript objects

The result is:
json-0001

By |JavaScript, JSON, MySQL, PHP, Web Design|Commenti disabilitati su PHP MySQL code to extract data from MySQL table and display as JSON

MySQL injection protection

How to prevent MySQL injection

What is SQL injection?
SQL injection is the attempt to issue SQL commands to a database through a website interface, to gain other information. Namely, this information is stored database information such as usernames and passwords.

The code to prevent injection:

// collect data from HTML form
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];
 
//Prevent MySQL injection
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);

// Now you can send to DB secure data
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);

Notice:
stripslashes —> Un-quotes a quoted string
mysql_real_escape_string —> Escapes special characters in a string for use in an SQL statement

By |MySQL, Web Design|Commenti disabilitati su MySQL injection protection

PHP – My SQL – Login

PHP – My SQL – Login

DOWNLOAD

 

Creazione database

Entriamo in phpMyAdmin

In alto posizioniamoci su localhost> mydatabase

Selezioniamo linguetta “SQL”, nell’area di input copiamo i comandi SQL:

CREATE TABLE IF NOT EXISTS `members` (
 `id` int(4) NOT NULL AUTO_INCREMENT,
 `username` varchar(65) NOT NULL DEFAULT '',
 `password` varchar(65) NOT NULL DEFAULT '',
 `email` varchar(255) NOT NULL DEFAULT '',
 `attivazione` varchar(255) NOT NULL DEFAULT '',
 PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

Clicchiamo sul bottone a destra ‘Esegui’

mysql-0008

Creazione Form Login

main_login.php

Invierà i dati a “checklogin.php”, in particolare:
– name=”myusername”
– name=”mypassword”

<table width="300" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<form name="form1" method="post" action="checklogin.php">
<td>
<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<tr>
<td colspan="3"><strong>Login</strong></td>
</tr>
<tr>
<td width="78">Username</td>
<td width="6">:</td>
<td width="294"><input name="myusername" type="text" id="myusername"></td>
</tr>
<tr>
<td>Password</td>
<td>:</td>
<td><input name="mypassword" type="text" id="mypassword"></td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td><input type="submit" name="Submit" value="Login"></td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
</table>
</td>
</form>
</tr>
</table>

Check Login

checklogin.php

Interroga il database se
– login corretto -> login_success.php
– login errato -> checklogin.php restituisce un messaggio di errore

<?php

$host="localhost"; //lasciare com'è se utilizzate bluehost
$username="lucedigi_user"; 
$password="mypassword"; 
$db_name="lucedigi_testphp"; // database name
$tbl_name="members"; //Indicate la tabella presente nel database a cui si deve collegare 

// Connetti al server e seleziona il database
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("DB non connesso");

// ricevo username e password dal form HTML
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];

//Protezione da MySQL injection
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);

// Invio una query di ricerca nella tabella, all'interno campi username e password
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);

//
$count=mysql_num_rows($result);

//
if($count==1){

// Verifica dati e reindirizza a  "login_success.php"
session_register("myusername");
session_register("mypassword");
header("location:login_success.php");
}
else {
echo "Username o Password errati!";
}
?>

Login Success

login_success.php

<?php
session_start();
if(!session_is_registered(myusername)){
header("location:main_login.php");
}
?>

<html>
<body>
Correttamente Loggato!
</body>
</html>
By |MySQL, PHP|Commenti disabilitati su PHP – My SQL – Login

PHP – MySQL – Simple Data Management Skeleton

PHP – MySQL – Simple Data Management Skeleton

DOWNLOAD

 

insert-form.php

<?php
// Create DATABASE connection - START
// Statement: mysqli_connect(host,username,password,dbname)
// NOTICE: se lo script è installato nello stesso server del Data Base, host->localhost
$con=mysqli_connect("localhost","lucedigi_user","mypassword","lucedigi_testphp");
// Check connection
if (mysqli_connect_errno())
  {
  echo "<br> Failed to connect to MySQL: " . mysqli_connect_error();
  }
else
  {
  echo "Great! Connect to MySQL!";
  }
  // Create DATABASE connection - END
  ?>
  
<html>
<body>

<!-- FORM INSERT START -->
<!-- Send data to insert-engine.php -->
<br><br><strong>Insert New Data:</strong>
<form action="insert-engine.php" method="post">
<br>First name: <input type="text" name="firstname">
<br>Last name: <input type="text" name="lastname">
<br>Age: <input type="text" name="age">
<br><input type="submit">
</form>
<!-- FORM INSERT END -->

<!-- FORM DELETE START -->
<!-- Send data to delete-engine.php -->
<br><strong>Delete Data:</strong>
<form action="delete-engine.php" method="post">
<br>PID: <input type="text" name="deletepid">
<br><input type="submit">
</form>
<!-- FORM DELETE END -->

<!-- FORM UPDATE START -->
<!-- Send data to update-engine.php -->
<br><strong>Update Data:</strong>
<form action="update-engine.php" method="post">
<br>PID: <input type="text" name="updatepid">
<br>First name: <input type="text" name="upfirstname">
<br>Last name: <input type="text" name="uplastname">
<br>Age: <input type="text" name="upage">
<br><input type="submit">
</form>
<!-- FORM UPDATE END -->

</body>
</html>

<?php
// SELECT asterisco (tutti i dati) dalla tabella Persons - START
// inserisco i dati nella variabile $result
$result = mysqli_query($con,"SELECT * FROM Persons");

echo "<strong>Data Inside Database:</strong>";
echo "<br><br>PID - First name - Last name - Age<br>";
// Restituisce il set di record come un array
// ad ogni chiamata viene restituita la riga successiva
while($row = mysqli_fetch_array($result))
  {
  // Visualizza a video i dati
  echo $row['PID'] . " - " .$row['FirstName'] . " - " . $row['LastName'] . " - " . $row['Age'];
  echo "<br>";
  }
// SELECT asterisco (tutti i dati) dalla tabella Persons - END

mysqli_close($con); 
echo "<br>Great! Connection Closed!"; 
?>

update-engine.php

<?php
// Create connection
// Statement: mysqli_connect(host,username,password,dbname)
// NOTICE: se lo script è installato nello stesso server del Data Base, host->localhost
$con=mysqli_connect("localhost","lucedigi_user","mypassword","lucedigi_testphp");

// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
else
  {
  echo "Great! Connect to MySQL!";
  }
  
// Update records START
// SET column1=value, column2=value2,...
mysqli_query($con,"UPDATE Persons SET Age='$_POST[upage]', FirstName='$_POST[upfirstname]', LastName='$_POST[uplastname]' WHERE PID='$_POST[updatepid]'");

// Update records END
echo "<br>1 record updated";

mysqli_close($con); 
echo "<br>Great! Connection Closed!"; 
echo "<br><a href='insert-form.php'>Torna alla pagina precedente</a>";
?>

insert-engine.php

<?php
// Create connection
// Statement: mysqli_connect(host,username,password,dbname)
// NOTICE: se lo script è installato nello stesso server del Data Base, host->localhost
$con=mysqli_connect("localhost","lucedigi_user","mypassword","lucedigi_testphp");

// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
else
  {
  echo "Great! Connect to MySQL!";
  }
 
// ###################################################### 
// Aggiungere nuovi record alle colonne con POST - START
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
// Aggiungere nuovi record alle colonne con POST - END
// ###################################################### 

if (!mysqli_query($con,$sql))
  {
  die('Error: ' . mysqli_error($con));
  }
echo "<br>1 record added";

mysqli_close($con); 
echo "<br>Great! Connection Closed!"; 
echo "<br><a href='insert-form.php'>Torna alla pagina precedente</a>";
?>

delete-engine.php

<?php
// Create connection
// Statement: mysqli_connect(host,username,password,dbname)
// NOTICE: se lo script è installato nello stesso server del Data Base, host->localhost
$con=mysqli_connect("localhost","lucedigi_user","mypassword","lucedigi_testphp");

// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
else
  {
  echo "Great! Connect to MySQL!";
  }
  
// Delete records START
mysqli_query($con,"DELETE FROM Persons WHERE PID='$_POST[deletepid]'");
// Delete records END
echo "<br>1 record deleted";

mysqli_close($con); 
echo "<br>Great! Connection Closed!"; 
echo "<br><a href='insert-form.php'>Torna alla pagina precedente</a>";
?>
By |MySQL, PHP|Commenti disabilitati su PHP – MySQL – Simple Data Management Skeleton

My SQL – Data Types

My SQL – Data Types

Text types:

CHAR(size)
Holds a fixed length string (can contain letters, numbers, and special characters). The fixed size is specified in parenthesis. Can store up to 255 characters

VARCHAR(size)
Holds a variable length string (can contain letters, numbers, and special characters). The maximum size is specified in parenthesis. Can store up to 255 characters. Note: If you put a greater value than 255 it will be converted to a TEXT type

TINYTEXT
Holds a string with a maximum length of 255 characters

TEXT
Holds a string with a maximum length of 65,535 characters

BLOB
For BLOBs (Binary Large OBjects). Holds up to 65,535 bytes of data

MEDIUMTEXT
Holds a string with a maximum length of 16,777,215 characters

MEDIUMBLOB
For BLOBs (Binary Large OBjects). Holds up to 16,777,215 bytes of data

LONGTEXT
Holds a string with a maximum length of 4,294,967,295 characters

LONGBLOB
For BLOBs (Binary Large OBjects). Holds up to 4,294,967,295 bytes of data

ENUM(x,y,z,..)
Let you enter a list of possible values. You can list up to 65535 values in an ENUM list. If a value is inserted that is not in the list, a blank value will be inserted.
Note: The values are sorted in the order you enter them.
You enter the possible values in this format: ENUM(‘X’,’Y’,’Z’)

SET
Similar to ENUM except that SET may contain up to 64 list items and can store more than one choice

Number types:

TINYINT(size)
-128 to 127 normal. 0 to 255 UNSIGNED*. The maximum number of digits may be specified in parenthesis

SMALLINT(size)
-32768 to 32767 normal. 0 to 65535 UNSIGNED*. The maximum number of digits may be specified in parenthesis

MEDIUMINT(size)
-8388608 to 8388607 normal. 0 to 16777215 UNSIGNED*. The maximum number of digits may be specified in parenthesis

INT(size)
-2147483648 to 2147483647 normal. 0 to 4294967295 UNSIGNED*. The maximum number of digits may be specified in parenthesis

BIGINT(size)
-9223372036854775808 to 9223372036854775807 normal. 0 to 18446744073709551615 UNSIGNED*. The maximum number of digits may be specified in parenthesis

FLOAT(size,d)
A small number with a floating decimal point. The maximum number of digits may be specified in the size parameter. The maximum number of digits to the right of the decimal point is specified in the d parameter

DOUBLE(size,d)
A large number with a floating decimal point. The maximum number of digits may be specified in the size parameter. The maximum number of digits to the right of the decimal point is specified in the d parameter

DECIMAL(size,d)
A DOUBLE stored as a string , allowing for a fixed decimal point. The maximum number of digits may be specified in the size parameter. The maximum number of digits to the right of the decimal point is specified in the d parameter

*The integer types have an extra option called UNSIGNED. Normally, the integer goes from an negative to positive value. Adding the UNSIGNED attribute will move that range up so it starts at zero instead of a negative number.

Date types:

DATE()
A date. Format: YYYY-MM-DD
Note: The supported range is from ‘1000-01-01’ to ‘9999-12-31’

DATETIME()
*A date and time combination. Format: YYYY-MM-DD HH:MM:SS
Note: The supported range is from ‘1000-01-01 00:00:00’ to ‘9999-12-31 23:59:59’

TIMESTAMP()
*A timestamp. TIMESTAMP values are stored as the number of seconds since the Unix epoch (‘1970-01-01 00:00:00’ UTC). Format: YYYY-MM-DD HH:MM:SS
Note: The supported range is from ‘1970-01-01 00:00:01’ UTC to ‘2038-01-09 03:14:07’ UTC

TIME()
A time. Format: HH:MM:SS
Note: The supported range is from ‘-838:59:59’ to ‘838:59:59’

YEAR()
A year in two-digit or four-digit format.
Note: Values allowed in four-digit format: 1901 to 2155. Values allowed in two-digit format: 70 to 69, representing years from 1970 to 2069

*Even if DATETIME and TIMESTAMP return the same format, they work very differently. In an INSERT or UPDATE query, the TIMESTAMP automatically set itself to the current date and time. TIMESTAMP also accepts various formats, like YYYYMMDDHHMMSS, YYMMDDHHMMSS, YYYYMMDD, or YYMMDD.

By |MySQL|Commenti disabilitati su My SQL – Data Types