Web Design

How to use multiple HTML form and only one PHP engine

How to use multiple HTML form and only one PHP engine

form.html

<html>
<body>
  
<form action="engine.php?action=firstEvent" method="post">
    Text: <input type="text" name="content"><br/>
    <input type="submit" value="Insert Event">
</form>

<form action="engine.php?action=secondEvent" method="post">
    Text: <input type="text" name="content"><br/>
    <input type="submit" value="Insert Event">
</form>

<form action="engine.php?action=thirdEvent" method="post">
    Text: <input type="text" name="content"><br/>
    <input type="submit" value="Insert Event">
</form>
  
</body>
</html>

engine.php

<?php
// Get HTML form data
if($_GET['action'] == 'firstEvent'){
    echo 'firstEvent <br>';
    $content = $_REQUEST['content']; 
    echo $content;
}

if($_GET['action'] == 'secondEvent'){
    echo 'secondEvent <br>';
    $content = $_REQUEST['content']; 
    echo $content;
}

if($_GET['action'] == 'thirdEvent'){
    echo 'thirdEvent <br>';
    $content = $_REQUEST['content']; 
    echo $content;
}
?>

Notice that the HTML form can send:
– engine.php?action=firstEvent
– engine.php?action=secondtEvent
– engine.php?action=thirdEvent

The PHP script makes different actions if it gets:
– GET[‘action’] == ‘firstEvent’
– GET[‘action’] == ‘secondEvent’
– GET[‘action’] == ‘thirdEvent’

By |PHP, Web Design|Commenti disabilitati su How to use multiple HTML form and only one PHP engine

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 – MySQL – Simple Calendar

PHP – MySQL – Simple Calendar

DOWNLOAD

 

We want a calendar like this:

—–

Title of the event

Start date – End date

Content bla bla bla … Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus.

Link>

—–

Create database

Entriamo in phpMyAdmin

In alto posizioniamoci su localhost> mydatabase

Usando phpMyAdmin creiamo:

Colonna di sinistra> ‘Crea tabella’> MyISAM

Nome tabella: calendar’

Struttura> aggiungere i campi

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

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

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

Campo: content
Tipo: LONGTEXT -> it must contain max 4,294,967,295 characters
Lunghezza: -> non specifichiamo nulla
Predefinito: Nessuno
Null: deselezionato
Indice: nessuno
AUTO_INCREMENT: deselezionato

Campo: startDate
Tipo: DATETIME -> Format: YYYY-MM-DD HH:MM:SS Example: 2014-12-31 23:59:59

Campo: endDate
Tipo: DATETIME -> Format: YYYY-MM-DD HH:MM:SS Example: 2014-12-31 23:59:59

PhpMyAdmin
php-mysql-008

calendar_input_form.php

The input form

<!-- CONNESSIONE DB START -->
<?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!<br><br>";
  }
  // Create DATABASE connection - END
  ?>
<!-- CONNESSIONE DB END -->

<html>
<body>
 
<!-- FORM INSERT START -->
<!-- Send data to calendar_insert_engine.php -->
<form action="calendar_insert_engine.php?action=addEvent" method="post">
    Title: <input type="text" name="title"><br/>
    Link: <input type="text" name="link"><br/>
    Start date (YYYY-MM-DD HH:MM): <input type="text" name="startDate"><br/>
    End date (YYYY-MM-DD HH:MM): <input type="text" name="endDate"><br/>
    Content: <br/>
    <textarea rows="15" cols="30" name="content"></textarea><br/>
    <input type="submit" value="Insert Event">
</form>
<!-- FORM INSERT END -->
 
</body>
</html>

<!-- QUERY DB START -->
<?php
// SELECT asterisco (tutti i dati) dalla tabella START
// inserisco i dati nella variabile $result
// ordinati in base a startDate in ordine decrescente
$result = mysqli_query($con,"SELECT * FROM calendar ORDER BY startDate DESC");
 
echo "<strong>Calendar - Event List: (Order by startDate DESC)</strong>";
echo "<br><br>ID - Title - Link - Start date - End date - Content<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['id'] . " - " .$row['title'] . " - " . $row['link'] . " - " . $row['startDate'] . " - " . $row['endDate'] . " - " . $row['content'];
  echo "<br>";
  }
// SELECT asterisco (tutti i dati) dalla tabella END
 
