check if only one field is the same as the input field

1

How do I check if a field in my table is the same as typed? I'm trying to make a friendly URL, but 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 if I type one that is not in the database

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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 '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 the artigos table only has the url field that has the value url-teste-do-site

    
asked by anonymous 01.05.2018 / 04:26

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 doing a select every time the user types a character is not the best way. I would change the event keyup on line

     

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

     

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

     

or 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 isValidUrl function checks whether the url is valid within the established pattern. Only if the URL entered is valid, it executes the $.ajax({ method that allows you to send and treat the result, thus avoiding multiple selects.

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

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

I would make it different from you: Verify in the bank if that url already exists. If the query presents some line it means that it has resulted, therefore the url already exists. Otherwise, it is available for use. The code looks 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;
}
    
01.05.2018 / 05:12
1

Review your query to the bank and the condition that validates the query result, here's an example of how I would resolve this situation. remembering that there are several ways to solve this problem, in this case I advise that in WHERE of your query to the bank you do not use 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'];
}
    
01.05.2018 / 05:36