How to concatenate two fields?

1

You will see this code is an autocomplete that works with PHP and JQuery and a bit of Ajax. It works, because I write names and I get the names of the database. But what I also need is that they help me to concatenate the name and the surname. So that they leave me in the same query. One next to the other.

<?php

include("conexion.php");

if(isset($_POST['query']))
{

$output = '';
$query = "SELECT nombre FROM personas WHERE nombre LIKE '%". $_POST['query']."%'";
$result = mysqli_query($conn, $query);
$output = '<ul class="list-unstyled">';

if(mysqli_num_rows($result) > 0 )
{

    while($row = mysqli_fetch_array($result))
    {

          $output .= '<li><a href="www.google.com.do">'.$row['nombre'].'</a></li>';
    }
}
else
{
     $output .= '<li>Not found</li>';
}

$output .= '</ul>';
echo $output;

}

? >

    
asked by luis 29.08.2016 в 01:50
source

1 answer

2

You can do it by php or by mysql with the CONCAT function:

PHP

<?php

include("conexion.php");

if (isset($_POST['query'])) {

    $query = "SELECT nombre, apellido FROM personas WHERE nombre LIKE '%". $_POST['query']."%'";
    $result = mysqli_query($conn, $query);
    $output = '<ul class="list-unstyled">';

    if (mysqli_num_rows($result) > 0 ) {

        while ($row = mysqli_fetch_array($result)) {

            $output .= '<li><a href="www.google.com.do">'.$row['nombre'].' '.$row['apellido'].</a></li>';
        }
    } else {
        $output .= '<li>Not found</li>';
    }

    $output .= '</ul>';
    echo $output;
}

MySQL

<?php

include("conexion.php");

if (isset($_POST['query'])) {

    $query = "SELECT CONCAT(nombre, ' ', apellido) as nombre_completo FROM personas WHERE nombre LIKE '%". $_POST['query']."%'";
    $result = mysqli_query($conn, $query);
    $output = '<ul class="list-unstyled">';

    if (mysqli_num_rows($result) > 0 ) {

        while ($row = mysqli_fetch_array($result)) {

            $output .= '<li><a href="www.google.com.do">'.$row['nombre_completo'].</a></li>';
        }
    } else {
        $output .= '<li>Not found</li>';
    }

    $output .= '</ul>';
    echo $output;
}
    
answered by 29.08.2016 / 02:38
source