check if only one field is equal to the one entered in the input

Asked

Viewed 247 times

0

How do I check if a field of my table is equal to the one typed ? I’m trying to make a friendly URL, only I’m having trouble checking the URL if it already exists in the database, what am I doing wrong ? is only printing the message of Esta URL não está disponível even though I typed one that wasn’t in the bank

INDEX.PHP

 <!DOCTYPE html>
 <html>
 <head>
 <meta charset="utf-8">
 <script type="text/javascript" src="jquery.min.js"></script>
 <title>Bem Vindo</title>
 </head>
 <body>
 <input type="text" id="url"/>
 <div id="resultados"></div>

 <script type="text/javascript">
  $(document).ready(function(){
    $("#url").on('keyup', function(){

        var url = $("#url").val();

        $.ajax({
            url: 'buscaURL.php',
            type: 'POST',
            data: {urlParaMontar: url},
            beforeSend: function(){
                $("#resultados").html("Carregando...");
            },
            success: function(data){
                $("#resultados").html(data);
            },
            error: function(){
                $("#resultados").html("Ouve um erro ao enviar sua URL");
            }
        });//ajax
    });
});
</script>
</body>
</html>

searchURL.php

<?php 
$url = $_POST['urlParaMontar'];

$a = array('A', 'À', 'Á', 'Â', 'Ã', 'Ä', 'Å', 'Æ', 'B', 'C', 'Ç', 'D', 'E', 'È', 'É', 'Ê', 'Ë', 'F', 'G', 'H', 'I', 'Ì', 'Í', 'Î', 'Ï', 'J', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'X', 'Z', 'W', 'Y', 'Ð', 'Ñ', 'Ò', 'Ó', 'Ô', 'Õ', 'Ö', 'Ø', 'Ù', 'Ú', 'Û', 'Ü', 'Ý', 'ß', 'à', 'á', 'â', 'ã', 'ä', 'å', 'æ', 'ç', 'è', 'é', 'ê', 'ë', 'ì', 'í', 'î', 'ï', 'ñ', 'ò', 'ó', 'ô', 'õ', 'ö', 'ø', 'ù', 'ú', 'û', 'ü', 'ý', 'ÿ', 'Ā', 'ā', 'Ă', 'ă', 'Ą', 'ą', 'Ć', 'ć', 'Ĉ', 'ĉ', 'Ċ', 'ċ', 'Č', 'č', 'Ď', 'ď', 'Đ', 'đ', 'Ē', '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u', 'v', 'x', 'z', 'w', 'y', 'd', 'n', 'o', 'o', 'o', 'o', 'o', 'o', 'u', 'u', 'u', 'u', 'y', 's', 'a', 'a', 'a', 'a', 'a', 'a', 'ae', 'c', 'e', 'e', 'e', 'e', 'i', 'i', 'i', 'i', 'n', 'o', 'o', 'o', 'o', 'o', 'o', 'u', 'u', 'u', 'u', 'y', 'y', 'a', 'a', 'a', 'a', 'a', 'a', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'd', 'd', 'd', 'd', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'g', 'g', 'g', 'g', 'g', 'g', 'g', 'g', 'h', 'h', 'h', 'h', 'i', 'i', 'i', 'i', 'i', 'i', 'i', 'i', 'i', 'i', 'ij', 'ij', 'j', 'j', 'k', 'k', 'l', 'l', 'l', 'l', 'l', 'l', 'l', 'l', 'l', 'l', 'n', 'n', 'n', 'n', 'n', 'n', 'n', 'o', 'o', 'o', 'o', 'o', 'o', 'oe', 'oe', 'r', 'r', 'r', 'r', 'r', 'r', 's', 's', 's', 's', 's', 's', 's', 's', 't', 't', 't', 't', 't', 't', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'w', 'w', 'y', 'y', 'y', 'z', 'z', 'z', 'z', 'z', 'z', 's', 'f', 'o', 'o', 'u', 'u', 'a', 'a', 'i', 'i', 'o', 'o', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'a', 'a', 'ae', 'ae', 'o', 'o','e','-','-','-','-','-','-','-','-');

$urlNova = str_replace($a,$b,$url);

$conexao = new PDO('mysql:host=localhost;dbname=noticias',"root","");

    $sql = $conexao->prepare("SELECT * FROM `artigos`");
    $sql->execute();
    $fetchAll = $sql->fetchAll();

    if(isset($urlNova) && $urlNova === $urlNova){
        echo "Esta URL não está disponível";
    }else{
        echo $urlNova;
    }

?>

