How to make a query using variables with PHP

Asked

Viewed 467 times

0

I am trying to make the following query in the database through PHP:

SELECT * FROM nwpedidos WHERE `nomeUsuario` = 'Nome'

However, the 'Name' varies according to who makes the query, for this I pass a variable via javascript. The problem is that the query does not return anything if I use variable as in the example below, but if I use the full command as in the example above, everything works normally.

<script>
 var a = getName();
 function getName(){
    var b = document.getElementById("LoginName1").innerText;
    var res = b.split(":");
    return res[1].trim();
 }
 </script>
<?php
require_once("connect.php"); //conectar no banco
$var = "<script>document.write(a);</script>"; //pegar o conteudo da variavel JS
$sql = "SELECT * FROM `nwpedidos` WHERE `nomeUsuario` = '" . $var . "'"; //consulta no banco (que não retorna nada)
$resultado = $MySQLi->query($sql) OR trigger_error($MySQLi->error, E_USER_ERROR);
while ($dado = $resultado->fetch_object()) {
?>
  • 2

    var_dump($var) face; and ve put here the result I believe the information inside the $var that is incorrect so it does not return anything!

  • Why not save user name in session?

  • var_dump had already tested, at first it’s right. 'string(35)'

  • @Viniciusdejesus with cookies for example?

  • @Gabrielsarates using Sessions, as you take the user name and save in var a?

  • @Viniciusdejesus with javascript, the user is written in a span with Loginname1 ID.

Show 1 more comment

2 answers

1


Example with page reload.

Let’s assume you’re in the index.php ok file.

1°) Part index.php file (html), button creation (Update)

<input type="button" id="submitUser" value="Atualizar" style="cursor: pointer;">

2º) File index.php parte (js)

//Criando obj user
user = new Object();

//Aaproveitando sua função...
//Função para obter o nome do usuário logado
function getName(){
    var b = document.getElementById("LoginName1").innerText;
    var res = b.split(":");
    return res[1].trim();
}

//Espera meio segundo para garantir o carregamento... DOM
setTimeout(() => {
    //Atribuindo o nome do usuário
    user.name = getName();

    //Cria url para o mesmo arquivo (index.php) passando parâmetro usuario_name
    var url = "location.href='index.php?user_name="+user.name;    
    
    //Localiza o botão que vai submeter
    var submitUser = document.getElementById('submitUser');

    //Adiciona ao botão o url passando o usuário na ação do click
    submitUser.setAttribute("onclick", url)    
}, 500);

3°) index.php part (php)

<?php
/*Recebendo o user_name pela url com ($_GET)
Só faz a consulta se existir o user_name na url.*/
if (isset($_GET['user_name']))
{   
    /*Atribuindo o usuário recebido por ($_GET) a váriavel ($userName)*/
    $userName = $_GET['user_name'];

    /*Conectar no banco*/
    require_once("connect.php");

    /*Consulta no banco*/
    $sql = "SELECT * FROM nwpedidos WHERE nomeUsuario = '$userName' "; 
    $resultado = $MySQLi->query($sql) OR trigger_error($MySQLi->error, E_USER_ERROR);
    while ($dado = $resultado->fetch_object()) {
} else {
    /*Caso o usuário não seja passado na url, criar um alert*/
    echo "<script>alert('Erro: Usuário não detectado.');</script>"
}
?>

If you want to not reload the page, you can use Ajax...

1

Buddy, I don’t know how you’re getting the value of LoginName1.

But I suppose you have this value somewhere on your page (either via Session or database)

And for using innerText, may be in some text element, <label>, <span>, etc...

The way you’re doing it, the variable $var, is empty.

I then reproduced your example, so that you have a sense of how to pass a value to the variable $var.

<html>
<head>
    <title>Teste Query</title>
</head>
<meta charset="utf-8">
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<body>
    <form method="POST" action="#"> 
        <label>Login Name</label>
        <input type="text" id="login-nome-input" value="usuario:gustavo">
	   <button type="button" id="btn-pesquisar"  >Pesquisar</button>
	   <p>

	   <span id="login-nome">usuario:frederico</span>
           <br>    		
		
	   <br>
	   <label id="resultado"></label>
    </form>     
</body>

<script>	
var nome = getName();
	
function getName(){
   var b = document.getElementById('login-nome').innerText;		
   var res = b.split(':');
   var texto = 'RESULTADO DA QUERY: '
   return texto + res[1].trim();
}
	
function getNameInput(){
   var b = document.getElementById('login-nome-input').value;		
   var res = b.split(":");
   return res[1].trim();		
}
	
 $('#btn-pesquisar').click(function() {
   var r = getNameInput();
   $('#resultado').text(r);
 });
</script>

<?php
   $var = "<script>document.writeln(nome);</script>";
   echo $var;
   require_once("connect.php"); //conectar no banco
   $sql = "SELECT * FROM `nwpedidos` WHERE `nomeUsuario` = '" . $var . "'";
   // continua o codigo

?>

  • Thanks for the reply Wagner, I tried your method but the query does not return anything. I used 'echo $sql' to see how the query looked and a space appeared after the variable, I tried to use a Trim in the variable $var but still the space continues. I switched writeln for just write in $var and the space is gone, but still the query returns nothing

  • If you can send a more complete code, it will help, just so I know how Voce is receiving the value Loginname1; update the question in more detail

  • Loginname1 is a span. But I managed to solve the problem using Session itself, thank you!

  • 1

    @Gabrielsarates, thanks.. If my answer was helpful in anything, please accept it!! T+

Browser other questions tagged

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