hey i have this code that always evaluates to true but it should only in the case of there being a value in the database i have selected, maybe im doing this wrong or maybe its something else but i cant seem to figure out the problem :( any assistence is greatly appreciated.

//submission code, inserting data into mysql database

$mySqlDate = date('Y-m-d');
$mySqlTime = date("g:i a");

if(isset($_GET['add']))
{
    $newnum = $_GET['newnum'];
    $firstname = $_GET['firstname'];
    $lastname = $_GET['lastname'];
}

if(strlen($newnum) == $min_length)
{
    $newnum = mysqli_real_escape_string($con, $_GET['newnum']);
    $firstname = mysqli_real_escape_string($con, $_GET['firstname']);
    $lastname = mysqli_real_escape_string($con, $_GET['lastname']);

    $check = mysqli_query($con, "SELECT count(*) FROM usernumdata WHERE numb = '".$newnum."'") or die();
    $row = mysqli_fetch_row($check);

    if ($row[0] > 0)
    {
        $sql="INSERT INTO usernumdata (numb) VALUES ('".$newnum."')";

        if (!mysqli_query($con,$sql)) {
            die('Error: ' . mysqli_error($con));
        }   
        echo "<div style='text-align: center'> <font size='6' color='green'>Successfully Added New Number</font> <div>";
    }
    else
    {
        echo "<div style='text-align: center'> <font size='6' color='red'>Number Already Exists In Do Not Call List</font> <div>";
    }
    /*
    $sql="INSERT INTO usernumdata (numb, firstname, lastname, date, time) VALUES ('".$newnum."','".$firstname."','".$lastname."','".$mySqlDate."','".$mySqlTime."')";

    if (!mysqli_query($con,$sql)) {
      die('Error: ' . mysqli_error($con));
    }
    echo "<div style='position:fixed; bottom:65; left:37%'> <font size='6' color='green'>Successfully Added New Entry</font> <div>";
    */
}

else{
    $length = "Remember Phone Number Must be ".$min_length. " Digits Long";
    echo "<div style='position:fixed; bottom:50; left:31%;'> <font size='6' color='blue'>".$length."</font> <div>";
}

as you can see from the code above im trying to set it up to do a double test which is probably bad coding pratice but i needs to output different messages in case of either, and what i was trying to do was see if the value was in the database already before inserting a new one but for some reason it always evaluates to true? help

Dani AI

Generated

Quick diagnosis and what went wrong: the original snippet inserted when the SELECT returned a positive count (meaning the number already existed), so the logic was effectively inverted — caught that. Two other important issues worth fixing while here: checking-then-inserting can still fail under concurrent requests (race condition), and using raw GET values plus manual escaping is fragile. A reliable approach is to enforce uniqueness at the database level and use prepared statements.

Safer, more robust pattern (atomic insert + handle duplicate): add a UNIQUE index on numb, then try the INSERT and detect duplicate-key errors instead of relying only on a prior SELECT. That avoids races and gives a single clear pathway for feedback. Example (PDO) showing the idea:

try {
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $stmt = $pdo->prepare('INSERT INTO usernumdata (numb, firstname, lastname) VALUES (:n, :f, :l)');
    $stmt->execute([':n' => $newnum, ':f' => $firstname, ':l' => $lastname]);

    // report success
} catch (PDOException $e) {
    if ($e->getCode() === '23000') {
        // report "already exists"
    } else {
        throw $e; // surface unexpected DB error for logging
    }
}

If a pre-check is preferred for clearer branching, use a prepared SELECT 1 FROM usernumdata WHERE numb = ? LIMIT 1 (faster than COUNT) and only INSERT when no row is returned — but still keep a UNIQUE constraint as a safety net.

Troubleshooting checklist specific to this thread: confirm $min_length is defined and matched against cleaned input (strip non-digits and then check length); prefer POST for writes; use prepared statements (mysqli_stmt or PDO) instead of manual escaping; and avoid swallowing errors with empty die() calls. Credit to for the logical fix — combining that with a UNIQUE index plus the insert-then-handle approach is the safest, most scalable solution.

Recommended Answers

All 4 Replies

that looks like it could work but my question is how would you use the if statement to run a check and give feedback to the user to let them know whther or not the number is there, also can you give an example cause this looks a little complicated, sorry im kind of new to the whole php/html/mysql thing so simple explanations are appreciated, thanks.

I changed your if condition at line 22 , if row count == 0 then means record does not exists with number, so show insert when $row[0]==0 , otherwise show "already exits" message

   if ($row[0] == 0)

Thank you so much urtrivedi, this is exactly what i needed. I bow to your wisdom cause i still dont fully understand but i am reading more into it as well as something on creating a login page so i will go from there. Thanks again for all the help you gave me. it was very much appreciated

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.