This response is open to the community changes or suggestion it is accepted for a good reference for future readers.
To send an array of JavaScript, using jQuery's AJAX, to receive it in PHP and to save it in MySQL, the following steps are used:
1. How to send data that stores a jQuery variable to php and save to the database with MySQLi?
This variable var community = []; You can imagine that it is a global variable because it mentions that it stores information or data. Although it remains empty like this:
var comunidad = [];
Suppose that variable contains this stored information.
var comunidad = ["Pedro", "Juan", "Carlos"];
The following request in ajax would be like this:
function grabarBD() {
// Datos almacenados nombres de usuarios
var comunidad = [];
// Convertir a objeto
var data = {};
data.comunidad = comunidad;
// enviar por POST mediante AJAX
var url = 'grabarbd.php'; //este es el PHP al que se llama por AJAX
$.ajax({
method: 'POST',
url: url,
data: data, //acá están todos los parámetros (valores a enviar) del
POST
success: function(response){
// Se ejecuta al finalizar
// mostrar si está OK en consola
console.log(response);
}
});
}
recordbd.php the value is received and recorded in the database.
if (!empty($_POST['comunidad'])) {
// Datos recibidos
$comunidad = implode(', ', $_POST['comunidad']);
//Datos de conexión a la base
$host = "localhost";
$usuario = "root";
$clave = "";
$basedatos = "comunidad";
$tabla = "comunidad";
// Conectar a la base
// la variable $myslqi contendrá el objeto con la conexión
$mysqli = mysqli_connect($host, $usuario, $clave, $basedatos);
if (mysqli_connect_errno($mysqli)) {
die( "Error al conectar a MySQL: " . mysqli_connect_error() );
}
// insert en la base
$sentencia = $mysqli->prepare("INSERT INTO $tabla (id, user_comunidad)
VALUES (?, ?)");
$sentencia->bind_param("is", $id, $comunidad );
$sentencia->execute();
// Cerrar la conexión
$sentencia = null;
$mysqli = null;
// Devolver una respuesta a JavaScript
echo "Se grabó nuevo usuarios a la comunidad";
}
As a result stored in the database:
id user_comunidad
---- ---------------------
1 Pedro, Juan, Carlos
Referece the following: source
Note: The following source only allows adding a record in the database in this modified example stores continuous records to the database taking into account that the id is a primary id with the attribute AUTO_INCREMENT.