1

I'm trying to insert values of $array into MySQL and I'm facing a problem that the values I'm getting in the database are zeros:

$v = mysqli_real_escape_string($connect, $array[0][0]);

mysqli_query($connect, 'INSERT INTO myTable(col)VALUES("'.$V.'")');
Don't Panic
  • 41,125
  • 10
  • 61
  • 80
  • 1
    You should learn to use prepared statements instead of substituting variables. Even using `mysqli_real_escape_string()` is not as safe. – Barmar Aug 29 '18 at 23:33
  • @Barmar especially if you end up using a different variable than the one you escaped ;) – Don't Panic Aug 30 '18 at 00:07
  • @Don'tPanic He could still get the variables wrong. `$v = $array[0][0]; mysqli_stmt_bind_param("s", $V);` – Barmar Aug 30 '18 at 00:17
  • @Barmar sure, definitely. I just meant that you could accidentally concat a variable that that you hadn't escaped, which could potentially cause worse problems than just binding the wrong value. Granted, the chances of there just happening to be a `$V` containing some SQL injection seem pretty low, but who knows. – Don't Panic Aug 30 '18 at 00:20

1 Answers1

2

You've set the value to the variable $v, but you're using capital $V in your SQL when you execute the query. PHP variables are case sensitive, so $V is undefined. It's just a typo, but I'll try to explain how it ends up as a zero in your database.

The undefined variable evaluates to null, but you're using it in a string context, so it becomes an empty string. That empty string gets converted to zero by MySQL when you try to insert it into a numeric type column.

You can catch problems like this if you enable warnings and notices on your development server. PHP will tell you about undefined variables, which will make it easier to avoid problems like this.

Don't Panic
  • 41,125
  • 10
  • 61
  • 80
  • Hey man, real good answer. I was a bit *eesh* about your saying it was "just a typo" (*lol*), but then continuing to "explain" why it becomes empty etc. Got my vote. – Funk Forty Niner Aug 30 '18 at 01:04
  • Thanks @Funk. :) I originally CV'd as typo, but then the comment I was leaving to try to explain why the typo had that effect was getting a little out of hand, so I figured I should just make it an answer. – Don't Panic Aug 30 '18 at 03:41