onceuponaduck
onceuponaduck

Reputation: 75

SQL insert to MySQL doesn't work

I'm currently trying to insert username, pw to a DB, and check if the username already exists.

The problem is that the SQL (select) syntax doesn't work, nor does the (insert). I've checked around for a couple of hours in forums and Stackoverflow, and my current code is the following.

What might be the problem?

Thanks, Jimmie.

 <?php
    $servername = "localhost";
    $username = "name";
    $password = "pw";
    $dbname = "dbaname";

    $mysqli = new mysqli($servername, $username, $password, $dbname);

    if ((isset ($_POST["identity"])) && (isset ($_POST["pin"])) && (isset ($_POST["token"])))
    {

      $identity = htmlspecialchars($_POST['identity'], ENT_QUOTES, "ISO-8859-1");
      $pin = htmlspecialchars($_POST['pin'], ENT_QUOTES, "ISO-8859-1");
      $token = htmlspecialchars($_POST['token'], ENT_QUOTES, "ISO-8859-1");

      echo "$identity";
      if($token == "xyz13D;A##:!#")
      {


        $result = $mysqli->query("SELECT `identity` FROM Users WHERE `identity` = '" . $identity . "'");
        if($result->num_rows == 0)
        {
           echo "successCreat";

              // Perform queries
              mysqli_query($mysqli,"SELECT * FROM Users");

              mysqli_query($mysqli,"INSERT INTO Users (identity,pin,userActivity, identityCreated) VALUES ('$identity', '$pin',1,now())");
        }
        else
        {
          echo "failureCreate";
        }

      }
      else
      {
        echo"Wrong Key";
      }
    }
    $mysqli->close();
    ?>

Upvotes: 0

Views: 172

Answers (1)

Isaiah
Isaiah

Reputation: 680

Assuming that identity is a primary key, then you can check the error flags after executing an INSERT query to see if an error occurred.

mysqli_query( $mysqli, "INSERT INTO ... " ); //< ... Represents query
if (mysqli_error( $mysqli )) {
  echo "Failure";
}
else {
  echo "Success";
}

Also, you should properly escape input as stated in the comments. In addition, you should check whether or not the connection attempt was successful using mysqli_connect_error.

Finally, there might be an issue in your SQL suntax which mysqli_error will also catch. A last possibility is that the POST data isn't being set properly and the code is being ignored completely.

Upvotes: 1

Related Questions