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 column Nombre
, the record contains Nombre Apellido 2Apellido
. I need to extract the Nombre
.
What you need is to make use of
SUBSTRING_INDEX(cadena, delimitador, numero)
to find in the string the first part up to the first white space:What the function does is split the string into chunks given by the delimiter and returns the
numero
first chunks. Ifnumero
it's negative, then it returns thenumero
latest. In the example I use1
so that it returns only the first part (whatever is before the first delimiter or white space).You can see an example online here .
PS: I have to warn you that the code suffers from serious security problems associated with SQL injection that must be solved with prepared queries or using
mysqli::real_escape_string()
.using an explode() of " " you can get the first word. Cheers!