0

I have a query that I would like to run to input data into my MySQL database. It is working fine with pure text and numbers, but inputting variables in:

$base_ids = 4;
while($j <= $base_ids){
$row = array(keygenb());

foreach($row as $value){
$query = "INSERT INTO webstore(col_1) VALUES('".$value."')";
echo $query;
$result = mysqli_query($con,$query);
}
$j++;
}

When I echo $query, there is a problem with the VALUES('".$value."')"; Echoing $query gives me this: ($value = XBox-CJbf-Ont4-B7kk)

INSERT INTO webstore(col_1) VALUES('')XBox-CJbf-Ont4-B7kk

The $value gets stuck on the end, rather than put between the quotes where it can be executed. I'm sure this is an easy fix, however I've tried to get around it a few ways and haven't yet found a way that works.

Many thanks,

Mem

  • Use escaping for all data that is passed to a query. mysqli_real_escape_string will do the thing – Alma Do Aug 08 '13 at 10:34
  • Are you sure? because I tried and it works alright for me.. – aljx0409 Aug 08 '13 at 10:35
  • I believe so - I've tried to use plain text or numbers and that inputs into my database without issues. I changed it to: $query = "INSERT INTO webstore(col_1) VALUES('".mysqli_real_escape_string($con,$value)."')"; I'm getting the same result for my echo statement and nothing in the database. :x – Memphis Aug 08 '13 at 10:37
  • Escaping is also a good idea for security reasons. Even if the query works, it may be vulnerable to [SQL Injection](http://stackoverflow.com/questions/2200256/how-can-i-avoid-sql-injection-attacks). – ygesher Aug 08 '13 at 10:37
  • Thanks for the tip, I will use it in future :) – Memphis Aug 08 '13 at 10:38
  • When passing php variable to a query, no concatenation is necessary: `$query="INSERT INTO webstore(col_1) VALUES('$value')";` is correct syntax. – ygesher Aug 08 '13 at 10:39
  • Yea, I was going to suggest what jegesh suggested. See what happens when you do that. I've never seen that bug before. However, jegesh, that's not necessarily the correct syntax for an sql query, that is just how PHP works. If you use double quotes, you can put the variables right into any string and it'll replace it with the string variable you put in. If he had used single quotes to form his query, he would have had to concatenate. Just letting anyone who reads this, know what's really going on. – Omar Aug 08 '13 at 10:43
  • That must have been what was wrong, it's working for me now. Thanks jegesh and Omar. – Memphis Aug 08 '13 at 10:44

0 Answers0