简体   繁体   中英

I am getting weird output

So, I am trying to retrieve data from my mysql database after a user registers or logins. The thing is that it somehow retrieves the letter "u" and that's weird, because there is no place that contains the letter "u".

This is the result I am getting as of now https://imgur.com/t3XBrPN

index.php(where user registers or logs in)

<?php include('server.php') ?>


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">

  <title>PwettyKittyPincesa</title>

  <link href="./style.css" type="text/css" rel="stylesheet" />

  <script>
      function start(){
        closeForm();
        closeRegForm();
      }

      function openForm() {
        document.getElementById("myForm").style.display = "block";
        closeRegForm();
      }

      function closeForm() {
        document.getElementById("myForm").style.display = "none";
      }

      function openRegForm() {
        document.getElementById("myRegForm").style.display = "block";
        closeForm();
      }

      function closeRegForm() {
        document.getElementById("myRegForm").style.display = "none";
      }
      </script>

</head>
<body onload="start()">
  <nav>
      <button class="button" type="submit" onclick="openForm()">Влез</button>
      <button class="buttonReg" type="submit" onclick="openRegForm()">Регистрирай се</button>
      <img src="Logo4.png" class="Logo" alt="Logo">
  </nav>

  <div class="form-popupRegister" id="myRegForm">
    <form method="post" action="server.php" class="form-containerReg">

        <h1>Регистрирация</h1>

        <label for="username"><b>Име</b></label>
        <input type="text" name="username" placeholder="Въведете името на лейдито" value="<?php echo $username; ?>">


        <label for="email"><b>Е-майл</b></label>
        <input type="email" name="email" placeholder="Въведете e-mail" value="<?php echo $email; ?>">


        <label for="password_1"><b>Парола</b></label>
        <input type="password" placeholder="Въведете парола" name="password_1">


        <label for="password_2"><b>Повторете Парола</b></label>
        <input type="password" placeholder="Въведете парола повторно" name="password_2">


        <button type="submit" class="btnReg" name="reg_user">Register</button>
        <button type="button" class="btn-cancelReg" onclick="closeRegForm()">Close</button>
    </form>
</div>

  <div class="form-popup" id="myForm">
    <form method="post" action="server.php" class="form-container">

        <h1>Влизане</h1>

            <label for="username"><b>Име</b></label>
            <input type="text" name="username" value="<?php echo $username; ?>">

            <label for="password"><b>Парола</b></label>
            <input type="password" name="password">

            <button type="submit" class="btn" name="login_user">Login</button>
            <button type="button" class="btn-cancel" onclick="closeForm()">Close</button>
    </form>
  </div>
</body>
</html>

index2.php(where the data should be output)

<?php include('server.php') ?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">

  <title>PwettyKittyPincesa</title>

  <link href="./style.css" type="text/css" rel="stylesheet" />

  <script>
    function getUserStats(){
        <?php
            $queryThree = "SELECT * FROM `register` WHERE ID='$idQuery' ";
            $userStats = mysqli_query($db,$queryThree);
            $userStatsTwo = mysqli_fetch_assoc($userStats);
        ?>
    }
  </script>
</head>
<body onload="getUserStats()">
    <div class="navWrapper">
        <div class="statistics">
            <div class="profilePicture" name="profilePicture">
                <label class="profilePictureLabel" for="profilePicture"><b><?php echo userStatsTwo['username']; ?></b></label>
            </div>

            <div class="money" name="money">
                <label class="rubyLabel" for="ruby"><b><?php echo userStatsTwo['money']; ?></b></label>
            </div>

            <div class="diamond" name="diamond">
                <label class="diamondLabel" for="diamond"><b><?php echo userStatsTwo['diamonds']; ?></b></label>
            </div>

            <div class="ruby" name="ruby">
                <label class="rubyLabel" for="ruby"><b><?php echo userStatsTwo['ruby']; ?></b></label>
            </div>

            <div class="level" name="level">
                <label class="levelLabel" for="level"><b>Level:<?php echo userStatsTwo['level']; ?></b></label>
            </div>
        </div>
    </div>
</body>
</html>

server.php(where the data is being processed)

<?php
session_start();

// initializing variables
$username = "";
$email    = "";
$idQuery = "";
$errors = array(); 


