How to go through all the records in the database table?

Asked

Viewed 1,350 times

2

Good afternoon, you guys! I’m starting in PHP and I already have a little problem. Is the following:

I need to go through all the records in the bank table, so I can validate if such a value already exists. I’m using Codeigniter and I did the following sort of thing:

$sql = $this->db->query("SELECT * FROM tabela")->result;

foreach ($sql as $resultado) {
if ($resultado->valor == $this->input->post("valor")) {
    echo "Valor já existente";
} else {
    echo "Cadastro OK";
}
}

This way it is validating only the first record of the table, that is, it only takes the "value" of the first line and shows "Existing value".
But if the value sought is from the second record, it continues to register.
Grateful from now on!

  • In theory your code is right. I think it would be simpler to make this comparison in sql than in php, basically you pass the 'value' in Where if there is no new registration, if there is a blocking the registration. You could put the real code?

1 answer

1

It seems simpler to check if the value already exists in the database than to use php for this. Add a WHERE comparing the desired value, if you have any return does not perform an Insert, if the return is false makes an Insert.

$sql = $this->db->query("SELECT * FROM tabela WHERE campos = 'valor'")->result;

if(!$sql){
   //faz o insert nesse bloco
}else{
    echo 'esse valor já existe, escolha outro';
}

Browser other questions tagged

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