How to list and query contacts with PHP and Javascript?

Asked

Viewed 1,012 times

0

Hello, I need a practical example in PHP that brings me to contact list of a database table, and click on in a contact is displayed the information of the same. Follow the image below:

inserir a descrição da imagem aqui

I am a beginner in PHP, I tried to use the query by AJAX, but I was not successful. I tried to research in numerous places some example that could help me with the question, but found nothing either.

I would like to accomplish this without updating the screen or redirecting to another page (Javascript).

I count on your help, thank you!

  • 2

    Try to break your problem into smaller problems the way it gets too wide and difficult for someone to help you.

  • 1

    You are asking for an example while you should post a question. I’m sorry but the issue of the way it is does not fit the site templates. I suggest to do a [tour] and read the guide [Ask].

2 answers

1


thus tries HTML file

<html>
<title>teste</title>
<head>
    <!-- CSS aqui -->
</head>
<body>

    <h1>Consultar</h1>

    <p>Clique no botao</p>
    <p><button class='doQuery' data-userid='1'>Marco</button></p>
    <p><button class='doQuery' data-userid='2'>Alvori</button></p>
    <p><button class='doQuery' data-userid='3'>Cintia</button></p>
    <p><button class='doQuery' data-userid='4'>Jair</button></p>

    <hr>
    <div id='resultadofinal'></div>

<!-- JS aqui no final da pagina para carregar mais rapido -->

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(function(){

    $.system = {};
    $.system.path = '/stackoverflow/exemplo1/'; // ou colocar a pasta raiz $.system.path = '/';

    jQuery(".doQuery").click(function(){

        var id_usuario = $(this).attr('data-userid');

        jQuery.post( $.system.path + 'result.php' , { id_usuario:id_usuario,outraval:'valor_da_val' } , function(result,status){ 


            if( status == 'success' )
            {

                var json = jQuery.parseJSON(result);

                if( json.resultStatus == 'success' )
                {

                    jQuery("#resultadofinal").html(json.html);

                }
                else
                {
                    jQuery("#resultadofinal").html(json.resultMSG);

                }

            } 
            else
            {
                alert('Erro no requisicao jquery');
            }


        } );
    });
});
</script>

</body>
</html>

FILE result.php - do your sql according to your database here I took example of xampp

<?php 

$con   = mysql_connect('localhost','root','');
$db    = mysql_select_db('webauth',$con);


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

    // input    
    $id    = $_POST['id_usuario'];

    ####
    $html  = array();
    $table = 'user_pwd';

    // your SQL


    //Query
    $sql = mysql_query("SELECT * FROM {$table} WHERE id = '{$id}'",$con);

    if( mysql_error() )
    {
        $html['resultStatus'] = 'error';    
        $html['resultMSG']    = mysql_error();
    } 
    else
    {

        if( mysql_num_rows($sql) >= 1 )
        {

            $html['resultStatus'] = 'success';      

            $html['html'] = "
                <table>
                <tr>
                    <td>Nome</td>
                    <td>Senha</td>
                </tr>
            ";

            while( $row = mysql_fetch_assoc($sql) )
            {

                //aqui voce define os dados da sua table
                $html['html'] .= "
                    <tr>
                        <td>{$row['name']}</td>
                        <td>{$row['pass']}</td>
                    </tr>

                ";

            }

            $html['html'] .= "</table>";

        } 
        else
        {
            $html['resultStatus'] = 'error';        
            $html['resultMSG'] = 'Nenhum resultado';                    
        }

    }



    // output
    echo json_encode($html);


}
?>
  • Perfect guy! That’s just what I needed. Thank you so much!

  • @Marcosviniciusdossantos, done! cara just modifies the result.php file I put in the condition or TRUE, remove this, I already made the answer edit. abs

  • Oh yes, I’ve even done a test here, it’s working perfectly. It helped me a lot, thank you Rafael!

-1

I believe that with method get becomes easy...

each contact on that list is a link that goes to the same page only with an extension like this ( I am based on the url that appears in the image):

test.php? contact=contact name

<?php 

// se existir o contato na url...
if(isset($_GET['contato'])){

$contato = $_GET['contato'];

//seleciona todos os dados daquele contato
$selecionaContato = mysql_query("SELECT * FROM contato WHERE nomeContato='$contato'");
while($dadosContato = mysql_fetch_array(selecionaContato)){   
//mostre abaixo todos os dados do usuário selecionado
?>

 <p>Nome Completo: <?php echo $dadosContato['nome'];?></p>
 <p>telefone: <?php echo $dadosContato['tel'];?></p>
 <p>Endereço: <?php echo $dadosContato['endereco'];?></p>


  <?php }
  // fecha o while
  // se nao existir o contato na url mostra o texto abaixo..

   }else{ ?>


  <p>Selecione um contato no menu a esquerda</p>


  <?php } // fecha o else ?>

it is quite simple this type of method, if you need a higher security, recommend the post method

If you have not created a Slug in your table advise you to check by the id of each contact.. type this...

test.php? idContact=1

$id = $_GET['idContato'];
// force para que a variavel id seja um numero para evitar hachers
$id = (int)$id;
//seleciona todos os dados daquele contato pelo id
$selecionaContato = mysql_query("SELECT * FROM contato WHERE     idContato='$id'");

then the rest is the same...

  • Thanks for the tip Andrei! Sorry, I just forgot to specify. But, I would like to be doing this without refreshing the screen. That is, by javascript. But I’ll save this example as an alternative if I can’t do it in JS.

  • Never, never, NEVER construct queries by string interpolation (i.e. $bla inside the string). What happens if I have D'Artagnan on my contact list? (cf. here)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.