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";
}
The code looks right. The comparison should be
$registro >= 1
.– rray
@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.– Guilherme Nascimento
@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
@Bacco Boa!! is worth questioning directly the AP :)
– Guilherme Nascimento
@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
– rray
That’s the case here: How not to repeat value in Mysql - complement: https://answall.com/a/34075/70
– Bacco