Show first word of a field in SQL

3

I have the need to get the first word of a data from the table. I have searched for information but I only see to get the characters you want.

<?php
    $usuario = $_SESSION['username'];
    $pass = $_SESSION['password'];

    $results = $mysqli->query("SELECT Nombre, SUBSTRING(Nombre, 1,20) AS palabra, 
                              IdUsuario, Username, Password 
                              FROM Usuarios 
                              WHERE Username='$usuario' AND Password ='$pass'");
    mysqli_set_charset("utf8");
    if($res = $results->fetch_array()) {}

    ?>

For example, in the Nombre column, the record contains Nombre Apellido 2Apellido . I need to extract the Nombre .

    
asked by Miguel 04.09.2018 в 12:41
source

2 answers

1

What you need to do is use SUBSTRING_INDEX(cadena, delimitador, numero) to find in the chain the first part until the first blank space:

<?php
/* Evitamos inyección SQL */
$usuario = $mysqli->real_escape_string($_SESSION['username']);
$pass = $mysqli->real_escape_string($_SESSION['password']);
/* Cambiamos a UTF-8 *ANTES* de hacer consultas SQL */
$mysqli->set_charset("utf8");

/* Realizamos la consulta SQL */
$results = $mysqli->query("
  SELECT
    Nombre,
    SUBSTRING_INDEX(Nombre, ' ', 1) palabra,
    IdUsuario,
    Username,
    Password
  FROM Usuarios 
  WHERE Username='$usuario' AND Password ='$pass'
");
if($res = $results->fetch_array()) {
    /* Aquí se supone que haces lo necesario con $res['palabra'] */
}
?>

What the function does is divide the string into portions given by the delimiter and return the first numero . If numero is negative, then returns the numero last. In the example I use 1 to return only the first part (whatever is before the first delimiter or blank).

You can see a online example here .

PS: I have to warn you that the code suffers from the serious security problems associated with SQL injection to be solved with prepared queries or using mysqli::real_escape_string() .

    
answered by 04.09.2018 / 12:47
source
0

using an explode () of "" you can get the first word. Greetings!

<?php
$usuario = $_SESSION['username'];
$pass = $_SESSION['password'];

$results = $mysqli->query("SELECT Nombre, SUBSTRING(Nombre, 1,20) AS palabra, 
                          IdUsuario, Username, Password 
                          FROM Usuarios 
                          WHERE Username='$usuario' AND Password ='$pass'");
mysqli_set_charset("utf8");

while($row = $result->fetch_assoc()) {
    echo explode(" ",$row['Nombre'])[0];
}

?>
    
answered by 04.09.2018 в 12:50