[ESP/ENG] Programar para Hive #3 PHP | Programming for Hive #3 PHP

previewdevhive2.png

Nota: Toda referencia a Base de datos de Hive, debe entenderse como Base de Datos del proyecto HiveSQL.

Vamos progresando y ya hoy podemos comenzar a programar… pero voy desde el principio. Aquellos interesados en crear proyectos para Hive (o los que solo tienen curiosidad) les recomiendo lean los dos Posts anteriores: Programar para Hive y Programar para Hive #2 para que tengan toda la información paso por paso.

Llegado a este punto, puedo informar que he buscado y rebuscado y no existe un tutorial en Español tan detallado como este que van a leer. Es mi intención ahorrarles el trabajo de volver a recorrer un camino empedrado, si ya yo encontré un atajo.

Recapitulando: Primero se paga el registro, se reciben las credenciales para conectar a la base de datos de Hive, para ello se usa el programa DBeaver (es el que recomiendo), y ahora les explico como se realizan las búsquedas SQL en la base de datos de Hive, escribiendo código PHP.

Aquí viene un freno (hoy estoy inspirado 😏), aclarar una vez más, que la base de datos de Hive está en MSSQL Server (nada de MySQL, ni MariaDB), por lo que el hosting que contraten, tiene que tener compatibilidad en PHP con este tipo de base de datos. Investigando un poco, solo encontré que Justhost, HostPapa y GoDaddy ofrecen este servicio. ¡Quedan Advertidos!

hosting.png
Fuente: Imagen editada con los logos de cada web

Se puede realizar el proyecto con conexión local (creando un server web en la PC), mi recomendación es usar XAMPP (Tutorial para instalar XAMPP). Deben instalar por supuesto las librerías para que funcione el MSSQL. Aquí los pasos:

  1. Descargar el archivo msodbcsql.msi
  2. Descargar el archivo php_sqlsrv-5.7.1preview-7.3-ts-vc15-x64.zip
  3. Instalar el archivo msodbcsql.msi
  4. Descompactar el archivo php_sqlsrv-5.7.1preview-7.3-ts-vc15-x64.zip
  5. Copiar el archivo php_sqlsrv.dll en la ruta xampp\php\ext
  6. Abrir con el bloc de notas (por ejemplo) el archivo php.ini (que se encuentra en la ruta xampp\php)
  7. Buscar dentro del archivo php.ini este texto: Module Settings
  8. Debajo escribir lo siguiente: extension=php_sqlsrv.dll
  9. Buscar dentro del archivo php.ini este texto: extension=odbc (si no existe, agregarlo)
  10. Ahora inicie el servicio Apache del XAMPP

Con estos pasos, ya puede programar para Hive desde su PC y de forma local. El lenguaje de programación que yo utilicé fue PHP. Hay que crear dos archivos, uno donde escribir los códigos de la conexión a la base de datos, y el otro para realizar la consulta SQL.

El primero, lo llamaremos cfgdata.php (o como usted desee) dentro va el siguiente código:

<?php
$serverName = "Aquí la url del server de Hive";
$connectionInfo = array( "Database"=>"Aquí el nombre de la base de datos", "UID"=>"Aquí el usuario", "PWD"=>"Aquí la contraseña","CharacterSet" => "UTF-8");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
?>

Todos los datos que se piden en el código, se reciben con el registro en HiveSQL.io

El segundo archivo es el principal getpost.php. Aquí se escribe el código para realizar la consulta SQL y que devuelva los datos en formato JSON:

<?php
require_once('cfgdata.php');

header('Content-Type: application/json;charset=utf-8');

$sql = "SELECT title FROM DBHive.dbo.Comments WHERE author LIKE 'lapasta' AND title NOT LIKE ''";
$result = sqlsrv_query($conn, $sql);

while($row = sqlsrv_fetch_array($result)) {
$producto[]= array_map('utf8_encode',$row);
}

$jsonx= json_encode($producto,JSON_UNESCAPED_UNICODE);
echo utf8_decode($jsonx);

sqlsrv_close( $conn );
?>

Explicación del código de la consulta:

SELECT title FROM DBHive.dbo.Comments WHERE author LIKE 'lapasta' AND title NOT LIKE ''

Esta consulta nos va a mostrar todos los Post escritos por un usuario específico. Un tip: la tabla Comments tiene tanto los Post escritos por el usuario, como sus Comentarios, se diferencian fácilmente, porque en los comentarios el campo title está vacío.

Explico la consulta: Mostrar (SELECT) el campo donde están los títulos de los Posts (title), que se encuentra en la base de datos de Hive en la tabla Comments (DBHive.dbo.Comments), donde (WHERE) solo quiero ver solo los Posts del usuario (author LIKE) ‘lapasta’ y (AND) que el campo título (title) del Post no este (NOT LIKE) en blanco o vacío ‘’

