Reza Reza - 3 months ago 6x
PHP Question

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?


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);


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

/* close statement */