and in the table artigos only has the field url that has the value url-teste-do-site

  • There’s a WHERE missing?

  • where url = '$url' ? i am not passing any parameter in the URL, I have an input that type any url, if it is not in the database it shows it normally, if it is showing this error message, however it is showing the error even if the url is not in the database

  • Well eh, I find it strange not to check if it exists in the bank with WHERE.

  • the only solution was to leave the field unico no bank, but I didn’t want to do it, I wanted a nice check, if you know a solution put there friend, thank you

  • leave some examples for us, otherwise it becomes difficult, what you want is to check if some parameter of the url is equal to a field in the table would be this?

  • 1

    the code you posted doesn’t make sense as @dvd has commented, the way you posted it, it will always fall on the condition that print is not available

  • A nice check would be to see if the bank has such a URL with WHERE. From what I’m seeing, you’re doing nothing but make a simple bank consultation with "SELECT * FROM articles")

  • what’s in your articles table? and what’s in your url?

  • 1

    A cute question would be to also post HTML to avoid that we have extra work in typing the same.

  • Not to mention that if doesn’t make any sense.

  • edited the question, see if they understand better now, what I want is just to check if the input field is already registered in the database, I thought to use the where I would have to pass some parameter on url

  • 1

    Blz, I’m gonna study this case.

Show 7 more comments

3 answers

2


Taking advantage of your code I made the necessary adaptations for full operation.

$url = $_POST['urlParaMontar'];
$a = ......
$b = ......
$urlNova = str_replace($a,$b,$url);

$conexao = .....

/*********verifica se existe no banco alguma url igual a digitada*********/

    $sql = $conexao->prepare("SELECT * FROM artigos where url='$urlNova'");
    $sql->execute();

    $linha = $sql->fetch(PDO::FETCH_ASSOC);
    //se existe é colocada nessa variavel
    $urlBanco = $linha['url'];

/**************************** fim verificação ****************************/

    if(isset($url) && $urlBanco === $urlNova){
        echo "Esta URL existe no banco";
    }else{
        echo "url digitada " .$url. " Nao existe no banco "; 
    }

NOTE: making an asynchronous request and making a select each time the user type a character is not the best way. I would change the event keyup on the line

$("#url").on('keyup', function(){ from index.php to

$("#url").on('blur', function(){

or would use version 1.1 below!!

Version 1.1 :)

function isValidUrl(url){

var myVariable = url;
    if(/^[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/i.test(myVariable)) {
      return 1;
    } else {
      return -1;
    }   
}


$(document).ready(function () {

    $('input').keyup(function() {
        $th = $(this);

        if (isValidUrl($th.val())==1){

          $.ajax({
            url: 'buscaURL.php',
            type: 'POST',
            data: {urlParaMontar: $th.val()},
            beforeSend: function(){
                $("#resultados").html("Carregando...");
            },
            success: function(data){
                $("#resultados").html(data);
            },
            error: function(){
                $("#resultados").html("Ouve um erro ao enviar sua URL");
            }
         });//ajax 

      }

    });
});

The function isValidUrl checks whether the url is valid within the established standard. Only if the entered URL is valid does it execute the method $.ajax({ which allows you to send and treat the result thus avoiding running multiple selects.

If you want full validation of url since http ..... use

if(/^(http|https|ftp):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/i.test(myVariable)) {

1

I’d do it different than you: I would check the database to see if that url already exists. If the query displays a line it means it has worked, so the url already exists. Otherwise, it’s available for use. The code would look like this:

//Consulta buscando a url na base. Como não sei o nome do campo da sua tabela, só substituir url pelo campo correto
$sql = $conexao->prepare("SELECT * FROM `artigos` WHERE **url** LIKE '$urlNova'");
$sql->execute();
//Verificar se a consulta retornou algo.
$num_rows = mysql_num_rows($sql);

if($num_rows > 0) {
 echo "Esta URL não está disponível";
} else {
 echo $urlNova;
}

1

Review your query to the bank and the condition that validates the result of the query, follow an example of how I would solve this situation. remembering that there are several ways to solve this problem, in this case I advise that in the WHERE of your inquiry to the bank you do not use the LIKE, because it is a search for an exact value.

$urlNova = str_replace($a,$b,$url);

$conexao = new PDO('mysql:host=localhost;dbname=noticias',"root","");

$sql = $conexao->prepare("SELECT * FROM `artigos` WHERE url = '$urlNova'");
$sql->execute();

$resultado = $sql->fetch(PDO::FETCH_ASSOC);

if($sql->rowCount() == 0){//verifica se a urlNova está cadastrada no banco
    echo "Esta URL não está disponível";
}else{
    echo $urlNova;
    //echo $resultado['url'];
}
  • I thought to use the where I would have to pass some parameter on URL

  • You can mount your "urlNova", and compare it to the url that is stored in the database. The most practical would be to create the valid url, based on the article id or based on the article title.

Browser other questions tagged

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