-2

I'm trying to display some specific data from MySQL to the PHP web but I'm always getting 0 results . the code i used is:

<?php
$conn = mysqli_connect("localhost", "root", "", "summary");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$user= .$_SESSION["username"];
$sql = "SELECT money FROM users WHERE username= .$user";
$result = $conn->query($sql);
if (!empty($result) && $result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["money"];
}
echo "</table>";
} else { echo "0 results"; }
$conn->close();
?>
xQwerty
  • 1
  • 3

2 Answers2

-1

first of all you should use prepared statement in case to avoid sql injection

try to change code to this:

<?php 

// create connection
$conn = new mysqli("localhost", "root", "", "summary");

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$user = $_SESSION["username"];
$sql = "SELECT money FROM users WHERE username = ?";
if ($stmt = $conn->prepare($sql)) {
    $stmt->bind_param("s",$user);
    if ($stmt->execute()) {
        $result = $stmt->get_result();
        if ($result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                echo $row["money"];
            }
            $stmt->close();
            $conn->close();
        }else{ echo "0 result"; }
    }
}

?>
-1

Your SQL string is wrong.

$sql = "SELECT money FROM users WHERE username= '$user'";

However, I also strongly advise you to use prepared statements with parameter binding wither with mysqli_prepare or using PDO

So your code changes like this:

$user= .$_SESSION["username"];
$sql = "SELECT money FROM users WHERE username= ?";
$stmt = $conn->prepare($sql);

if($stmt)
{
    $stmt->bind_param('s', $user);

    if($stmt->execute())
    { 
        $result = $stmt->get_result(); 
        /...
    }
}
MrLumie
  • 247
  • 2
  • 10