MySQLi. PHP. GET. POST. Insert. Update. Delete. Segur SQL Inject

This tutorial is about two simple and basic applications to communicate with a MySQLi Database through GET and POST. We will also communicate with the database through a web page with PHP.

mysqlwebhost11

Here in Spanish:
http://kio4.com/appinventor/340C_appinventor_mysqli.htm

4 Likes

1.- MySQLi + PHP + GET + App Inventor.

p340B_mysqli_php_get.aia (3.3 KB)


oooooooooooOOOOOOOOOoooooooooooo
https://.............................../mysqli_get.php
mysqli_get.php

<?php
// Juan Antonio Villalpando
// http://kio4.com
// https://kio4.000webhostapp.com/mysqli_get.php

// 1.- IDENTIFICACION nombre de la base, del usuario, clave y servidor
$db_host="localhost";
$db_name="id13313319_kio4";
$db_login="id13313319_juanantonio";
$db_pswd="contraseña";

// 2.- CONEXION A LA BASE DE DATOS
$link = new mysqli($db_host, $db_login, $db_pswd, $db_name);

$boton = $_GET['boton'];

///////////////////////////////   INSERTAR - INSERT ////////////////////////////////////
if ($boton == "btnInsertar"){
    $Nombre = $_GET['Nombre'];
    $Edad = $_GET['Edad'];
    $Ciudad = $_GET['Ciudad'];
    $query="insert into personas (Nombre, Edad, Ciudad) values ('$Nombre','$Edad','$Ciudad')";
$result = mysqli_query($link, $query);
print("Datos agregados a la base.");
mysqli_close($link);
}
///////////////////////////////   BORRAR - DELETE  ////////////////////////////////////
if ($boton == "btnBorrar"){
    $Nombre = $_GET['Nombre'];
    $query="delete from personas where Nombre='$Nombre'";
$result = mysqli_query($link, $query);
print("Datos borrados.");
mysqli_close($link);
}
//////////////////////////////   ACTUALIZAR - UPDATE  ///////////////////////////////
if ($boton == "btnActualizar"){
    $Nombre = $_GET['Nombre'];
    $Edad = $_GET['Edad'];
    $Ciudad = $_GET['Ciudad'];
    $query="update personas set Edad='$Edad', Ciudad='$Ciudad' WHERE Nombre='$Nombre'";
$result = mysqli_query($link, $query);
print("Datos modificados.");
mysqli_close($link);
}

///////////////////// BUSCAR POR NOMBRE - SEARCH BY NAME /////////////////////////////
if ($boton == "btnBuscarNombre"){
	$Nombre=$_GET['Nombre'];
	$hacer = mysqli_query ($link, "SELECT * FROM personas WHERE Nombre='$Nombre' ");
	enviar_respuesta($hacer);
}
/////////////////////// MOSTRAR TABLA - SHOW TABLE  /////////////////////////////////////
if ($boton == "btnVerTabla"){
	$hacer = mysqli_query ($link, "SELECT * FROM personas");
	enviar_respuesta($hacer);
}

////////////////////////////// RESPUESTA - RESPONSE ///////////////////////
// En los casos que hay btnBuscarNombre o btnVerTabla y se debe enviar una respuesta actúa este código.
function enviar_respuesta($hacer)
{
$resultado = mysqli_query($GLOBALS['link'], "SHOW COLUMNS FROM personas");
$numerodefilas = mysqli_num_rows($resultado);
	if ($numerodefilas > 0) {
	$en_csv='';
		while ($rowr = mysqli_fetch_row($hacer)) {
			for ($j=0;$j<$numerodefilas;$j++) {
			$en_csv .= $rowr[$j].", ";
			}
		$en_csv .= "\n";
		}
	}

print $en_csv;
}
///////////////////////////////////////////////////////////////////
?>			
1 Like

2.- MySQLi + PHP + POST + App Inventor.

p340B_mysqli_php_post.aia (3.8 KB)


oooooooooooOOOOOOOOOoooooooooooo
http://.............../mysqli_post.php
mysqli_post.php

<?php
// Juan Antonio Villalpando
// juana1991@yahoo.com 
// http://kio4.com
// https://kio4.000webhostapp.com/mysqli_post.php

// 1.- IDENTIFICACION nombre de la base, del usuario, clave y servidor
$db_host="localhost";
$db_name="id13313319_kio4";
$db_login="id13313319_juanantonio";
$db_pswd="contraseña";

