0

I send 2 variables by url:

var http = false;
http = new XMLHttpRequest();

function carrega(){

    var nome = document.getElementById('CodigoUtente').value;
    var nomes = document.getElementById('Nome').value;

    var url_="conexao4?CodigoUtente="+nome+"&Nome="+nomes;
    http.open("GET",url_,true);
    http.onreadystatechange=function(){
        if(http.readyState==4){
            var retorno = JSON.parse(http.responseText);

            document.getElementById('CodigoUtente').value = retorno.CodigoUtente;
            document.getElementById('Nome').value = retorno.Nome;
            document.getElementById('DataNasc').value = retorno.DataNasc;
            document.getElementById('Sexo').value = retorno.Sexo;
            document.getElementById('Estadocivil').value = retorno.Estadocivil;
            document.getElementById('Nacionalidade').value = retorno.Nacionalidade;
            document.getElementById('Responsavel').value = retorno.Responsavel;
            document.getElementById('Parentesco').value = retorno.Parentesco;
            document.getElementById('Contato').value = retorno.Contato;
        }
    }
    http.send(null);
}

in the connection page4 I have the php that receives the variables:

$CodigoUtente = $_GET['CodigoUtente'];
$Nome = $_GET['Nome'];

if((isset($CodigoUtente)) && (isset($Nome))){
    $query= "SELECT CodigoUtente, Nome, DataNasc, Sexo, Estadocivil, Nacionalidade, Responsavel, Parentesco, Contato FROM centrodb.PsicUtentes   WHERE (CodigoUtente = '$CodigoUtente') OR (Nome LIKE '%$Nome%')";
    $resultados = $conn->query($query);
    $json = array();
    while ($rowResultados = $resultados->fetch_assoc()) {
        $dados = array(
            'CodigoUtente' => $rowResultados['CodigoUtente'],
            'Nome' => $rowResultados['Nome'],
            'DataNasc' => $rowResultados['DataNasc'],
            'Sexo' => $rowResultados['Sexo'],
            'Estadocivil' => $rowResultados['Estadocivil'],
            'Nacionalidade' => $rowResultados['Nacionalidade'],
            'Responsavel' => $rowResultados['Responsavel'],
            'Parentesco' => $rowResultados['Parentesco'],
            'Contato' => $rowResultados['Contato']
        );
        $json = $dados;
    }
    echo json_encode($json);
}

The problem is that they only work if you fill in the two inputs and intended that they return the data from the database only when filling one of them.

Curious_Mind was saying this way?

    $where_caluse = array();

if(isset($_GET['CodigoUtente'])){
  $where_caluse[] = "CodigoUtente = '".$_GET['CodigoUtente']."'";    
}

if(isset($_GET['Nome'])){
  $where_caluse[] =  "Nome = '".$_GET['Nome']."'";  
}

$where = array_filter($where_caluse);

$query = "SELECT CodigoUtente, Nome, DataNasc, Sexo, Estadocivil, Nacionalidade, Responsavel, Parentesco, Contato FROM centrodb.PsicUtentes";

$resultados = $conn->query($query);

if(!empty($where)){

$final_where = count($where) > 1 ? implode(' OR ', $where) : end($where);
$query = "$query WHERE ". $final_where;

$json = array();

while ($rowResultados = $resultados->fetch_assoc()) {

  $dados = array(
     'CodigoUtente' => $rowResultados['CodigoUtente'],
     'Nome' => $rowResultados['Nome'],
     'DataNasc' => $rowResultados['DataNasc'],
     'Sexo' => $rowResultados['Sexo'],
     'Estadocivil' => $rowResultados['Estadocivil'],
     'Nacionalidade' => $rowResultados['Nacionalidade'],
     'Responsavel' => $rowResultados['Responsavel'],
     'Parentesco' => $rowResultados['Parentesco'],
     'Contato' => $rowResultados['Contato']
    );
      $json = $dados;
}
echo json_encode($json);

}   

I tried to apply the form it said, but it is not working, it gives 500 error when I send the values ​​of the variables. Can you help fix the problem? I have a form to be populated with these values

