0

I am creating a verification code system, where a user receives an email with a code, they go to my website, input it, and if there code matches a code in the database table "verificationcodes", then they are redirected to another url. However so far, every code I input comes out as testsite.php?code=not matching. What am I doing wrong?

<?php 

if (isset($_POST['code-submit'])) {

require 'notseendatabasehandler.php';

$code = $_POST['code'];

//Checking for empty fields
if (empty($code)) {
  header("Location: testsite1.php?error=emptyfields");
  exit();
}

else {
  $sql = "SELECT codeNumber FROM verificationcodes;";
  $result = mysqli_query($conn, $sql);

  if ($result == $code) {
    header("Location: testsite2.php?code=success");
    exit();
  }

  else {
    header("Location:  testsite1.php?code=notmatching");
    exit();
  }
}
}

//Sending the user backwards if they entered incorrectly 
else {
  header("Location: homepage.php");
  exit(); 
}
  • Have you made sure that `$result` or `$code` contains what it should? – brombeer Apr 11 '20 at 07:57
  • `mysqli_query` just runs the query. You then need to fetch the result using something like `$row = mysqli_fetch_assoc($result);` and then compare `$row['codeNumber']` with `$code`. Also you need to add a `WHERE` clause to your query, and ideally you should change to prepared statements to avoid SQL injection. See https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php?noredirect=1&lq=1 – Nick Apr 11 '20 at 08:10

1 Answers1

-1

You need to change your code as below:

$conn->prepare("SELECT codeNumber FROM verificationcodes WHERE codeNumber= ?");

If you get the result in the above query then it means that the code is exist in the database and you can redirect to the success.

What you are currently doing is fetching all the codeNumber from the table and without looping through them you are comparing post data which will not work ever.

Or else get all the data as you are doing and do foreach loop and compare all the value with the post data.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Sarvil Ajwaliya
  • 233
  • 1
  • 8
  • 1
    please read https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php and use **prepared stetemens** for your answers with parameters – nbk Apr 11 '20 at 08:07