Check if there is record in the table

Asked

Viewed 2,006 times

2

I’m trying to check if there is a record in the mysql table using php,

I have the table "Slug", and in this table I have "id" and "slug_name", as I do to check if there is already a name in this table, for example: noticia_sobre_o_tempo. how do I see if this name already exists, in the table, after the select.

public function verificar($name){
$string = (string) $name;
$data = $conexao->query('SELECT * FROM slug);
}
  • I changed my answer, notice that the quotation mark is missing in your query....

2 answers

1

Simple friend, you will wear the cloister Where mysql.

Let me give you an example using a code to find a user (with Pdo).

$hostDB = "mysql:host=localhost;dbname=opentagv3";
$usuarioServidor = "root";
$senhaServidor = "123456";

try {
  $conexao = new PDO($hostDB, $usuarioServidor, $senhaServidor);
  $conexao->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

} catch (PDOException $erroNaConexao) {
  echo $erroNaConexao->getMessage();
  echo "<br>"."Erro ao Conectar com o Banco de Dados";
}

function buscaUsuarioPorEmail($email){
        $select = $this->conexao->prepare("SELECT * FROM usuarios WHERE email='$email'");
        $select->setFetchMode(PDO::FETCH_ASSOC);
        $select->execute();
        $usuario = $select->fetch();
        return $usuario;
    }

That one select says so: "Return me all users who have this email".. and my function receives the variable email as a parameter. If at the end of the function return null, the user with that email does not exist.

In your case it would be..

public function verificar($name){
$select = $this->conexao->prepare("SELECT * FROM slug where slug_name='$name'");
        $select->setFetchMode(PDO::FETCH_ASSOC);
        $select->execute();
        $slug= $select->fetch();
        return $slug;
}

I hope I’ve helped.

  • But to see if it does I wouldn’t have to do a line count ?

  • There are other ways to check if it contains a record, in this case I am using a variable to save the result, and if it is null it is because it does not exist, but could use the Row method and do an if to check if the affected lines were 0

  • I understood, in my case and the following, I need to return false or true, for me to receive via ajax, for when I type the name, show me in real time if it exists or not.

  • Only do an if on the variable that receives fetch(), and return true or false

1


Can do :

public function verificar($name)
{    $string = (string) $name;
     $data = $conexao->query('SELECT * FROM slug');
     $linha = mysqli_fetch_assoc($data);
     if($linha['slug_name'] != $string)
     {      echo "Não existe";
     }else
     {   echo "Já existe!";
     }
}

Needs to improve the query, but it’s a way.

  • What is this $password variable ?

Browser other questions tagged

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