How to traverse all the records in the database table?


Good afternoon, guys! I'm starting in PHP and I already had a problem. It is as follows:

I need to go through all records in the bank table so that I can validate if that value already exists. I'm using Codeigniter and did the following plus or minus this:

$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";

In this way you are only validating the first record of the table, that is, it only takes the "value" of the first row and shows "Value already existing". Home But if the value sought is from the second record, it continues to register. Home Thank you in advance!

asked by anonymous 05.10.2015 / 19:38

1 answer


It seems simpler to check if the value already exists in the database than using php for this. Add a WHERE by comparing the desired value, if it has a return it does not insert, if the return is false it makes an insert.

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

   //faz o insert nesse bloco
    echo 'esse valor já existe, escolha outro';
05.10.2015 / 20:25