// 2.- CONEXION A LA BASE DE DATOS
$link = new mysqli($db_host, $db_login, $db_pswd, $db_name);

$boton = $_POST['boton'];

///////////////////////////////   INSERTAR - INSERT ////////////////////////////////////
if ($boton == "btnInsertar"){
    $Nombre = $_POST['Nombre'];
    $Edad = $_POST['Edad'];
    $Ciudad = $_POST['Ciudad'];
    $query="insert into personas (Nombre, Edad, Ciudad) values ('$Nombre','$Edad','$Ciudad')";
$result = mysqli_query($link, $query);
print("Datos agregados a la base.");
mysqli_close($link);
}
///////////////////////////////   BORRAR - DELETE  ////////////////////////////////////
if ($boton == "btnBorrar"){
    $Nombre = $_POST['Nombre'];
    $query="delete from personas where Nombre='$Nombre'";
$result = mysqli_query($link, $query);
print("Datos borrados.");
mysqli_close($link);
}
//////////////////////////////   ACTUALIZAR - UPDATE  ///////////////////////////////
if ($boton == "btnActualizar"){
    $Nombre = $_POST['Nombre'];
    $Edad = $_POST['Edad'];
    $Ciudad = $_POST['Ciudad'];
    $query="update personas set Edad='$Edad', Ciudad='$Ciudad' WHERE Nombre='$Nombre'";
$result = mysqli_query($link, $query);
print("Datos modificados.");
mysqli_close($link);
}

///////////////////// BUSCAR POR NOMBRE - SEARCH BY NAME /////////////////////////////
if ($boton == "btnBuscarNombre"){
	$Nombre=$_POST['Nombre'];
	$hacer = mysqli_query ($link, "SELECT * FROM personas WHERE Nombre='$Nombre' ");
	enviar_respuesta($hacer);
}
/////////////////////// MOSTRAR TABLA - SHOW TABLE  /////////////////////////////////////
if ($boton == "btnVerTabla"){
	$hacer = mysqli_query ($link, "SELECT * FROM personas");
	enviar_respuesta($hacer);
}
/////////////////////// OBTENER ORDENADO - GET SORT  /////////////////////////////////////
if ($boton == "btnOrdenar"){
	$Columna = $_POST['Columna'];
	$hacer = mysqli_query ($link, "SELECT * FROM personas ORDER BY $Columna ASC");
	enviar_respuesta($hacer);
}

////////////////////////////// RESPUESTA - RESPONSE ///////////////////////
// En los casos que hay btnBuscarNombre o btnVerTabla y se debe enviar una respuesta actúa este código.
function enviar_respuesta($hacer)
{
$resultado = mysqli_query($GLOBALS['link'], "SHOW COLUMNS FROM personas");
$numerodefilas = mysqli_num_rows($resultado);
	if ($numerodefilas > 0) {
	$en_csv='';
		while ($rowr = mysqli_fetch_row($hacer)) {
			for ($j=0;$j<$numerodefilas;$j++) {
			$en_csv .= $rowr[$j].", ";
			}
		$en_csv .= "\n";
		}
	}

print $en_csv;
}
///////////////////////////////////////////////////////////////////
?>
1 Like

3.- MySQLi + PHP + POST + Web.

http://................/mysqli_htm_post.php

<html>
<head><meta charset="UTF-8"></head>
<body>
<form name="test" method="post" action="mysqli_htm_post.php">
  <p>Nombre - Name: 
    <input type="text" name="Nombre" value="">
    <br />
Edad - Age: 
<input type="text" name="Edad" value="">
<br />
Ciudad - City: 
<input type="text" name="Ciudad" value="">
<br />
<INPUT TYPE="submit" name="btnInsertar" value="Insertar - Insert">
<INPUT TYPE="submit" name="btnBorrar" value="Borrar - Delete">
<INPUT TYPE="submit" name="btnActualizar" value="Actualizar - Update">
<INPUT TYPE="submit" name="btnBuscarNombre" value="Buscar por Nombre - Search by Name">
<INPUT TYPE="submit" name="btnVerTabla" value="Ver Tabla - Show Table">
</p>
<p>Ordenar por (Nombre, Edad, Ciudad) - Sort by (Nombre, Edad, Ciudad): <input type="text" name="Columna" value="Nombre">
<INPUT TYPE="submit" name="btnOrdenar" value="Ordenar - Sort">
</p>
</form>
</body>
</html>

<?php
// Juan Antonio Villalpando
// juana1991@yahoo.com 
// http://kio4.com
// kio4.000webhostapp.com/mysqli_htm_post.php
/// https://www.000webhost.com/cpanel-login

