Check if there is a record in the table

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, select deposit.

public function verificar($name){
$string = (string) $name;
$data = $conexao->query('SELECT * FROM slug);
}
    
asked by anonymous 24.07.2017 / 15:17

2 answers

1

You 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!";
     }
}

You need to improve query , but it's a path.

    
24.07.2017 / 15:30
1

Simple friend, you will use the Where of mysql clause.

I'll give you an example using a code to fetch 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;
    }

This select reads: "Give me back all users who have this email" .. and my function receives the email variable as a parameter. If at the end of the function returns 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 have helped.

    
24.07.2017 / 15:26