(PHP) What variable do I put inside mysqli_affected_rows

Asked

Viewed 525 times

0

  <?php
$conexao = mysqli_connect("localhost","root","","banco");

$nome = isset($_REQUEST['nome'])?$_REQUEST['nome']:"";
$telefone = isset($_REQUEST['telefone'])?$_REQUEST['telefone']:"";
$sql = "insert into tb_banco(nome, telefone)values('$nome','$telefone')";
$salvar = mysqli_query($conexao,$sql);

$registro = mysqli_affected_rows($salvar);

if($registro==0){
    echo "telefone já cadastrado,use outro";
}else{
    echo "Cadastro realizado com sucesso";
}

?>
  • 1

    The code looks right. The comparison should be $registro >= 1.

  • 1

    @rray but the code is wrong yes, INSERT will not check if there are other phones, on mysqli_affected_rows will only return how many inserted, will always be 0 or 1, because has only one Insert, 0 for chance can not insert.

  • 3

    @Guilhermebirth if she has a Unique Dice, the code is perfect - it’s even the right way to do it, and not the classic wrong code that everyone uses "select to see if it exists, then Insert" (minus the $save problem, where it should be $connected) - Eventually she could check for error 1062 instead of checking affected, just in case of differentiating other errors.

  • @Bacco Boa!! is worth questioning directly the AP :)

  • @Guilhermenascimento well-noted, Insert can even do this If your phone has a unique index. I clung to the title of the question no longer any other text explained the xD problem

  • 2

    That’s the case here: How not to repeat value in Mysql - complement: https://answall.com/a/34075/70

Show 1 more comment

1 answer

4


According to the PHP documentation on http://php.net/manual/en/function.mysql-affected-rows.php:

int mysql_affected_rows ([ resource $link_identifier = NULL ] )

It is a function that returns an integer value containing "the number of lines affected by the last INSERT, UPDATE, REPLACE or DELETE associated with link_identifier."

link_identifier: in turn is the connection to the mysql database. This argument is not required when you only have a connection to Mysql database.

Bringing this to your example would be:

$conexao = mysqli_connect("localhost","root","","banco");

$nome = isset($_REQUEST['nome'])?$_REQUEST['nome']:"";
$telefone = isset($_REQUEST['telefone'])?$_REQUEST['telefone']:"";
$sql = "insert into tb_banco(nome, telefone)values('$nome','$telefone')";
$salvar = mysqli_query($conexao,$sql);

$registro = mysqli_affected_rows($conexao);

if($registro==0){
    echo "telefone já cadastrado,use outro";
}else{
    echo "Cadastro realizado com sucesso";
}

Browser other questions tagged

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