// connect to the database
$db = mysqli_connect('localhost', 'id9159890_uregisterdb', 'censored', 'id9159890_registerdb');

// REGISTER USER
if (isset($_POST['reg_user'])) {
  // receive all input values from the form
  $username = mysqli_real_escape_string($db, $_POST['username']);
  $email = mysqli_real_escape_string($db, $_POST['email']);
  $password_1 = mysqli_real_escape_string($db, $_POST['password_1']);
  $password_2 = mysqli_real_escape_string($db, $_POST['password_2']);

  // form validation: ensure that the form is correctly filled ...
  // by adding (array_push()) corresponding error unto $errors array
  if (empty($username)) { array_push($errors, "Username is required"); }
  if (empty($email)) { array_push($errors, "Email is required"); }
  if (empty($password_1)) { array_push($errors, "Password is required"); }
  if ($password_1 != $password_2) {
    array_push($errors, "The two passwords do not match");
  }

  // first check the database to make sure 
  // a user does not already exist with the same username and/or email
  $user_check_query = "SELECT * FROM `register` WHERE username='$username' OR email='$email' LIMIT 1";
  $result = mysqli_query($db, $user_check_query);
  $user = mysqli_fetch_assoc($result);

  if ($user) { // if user exists
    if ($user['username'] === $username) {
      array_push($errors, "Username already exists");
    }

    if ($user['email'] === $email) {
      array_push($errors, "email already exists");
    }
  }

  // Finally, register user if there are no errors in the form
  if (count($errors) == 0) {
    $password = md5($password_1);//encrypt the password before saving in the database

    $query = "INSERT INTO `register` (username, password, email, money, ruby, diamonds, levelpoints, level)
    VALUES ('$username', '$password', '$email', '0', '0', '0', '0', '0')";
    mysqli_query($db, $query);

    $idQuery = "SELECT ID FROM `register` WHERE username='$username'";
    mysqli_query($db, $idQuery);
    $_SESSION['username'] = $username;
    $_SESSION['userid'] = $idQuery;
    $_SESSION['success'] = "You are now logged in";
    header('location: index2.php');
  }
}


// LOGIN USER
if (isset($_POST['login_user'])) {
  $username = mysqli_real_escape_string($db, $_POST['username']);
  $password = mysqli_real_escape_string($db, $_POST['password']);

  if (empty($username)) {
    array_push($errors, "Username is required");
  }
  if (empty($password)) {
    array_push($errors, "Password is required");
  }

  if (count($errors) == 0) {
    $password = md5($password);
    $query = "SELECT * FROM `register` WHERE username='$username'";
    $results = mysqli_query($db, $query);
    if (mysqli_num_rows($results) == 1) {
      $_SESSION['username'] = $username;
      $_SESSION['success'] = "You are now logged in";
      header('location: index2.php');
    }else {
        array_push($errors, "Wrong username/password combination");
    }
  }
}

  ?>

The results that I should be getting are(from top to bottom and left to right) Username, Level, Money, Diamond, Ruby and their values should respectively be Username, 0, 0, 0, 0.

I've tried everything and nothing changes, I've re-constructed my code twice and it still outputs only that and nothing else.

You have an issue here in your code:

$idQuery = "SELECT ID FROM `register` WHERE username='$username'";
mysqli_query($db, $idQuery);
$_SESSION['username'] = $username;
$_SESSION['userid'] = $idQuery;

As i mentioned in my comment, check what are you getting in echo "SELECT * FROM register WHERE ID='$idQuery' "; you definitely getting this kind of result:

SELECT * FROM register` WHERE ID= 'SELECT ID FROM `register` WHERE username='somename''

For sub query, remove quotes around your variable from:

"SELECT * FROM register` WHERE ID='$idQuery' ";

should be:

"SELECT * FROM register` WHERE ID = $idQuery";

Note that, this is success case, as you show your result here https://imgur.com/P64hqvI , your query is working fine..

You also need to use some protection for $idQuery if $idQuery == '' then your you can't get any result also.

As @patrick-q mentioned, use session to store username or ID instead of saving a full query.

Second, you code is wide open for SQL injection, for preventing, use PDO.

Some helpful links:

Are PDO prepared statements sufficient to prevent SQL injection?

How can I prevent SQL injection in PHP?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM