0

So I'm a beginner with PHP, and currently, I'm studying MySQL right now, and I'm having trouble with this particular code.

$connection = mysqli_connect('localhost','root','','loginapp'); 

$username = $_POST['username'];
$password = $_POST['password'];

$query = "INSERT INTO users(username,password) VALUES ('$username','$password')";
$result = mysqli_query($connection,$query);

if ($result)
   echo 1

else if(!$result)
   echo 0;

*Basically it echoes 1 if the username and password have been transferred to the database successfully, and 0 when it doesn't.

If I remember correctly, you only use quotes ' ' for strings and when passing variables, you don't need to encase them with ' or ". So, I tried removing the quotes from the variables in VALUES($username,$password) and it starts to echo 0 instead. Can anyone provide me an explanation as to why the variables have to be enclosed with ' or " inside the VALUES so I'd have a better understanding of how it works?

NIKHIL NEDIYODATH
  • 2,703
  • 5
  • 24
  • 30
Jp Arcilla
  • 83
  • 1
  • 1
  • 8
  • Or better prevent SQL injection and remove the need to qoute manually https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php – Raymond Nijland Mar 22 '18 at 17:26
  • Can you please share your error? – NIKHIL NEDIYODATH Mar 22 '18 at 17:42
  • If you find a SQL tutorial (any flavor), you'll see that strings need to be quoted in any SQL statement. `INSERT INTO MyTable (ID, Val) VALUES (1, 'Some text')`, for instance. It's not relevant whether the values are coming from variables or not, it's basic SQL syntax. – Ken White Mar 22 '18 at 17:53

1 Answers1

0

You password and username fields must be strings in mysql, so you'll need to put them between quotes on the query.

I suggest you to take a look at prepared statments too, it will be a better way to do this query.

Dionei Miodutzki
  • 657
  • 7
  • 16
  • Yeah but since we're talking about passing variables here, I got really confused why I needed to add quotes to $username and $password inside VALUES and didn't think it had that much impact on the code. – Jp Arcilla Mar 22 '18 at 17:42