1

I am trying to make a script to check if an int is already added to my database. If so, it will re-generate another random number and check again. If it doesn't exist, it'll insert into the database.

However, I am having troubles. If a number exists, it just prints out num exists, how would I re-loop it to check for another and then insert that? I have tried to use continue;, return true; and so on... Anyway, here is my code; hopefully someone can help me!

<?php
require_once("./inc/config.php");

$mynum = 1; // Note I am purposely setting this to one, so it will always turn true so the do {} while will be initiated.

echo "attempts: ---- ";

$check = $db->query("SELECT * FROM test WHERE num = $mynum")or die($db->error);

if($check->num_rows >= 1) {
    do {

        $newnum = rand(1, 5);
            $newcheck = $db->query("SELECT * FROM test WHERE num = $newnum")or die($db->error);
                if($newcheck->num_rows >= 1) {
                echo $newnum . " exists! \n";
                } else {
            $db->query("INSERT test (num) VALUES ('$newnum')")or die($db->error);
            echo "$newnum - CAN INSERT@!@!@";
            break;
        }

    } while(0);
}
?>
Constantin Groß
  • 10,719
  • 4
  • 24
  • 50
DharmeshPHP
  • 41
  • 1
  • 6

3 Answers3

1

I think the logic you're looking for is basically this:

do {
  $i = get_random_int();
} while(int_exists($i));
insert_into_db($i);

(It often helps to come up with some functions names to simplify things and understand what's really going on.)

Now just replace the pseudo functions with your code:

do {
  $i = rand(1, 5);
  $newcheck = $db->query("SELECT * FROM test WHERE num = $i")or die($db->error);
  if ($newcheck->num_rows >= 1) {
    $int_exists = true;
  } else {
    $int_exists = false;
  }
} while($int_exists);
$db->query("INSERT test (num) VALUES ('$i')") or die($db->error);

Of course, you can do a little more tweaking, by shortening...

// ...
  if ($newcheck->num_rows >= 1) {
    $int_exists = true;
  } else {
    $int_exists = false;
  }
} while($int_exists);

...to:

// ...
  $int_exists = $newcheck->num_rows >= 1;
} while($int_exists);

(The result of the >= comparison is boolean, and as you can see, you can assign this value to a variable, too, which saves you 4 lines of code.)

Also, if you want to get further ahead, try to replace your database calls with actual, meaningful functions as I did in my first example.

This way, your code will become more readable, compact and reusable. And most important of all, this way you learn more about programming.

tmh
  • 1,385
  • 2
  • 12
  • 18
0

The logic is incorrect here. Your do-while loop will get executed only once (as it's an exit-controlled loop) and will stop on the next iteration as the while(0) condition is FALSE.

Try the following instead:

while($check->num_rows >= 1) {
    $newnum = rand(1, 5);
    $newcheck = $db->query("SELECT * FROM test WHERE num = $newnum")or die($db->error);

    if ($newcheck->num_rows >= 1) {
        echo $newnum . " exists! \n";
    } else {
        $db->query("INSERT test (num) VALUES ('$newnum')") or die($db->error);
        echo "$newnum - CAN ISNERT@!@!@";
        break;
    }
}

Sidenote: As it currently stands, your query is vulnerable to SQL injection and could produce unexpected results. You should always escape user inputs. Have a look at this StackOverflow thread to learn how to prevent SQL injection.

Community
  • 1
  • 1
Amal Murali
  • 75,622
  • 18
  • 128
  • 150
0

Here is an example of some code that I threw together using some of my previously made scripts. You will notice a few changes compared to your code, but the concept should work just the same. Hope it helps.

In my example I would be pulling the database HOST,USER,PASSWORD and NAME from my included config file

require_once("./inc/config.php");

echo "attempts: ---- ";

$running = true;
while($running == true) {

//create random number from 1-5
$newnum = rand(1,5); 

//connect to database
$mysqli = new mysqli(HOST, USER, PASSWORD, NAME); 
//define our query
$sql = "SELECT * FROM `test` WHERE `num` = '".$$newnum."'"; 
//run our query
$check_res = mysqli_query($mysqli, $sql) or die(mysqli_error($mysqli));

    //check results, if num_rows >= our number exists
    if (mysqli_num_rows($check_res) >= 1){ 
    echo $newnum . " exists! \n";
}
else { //our number does not yet exists in database

    $sql = "INSERT INTO `test`(`num`) VALUES ('".$newnum."')";
    $check_res = mysqli_query($mysqli, $sql) or die(mysqli_error($mysqli));
    if ($check_res){
        echo $newnum . " - CAN ISNERT@!@!@";

        // close connection to datbase
        mysqli_close($mysqli);
    }
    else{
        echo "failed to enter into database";
        // close connection to database
        mysqli_close($mysqli); 
    }
    break;
}


}

I would also like to note that this will continue to run if all the numbers have been used, you may want to put in something to track when all numbers have been used, and cause a break to jump out of the loop.

Hope this helps!

jjonesdesign
  • 410
  • 2
  • 14