1

I want to get data from database using session of loggedin user in my website so he can see his profile with all of his data like name,country,city and address. But code which I am using is not working "SELECT * FROM login WHERE username = $_SESSION[user]" it's not giving me any data but when I replace it with this "SELECT * FROM login WHERE passowrd = $_SESSION[pass]" it works fine but it gives all data from database instead of only session or user who is loggedin please tell me the solution

here is the full code:

 <?php
    if(!isset($_COOKIE['loggedin'])){
        header("location:index.php");
    }

session_start();

if(!isset($_SESSION['user'])){

header("location: index.php");
}
else {

?>


<?php
$con=mysqli_connect("localhost","root","123","user");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$result = mysqli_query($con,"SELECT * FROM login WHERE username = $_SESSION[user]")
    or die(mysql_error());  

echo "<table border='1'>
<tr>
<th>Name</th>
<th>Country</th>
<th>City</th>
<th>Address</th>

</tr>";

while($row = mysqli_fetch_array($result, MYSQL_ASSOC))
  {
  echo "<tr>";
      echo "<td>" . $row['name'] . "</td>";
          echo "<td>" . $row['country'] . "</td>";
              echo "<td>" . $row['city'] . "</td>";
    echo "<td>" . $row['address'] . "</td>";

  echo "</tr>";
  }
echo "</table>";

mysqli_close($con);}
?> 

1 Answer 1

4

You have a lot of mistakes, mate. Let me try to give you a few advices:

  1. Instead of:

    "SELECT * FROM login WHERE username = $_SESSION[user]"

you need something like:

"SELECT * FROM login WHERE username = '".$_SESSION[user]."'"

You need the apostrophes around the username.

  1. Make sure that $_SESSION[user] exists and really holds the username.

  2. Never write queries like SELECT *, because that's not a good practice. The best practice is to select only the columns you really need. It is safer and more economical if we talk about memory usage. So instead of SELECT * use SELECT col1, col2, col3.

  3. Try to obfuscate your password. If somebody breaks through your database he will be able to steal the identity of any users. Read more here and here. Do not forget about rainbow tables either if you are thinking about using something as simple as MD5.

  4. Escape your queries to prevent SQL injections.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.