-2

I can not for the life of me figure out how to format this for it to work properly.

I am running a query on a database, and it works completely fine if you put in a string of the username directly.

    $link = mysqli_connect("localhost", "root", "123", "accounts");

    $query = "SELECT balance FROM `users` WHERE `username` = 'bob'";
    $result = mysqli_query($link, $query);
    $row = mysqli_fetch_row($result);
    return $row[0];

However, if I replace the query with

$query = "SELECT balance FROM `users` WHERE `username` = $username";

It will not work. I've tried every combination I can try for the variable $username, and it still doesn't work. Can someone guide me in the right direction?

bubly
  • 1
  • 2
  • You need quotes around `$username`, just like you have around `bob`. – Barmar Jun 02 '22 at 23:49
  • But you shouldn't put variables into queries in the first place. Use a prepared statement with parameters to prevent SQL injection. See https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php – Barmar Jun 02 '22 at 23:50
  • Using quotes around $username does not work either @Barmar – bubly Jun 02 '22 at 23:56
  • My guess is you used backticks instead of qutoes. But I just told you not to do it this way at all, so who cares. Use a prepared statement and get it right. – Barmar Jun 02 '22 at 23:58

0 Answers0