// 1.- IDENTIFICACION nombre de la base, del usuario, clave y servidor
$db_host="localhost";
$db_name="id13313319_kio4";
$db_login="id13313319_juanantonio";
$db_pswd="Contraseña";

// 2.- CONEXION A LA BASE DE DATOS
$link = new mysqli($db_host, $db_login, $db_pswd, $db_name);

///////////////////////////////   INSERTAR - INSERT ////////////////////////////////////
if(isset($_POST['btnInsertar'])){
    $Nombre = $_POST['Nombre'];
    $Edad = $_POST['Edad'];
    $Ciudad = $_POST['Ciudad'];
    $query="insert into personas (Nombre, Edad, Ciudad) values ('$Nombre','$Edad','$Ciudad')";
$result = mysqli_query($link, $query);
print("Datos agregados a la base.");
mysqli_close($link);
}
///////////////////////////////   BORRAR - DELETE  ////////////////////////////////////
if(isset($_POST['btnBorrar'])){
    $Nombre = $_POST['Nombre'];
    $query="delete from personas where Nombre='$Nombre'";
$result = mysqli_query($link, $query);
print("Datos borrados.");
mysqli_close($link);
}
//////////////////////////////   ACTUALIZAR - UPDATE  ///////////////////////////////
if(isset($_POST['btnActualizar'])){
    $Nombre = $_POST['Nombre'];
    $Edad = $_POST['Edad'];
    $Ciudad = $_POST['Ciudad'];
    $query="update personas set Edad='$Edad', Ciudad='$Ciudad' WHERE Nombre='$Nombre'";
$result = mysqli_query($link, $query);
print("Datos modificados.");
mysqli_close($link);
}

///////////////////// BUSCAR POR NOMBRE - SEARCH BY NAME /////////////////////////////
if(isset($_POST['btnBuscarNombre'])){
	$Nombre=$_POST['Nombre'];
	$hacer = mysqli_query ($link, "SELECT * FROM personas WHERE Nombre='$Nombre' ");
	enviar_respuesta($hacer);
}
/////////////////////// MOSTRAR TABLA - SHOW TABLE  /////////////////////////////////////
if(isset($_POST['btnVerTabla'])){
	$hacer = mysqli_query ($link, "SELECT * FROM personas");
	enviar_respuesta($hacer);
}

/////////////////////// OBTENER ORDENADO - GET SORT  /////////////////////////////////////
if(isset($_POST['btnOrdenar'])){
    $Columna=$_POST['Columna'];
	$hacer = mysqli_query ($link, "SELECT * FROM personas ORDER BY `$Columna` ASC");
	enviar_respuesta($hacer);
}

////////////////////////////// RESPUESTA - RESPONSE ///////////////////////
// En los casos que hay btnBuscarNombre o btnVerTabla y se debe enviar una respuesta actúa este código.
function enviar_respuesta($hacer)
{
$resultado = mysqli_query($GLOBALS['link'], "SHOW COLUMNS FROM personas");
$numerodefilas = mysqli_num_rows($resultado);
	if ($numerodefilas > 0) {
	$en_csv='';
		while ($rowr = mysqli_fetch_row($hacer)) {
			for ($j=0;$j<$numerodefilas;$j++) {
			$en_csv .= $rowr[$j].", ";
			}
		$en_csv .= "<br>"."\n";
		}
	}

print $en_csv;
}
///////////////////////////////////////////////////////////////////
?>

A user asked me how you could upload emoji to the database.
I tried this and it worked for me:

trebujena3

In file .php add this:
// 2.- Connection to the database.
$link = new mysqli($db_host, $db_login, $db_pswd, $db_name);
$link->set_charset(‘utf8mb4’); // ADD THIS

About SQL Injection in MySQLi.

This interesting discussion on Kodular gave me the idea to adapt my code to a higher level of security. It is about protecting it against SQL Inject,…

… for this I used the ideas of this tutorial:

2.- MySQLi + PHP + POST + App Inventor.

p340B_mysqli_php_post.aia (3.8 KB)

<?php
// Juan Antonio Villalpando
// http://kio4.com/appinventor/340D_appinventor_mysqli_inject.htm

// 1.- IDENTIFICACION nombre de la base, del usuario, clave y servidor
$db_host="localhost";
$db_name="my_database";
$db_login="juan";
$db_pswd="contraseña";