mysqli_close($con); 
echo "<br>Great! Connection Closed!"; 
?>
<!-- QUERY DB END -->

calendar_insert_engine.php

The PHP engine to store data

<?php
 
$host="localhost"; //lasciare com'è se utilizzate bluehost
$username="lucedigi_user"; 
$password="mypassword"; 
$db_name="lucedigi_testphp"; // database name
$tbl_name="calendar"; //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");
 
// Ottengo i dati dal form HTML
// Se dal form arriva - action=addEvent - esegui il seguente
if($_GET['action'] == 'addEvent'){
    $title = mysql_real_escape_string($_POST['title']);
    $link = mysql_real_escape_string($_POST['link']);
    $content = mysql_real_escape_string($_POST['content']);
    $startDate = date('Y-m-d H:i:s', strtotime($_POST['startDate'] . ":00"));
    $endDate = date('Y-m-d H:i:s', strtotime($_POST['endDate'] . ":00"));

    // Invio una query per inserire i dati
    mysql_query("INSERT INTO calendar VALUES (null, '$title', '$link', '$content', '$startDate', '$endDate');");
	echo "Great! New Record Inserted!";
}

?>

IMPROVE INPUT FORM WITH date tag

<!-- CONNESSIONE DB START -->
<?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!<br><br>";
  }
  // Create DATABASE connection - END
  ?>
<!-- CONNESSIONE DB END -->

<html>
<body>
 
<!-- FORM INSERT START -->
<!-- Send data to calendar_insert_engine.php -->
<form action="calendar_insert_engine.php?action=addEvent" method="post">
    Title: <input type="text" name="title"><br/>
    Link: <input type="text" name="link"><br/>
    Start date (this send -> 2018-02-05): <input type="date" name="startDate"><br/>
    End date (this send -> 2018-02-05): <input type="date" name="endDate"><br/>
    Content: <br/>
    <textarea rows="15" cols="30" name="content"></textarea><br/>
    <input type="submit" value="Insert Event">
</form>
<!-- FORM INSERT END -->
 
</body>
</html>

<!-- QUERY DB START -->
<?php
// SELECT asterisco (tutti i dati) dalla tabella START
// inserisco i dati nella variabile $result
// ordinati in base a startDate in ordine decrescente
$result = mysqli_query($con,"SELECT * FROM calendar ORDER BY startDate DESC");
 
echo "<strong>Calendar - Event List: (Order by startDate DESC)</strong>";
echo "<br><br>ID - Title - Link - Start date - End date - Content<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['id'] . " - " .$row['title'] . " - " . $row['link'] . " - " . $row['startDate'] . " - " . $row['endDate'] . " - " . $row['content'];
  echo "<br>";
  }
// SELECT asterisco (tutti i dati) dalla tabella END
 
mysqli_close($con); 
echo "<br>Great! Connection Closed!"; 
?>
<!-- QUERY DB END -->
<?php
 
$host="localhost"; //lasciare com'è se utilizzate bluehost
$username="lucedigi_user"; 
$password="mypassword"; 
$db_name="lucedigi_testphp"; // database name
$tbl_name="calendar"; //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");
 
// Ottengo i dati dal form HTML
// Se dal form arriva - action=addEvent - esegui il seguente
if($_GET['action'] == 'addEvent'){
    $title = mysql_real_escape_string($_POST['title']);
    $link = mysql_real_escape_string($_POST['link']);
    $content = mysql_real_escape_string($_POST['content']);
    $startDate = date('Y-m-d H:i:s', strtotime($_POST['startDate'] . " 00:00:00"));
    $endDate = date('Y-m-d H:i:s', strtotime($_POST['endDate'] . " 00:00:00"));

    // Invio una query per inserire i dati
    mysql_query("INSERT INTO calendar VALUES (null, '$title', '$link', '$content', '$startDate', '$endDate');");
	echo "Great! New Record Inserted!";
}

?>

Notice:
the HTML form send data as 2018-02-05
the PHP script add ” 00:00:00″ -> strtotime($_POST[‘startDate’] . ” 00:00:00″
because MySQL DATETIME needs the format: YYYY-MM-DD HH:MM:SS Example: 2014-12-31 23:59:59

By |PHP, Web Design|Commenti disabilitati su PHP – MySQL – Simple Calendar

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