Bruno
  • 801
  • 5
  • 11
  • 1
    Completely different note: do not use raw SQL unless you want your database destroyed by someone casually dropping some quotes and semicolons in your variables. And if you're using mysql, use the msqli library. – Mike 'Pomax' Kamermans Jan 28 '19 at 17:08
  • I think you can get your answer here : https://stackoverflow.com/a/13102500/6718738 – Mozart Jan 28 '19 at 17:15
  • @Mozart Al Khateeb, my problem is npo treatment of the `$query` variable to check the parameters. The question that put up help? – Bruno Jan 28 '19 at 17:22
  • @Bruno i'm not an expert with php and mysql and I did not exactly understand where your problem is, please explain more, and i have noticed this in your query Nome = '%$Nome%' try removing the %, We usually use this in sqlserver with like and not = .. – Mozart Jan 28 '19 at 17:27
  • @Mozart Al Khateeb My problem is that I want to search for the variables without depending on each other and send the value of the variables through the url – Bruno Jan 28 '19 at 17:30
  • @Bruno so is your problem on the server side ? (php) or client side with javascript, have you tried testing the get method with an app such as postman ? another thing i noticed is this if((isset($CodigoUtente)) && (isset($Nome))) shouldn't it be if((isset($CodigoUtente)) || (isset($Nome))) ? try testing the get method alone so you can figure wich side has the problem – Mozart Jan 28 '19 at 17:34
  • @Mozart Al Khateeb If the get method with only one variable works correctly, the problem is when I place the second variable. The problem is in the two conditions that I put in the query. If you fill in the two variables returns the correct data, but if you fill only one of them always returns the last row of the table – Bruno Jan 28 '19 at 17:38
  • alright then it is a data querying issue I think, does this happen when you fill only this CodigoUtente or that Nome ? – Mozart Jan 28 '19 at 17:41
  • @Mozart Al Khateeb If you fill in the codigout and name returns the correct data, if you fill in only the codigout or only the name, always return the last line of the database – Bruno Jan 28 '19 at 17:44
  • @Bruno can you show us a sample of your data ? since that might be correct if your query meets the where condition of the last record. – Mozart Jan 28 '19 at 17:46
  • @Mozart Al Khateeb The data is already in the database table, the idea is to query the table by user code or name and return the existing data in the table in a form with those fields all. – Bruno Jan 28 '19 at 17:55
  • http://www.sqlfiddle.com/#!9/7e0f1/1 this is the expected result of your query. – Mozart Jan 28 '19 at 17:59
  • @Mozart Al Khateeb [link](http://www.sqlfiddle.com/#!9/7e0f1/2) but what he intended was to fill one of them and leave the other empty and return the correct data and not always return the last line of the table. I put an example of the link I send – Bruno Jan 28 '19 at 18:05
  • @Bruno sorry but why would you need this ? select * from tasks where title = ''; select * from tasks where name = ''; – Mozart Jan 28 '19 at 18:10
  • @Mozart Al Khateeb yes, I have already thought about doing two queries for each of the conditions, but then I do not know how to return the result of each query within the while, can it help? – Bruno Jan 28 '19 at 18:12
  • @Bruno i posted an answer could you please check it ? of course you will not echo the $query. – Mozart Jan 28 '19 at 18:20

2 Answers2

1
$where = " where ";
$CodigoUtente = 'a';
$Nome = '';
if($CodigoUtente != '' && $Nome != '')
{
  $where .= "CodigoUtente = '$CodigoUtente' OR Nome = '$Nome';"; 
}else if ($CodigoUtente != ''){
  $where .= "CodigoUtente = '$CodigoUtente';"; 
}else{
  $where .= " Nome = '$Nome';"; 
}

$query = "SELECT CodigoUtente, Nome, DataNasc, Sexo, Estadocivil, Nacionalidade, Responsavel, Parentesco, Contato FROM centrodb.PsicUtentes".$where;

echo $query;
Mozart
  • 2,117
  • 2
  • 20
  • 38
  • so it works and returns the correct data. But it still has a problem, for example it returns the codigoutente 255, if it re-searches another user the codigoutente has to be greater than 255 to return the data of the new user that I am searching, if it is smaller, for example the 151 maintains the same user, can you help? – Bruno Jan 29 '19 at 08:55
  • @Bruno I think you need to refresh your skills with some Sql querying examples: https://www.w3schools.com/sql/sql_and_or.asp ; your questions are not technical issues rather than misunderstanding how conditionals work (if-else) and how to select data from sql. you need to make some practice so you can solve your own problems later. – Mozart Jan 29 '19 at 12:09
  • I already solved it with this function and creating a clean button. I do not know if it will be the best practice, but it works. `function recarregarSemParametro(){ var url = window.location.href; if (url.indexOf("?") > -1 ){ url = url.substr(0,url.indexOf("?")).toLowerCase(); } window.location = url; }` and button `` – Bruno Jan 29 '19 at 12:45
  • The idea is to clear the parameters before sending the new values. – Bruno Jan 29 '19 at 12:45
0

You can try like this way before making you sql query. This will help you to handle WHERE with OR condition, without OR condition and without any condition at all.

$where = array();
$_GET['CodigoUtente'] = 'Sany';
$_GET['Nome'] = 'Bruno';

if(isset($_GET['CodigoUtente'])){
  $where[] = "CodigoUtente = '".$_GET['CodigoUtente']."'";    
}

if(isset($_GET['Nome'])){
  $where[] =  "Nome = '".$_GET['Nome']."'";  
}


$sql = "SELECT CodigoUtente, Nome, DataNasc, Sexo, Estadocivil, Nacionalidade, Responsavel, Parentesco, Contato FROM centrodb.PsicUtentes";

if(!empty($where)){
    $final_where = count($where) > 1 ? implode(' OR ', $where) : end($where);
    $sql = "$sql WHERE ". $final_where;
}

echo $sql; 

DEMO: https://3v4l.org/phZGW

A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103
  • I edited the question with the solution that presented, but it is giving error, can verify? – Bruno Jan 28 '19 at 17:50
  • you missed `$resultados = $conn->query($query);` line before `while` loop – A l w a y s S u n n y Jan 28 '19 at 17:55
  • but I had the same problem, if I fill only one of the variables returns the last row of the table and not the data of the user that I search – Bruno Jan 28 '19 at 17:58
  • corrected errors that had both the line that said it was missing and also removed the where inside the query, but still does not work, always returns the last line when only one of the variables – Bruno Jan 28 '19 at 18:08
  • But it shouldn't, did you check the demo with one or two variable set? – A l w a y s S u n n y Jan 29 '19 at 01:15