// 2.- CONEXION A LA BASE DE DATOS
$link = new mysqli($db_host, $db_login, $db_pswd, $db_name);

if($link->connect_error) {
  exit('Error de conexion con la base de datos.');
}
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link->set_charset("utf8mb4");

$boton = $_POST['boton'];

///////////////////////////////   INSERTAR - INSERT ////////////////////////////////////
if ($boton == "btnInsertar"){
    $Nombre = $_POST['Nombre'];
    $Edad = $_POST['Edad'];
    $Ciudad = $_POST['Ciudad'];
$stmt = $link->prepare("INSERT INTO personas (Nombre, Edad, Ciudad) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $Nombre, $Edad, $Ciudad);
$stmt->execute();
$stmt->close();
print("Datos agregados a la base.");
}

///////////////////////////////   BORRAR - DELETE  ////////////////////////////////////
if ($boton == "btnBorrar"){
    $Nombre = $_POST['Nombre'];
$stmt = $link->prepare("DELETE FROM personas WHERE Nombre = ?");
$stmt->bind_param("s", $Nombre);
$stmt->execute();
$stmt->close();
print("Datos borrados.");
}

//////////////////////////////   ACTUALIZAR - UPDATE  ///////////////////////////////
if ($boton == "btnActualizar"){
    $Nombre = $_POST['Nombre'];
    $Edad = $_POST['Edad'];
    $Ciudad = $_POST['Ciudad'];
$stmt = $link->prepare("UPDATE personas SET Edad = ?, Ciudad = ? WHERE Nombre = ?");
$stmt->bind_param("sss", $Edad, $Ciudad, $Nombre);
$stmt->execute();
$stmt->close();
print("Datos modificados.");
}

///////////////////// BUSCAR POR NOMBRE - SEARCH BY NAME /////////////////////////////
if ($boton == "btnBuscarNombre"){
	$Nombre=$_POST['Nombre'];
$stmt = $link->prepare("SELECT * FROM personas WHERE Nombre = ?");
$stmt->bind_param("s", $Nombre);
$stmt->execute();
$stmt->bind_result($id, $Nombre, $Edad, $Ciudad); 
     while ( $stmt-> fetch() ) {
          echo $id.",".$Nombre.",".$Edad.",".$Ciudad."\n";
     }
$stmt->close();
}

/////////////////////// MOSTRAR TABLA - SHOW TABLE  /////////////////////////////////////
if ($boton == "btnVerTabla"){
$stmt = $link->prepare("SELECT * FROM personas");
$stmt->bind_param();
$stmt->execute();
$stmt->bind_result($id, $Nombre, $Edad, $Ciudad); 
     while ( $stmt-> fetch() ) {
          echo $id.",".$Nombre.",".$Edad.",".$Ciudad."\n";
     }
$stmt->close();
}
/////////////////////// OBTENER ORDENADO - GET SORT  /////////////////////////////////////
if ($boton == "btnOrdenar"){
	$Columna = $_POST['Columna'];
$stmt = $link->prepare("SELECT * FROM personas ORDER BY $Columna ASC");
$stmt->bind_param();
$stmt->execute();
$stmt->bind_result($id, $Nombre, $Edad, $Ciudad); 
     while ( $stmt-> fetch() ) {
          echo $id.",".$Nombre.",".$Edad.",".$Ciudad.","."\n";
     }
$stmt->close();
}
///////////////////////////////////////////////////////////////////
?>

If you also use encrypted data, for example with this extension com.KIO4_SecretKey.aix, the data will be more protected.

Regards,
(Tutorial in Spanish)

Interesting about SQL Inject.

2 Likes

I want to make a project like this but it is about Register and Login. Please help.

First do the examples on this page to see if they work for you.

Very very thank you For this. But can you tell me how I can detect that if there(MySql) any data changed I got the result in my app. is this possible? Please try to reply.

I believe you will have to poll your dB from the app at regular intervals, unless you are able to set up a listener of some kind.

@AppHelper_Studio

Take a look at

Firebase realtime as data base.

JavaScript (ajax) MySQL in realtime.

2 Likes

Thank you very much.

hi , I had problem with inserting data from phone device to database
got 1101 error and I couldn't understand what's going on!! please help as an English document . when check the query link with browser and insert data , query worked and great. but in app didn't work and show me error.
(unable to get a response with specified URL)

You need to show your relevant blocks, and your php file

that's you talked about its waste my time and didn't make any sense - when I did same as blown - today I did same as many video on the internet . I opened his file project and everything just upload ,don't change anything, but didn't work.