Reza
Reza

Reputation: 523

Mysqli returns the wrong data

I would like to echo out the values of the column username and tried it like this:

public function username_exists($username) {
    $conn = new mysqli($this->servername, $this->username, $this->password, $this->db_name);
    $result = mysqli_query($conn, "SELECT username FROM fe_users WHERE username = $username");
    while ($row = mysqli_fetch_assoc($result)) {
        echo $row["username"];
    }
}

When I run this code, for some reason it always returns the string 33, which is also stored in my database but it is definitely not the value of the column username. Why am I getting this output and how can I display the username which is stored in the table fe_users?

Upvotes: 1

Views: 185

Answers (1)

Saty
Saty

Reputation: 22532

You need to quotes around $username

SELECT username FROM fe_users WHERE username = '$username'"

Better use bind and prepare statement. It automatically escape your string and free from sql injection attack

/* prepare statement */
$stmt = $conn->prepare( "SELECT username FROM fe_users WHERE username = ?");
$stmt->bind_param('s', $username);
$stmt->execute();

$stmt->bind_result($col1);

/* fetch values */
while ($stmt->fetch()) {
    printf("%s %s\n", $col1);
}

/* close statement */
$stmt->close();

Upvotes: 3

Related Questions