jsonphp.png
Datos extraídos de la base de datos de Hive y convertidos en formato JSON

Las combinaciones o criterios de búsquedas de las consultas son muchas, depende de la información que desee obtener cada quien en su proyecto.

Recordar que hasta ahora solo estamos programando para obtener información. Pues mi proyecto para Hive, va en ese sentido. Ya les estaré actualizando sobre el mismo próximamente.

[English Text]

Note: *Any reference to Hive Database should be understood as HiveSQL Project Database.

We are progressing and today we can start programming... but I'm going from the beginning. Those interested in creating projects for Hive (or those who are just curious) I recommend you to read the two previous Posts: Programming for Hive and Programming for Hive #2 to have all the information step by step.

At this point, I can report that I have searched and searched and there is no tutorial in Spanish as detailed as this one you are about to read. It is my intention to save you the trouble of retracing a cobblestone path, if I have already found a shortcut.

To recapitulate: First you pay the registration, you receive the credentials to connect to the Hive database, for this you use the DBeaver program (it is the one I recommend), and now I explain how to perform SQL searches in the Hive database, writing PHP code.

Here comes a brake (today I am inspired 😏), to clarify once again, that the Hive database is in MSSQL Server (no MySQL, nor MariaDB), so the hosting you hire, must have PHP compatibility with this type of database. Investigating a little, only Justhost, HostPapa and GoDaddy offer this service. Be warned!

hosting.png
Source: Edited image with the logos of each web site

You can do the project with local connection (creating a web server on the PC), my recommendation is to use XAMPP (Tutorial to install XAMPP). You must of course install the libraries for MSSQL to work. Here are the steps:

  1. Download the file msodbcsql.msi
  2. Download the file php_sqlsrv-5.7.1preview-7.3-ts-vc15-x64.zip
  3. Install the msodbcsql.msi file.
  4. Unzip the php_sqlsrv-5.7.1preview-7.3-ts-vc15-x64.zip file.
  5. Copy the file php_sqlsrv.dll in the path xampp\php\ext
  6. Open with the notepad (for example) the php.ini file (located in the xampp\php path).
  7. Find inside the php.ini file this text: Module Settings
  8. Underneath write the following: extension=php_sqlsrv.dll
  9. Search inside the php.ini file for this text: extension=odbc (if it does not exist, add it).
  10. Now start the Apache service of XAMPP

With these steps, you can now program for Hive from your PC and locally. The programming language I used was PHP. You have to create two files, one where to write the database connection codes, and the other one to make the SQL query.

The first one, we will call it cfgdata.php (or as you wish) inside goes the following code:

<?php
$serverName = "Here is the url of the Hive server";
$connectionInfo = array( "Database"=>"Here is the name of the database", "UID"=>"Here the user", "PWD"=>"Here is the password","CharacterSet" => "UTF-8");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
?>

All the data requested in the code is received with the record in HiveSQL.io

The second file is the main getpost.php file. Here you write the code to perform the SQL query and return the data in JSON format:

<?php
require_once('cfgdata.php');

header('Content-Type: application/json;charset=utf-8');

$sql = "SELECT title FROM DBHive.dbo.Comments WHERE author LIKE 'lapasta' AND title NOT LIKE ''";
$result = sqlsrv_query($conn, $sql);

while($row = sqlsrv_fetch_array($result)) {
$producto[]= array_map('utf8_encode',$row);
}

$jsonx= json_encode($producto,JSON_UNESCAPED_UNICODE);
echo utf8_decode($jsonx);

sqlsrv_close( $conn );
?>

Explaining the query code:

SELECT title FROM DBHive.dbo.Comments WHERE author LIKE 'lapasta' AND title NOT LIKE ''

This query will show us all the Posts written by a specific user. A tip: the Comments table has both the Post written by the user, and his Comments, they are easily differentiated, because in the comments the title field is empty.

Explain the query: Show (SELECT) the field where are the titles of the Posts (title), which is in the Hive database in the table Comments (DBHive.dbo.Comments), where (WHERE) I only want to see only the Posts of the user (author LIKE) 'lapasta' and (AND) that the field title (title) of the Post is not (NOT LIKE) blank or empty ''.

jsonphp.png
Data extracted from the Hive database and converted to JSON format

The combinations or search criteria of the queries are many, depending on the information you want to obtain in your project.

Remember that so far we are only programming to obtain information. Well, my project for Hive is going in that direction. I will be updating you about it soon.

Imagen tomada por el autor / Images taken by the author
Translated with www.DeepL.com/Translator

firma.png

H2
H3
H4
3 columns
2 columns
1 column
Join the conversation now
Logo
Center