Steve
Steve

Reputation: 596

PHP loop creating duplicate database rows

I'm playing about creating a database that contains plaintext and hash values for any combination of passwords, however when they are added to the database I end up with many duplicates before it moves on to the next combination... Any ideas as to why and how to stop it?

<?php
$con=mysqli_connect("localhost","root","","test");
// Check connection
if (mysqli_connect_errno())
{
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$numberof=0;
$alphabet = array("A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z");

for($i=0; $i<count($alphabet); $i++){
    for($j=0; $j<count($alphabet); $j++){
        for($k=0; $k<count($alphabet); $k++){
            for($l=0; $l<count($alphabet); $l++){
                $final = $alphabet[$i].$alphabet[$j].$alphabet[$k];
                $hash = md5($final);

                mysqli_query($con,"INSERT INTO hashes (plain, hash) VALUES ('$final', '$hash')");
            }
        }
    }
}
echo $numberof;
?>

Upvotes: 0

Views: 158

Answers (2)

Dhaval Bharadva
Dhaval Bharadva

Reputation: 3083

just remove the last loop. i have update your code as below:

for($i=0; $i<count($alphabet); $i++){
    for($j=0; $j<count($alphabet); $j++){
        for($k=0; $k<count($alphabet); $k++){
            $final = $alphabet[$i].$alphabet[$j].$alphabet[$k];
            $hash = md5($final);
            mysqli_query($con,"INSERT INTO hashes (plain, hash) VALUES ('$final', '$hash')");           
        }
    }
}

Upvotes: 0

ಠ_ಠ
ಠ_ಠ

Reputation: 3078

You have four nested for loops, with counters $i $j $k and $l. However, your final string that you use in your query only uses $i $j and $k So you'll have about 26 duplicates. I assume you meant to append the value of $l to the end of your string?

Upvotes: 1

Related Questions