0

I have a table called scoutboy and a table called levels. I have a table called scoutboy_has_levels that contains two foreign keys : scoutboy_id and levels_id.

Table levels contains a list of all 10 possible categories with each has an id.

Example: A scoutboy (with id 500) who is both nightwatcher(has level id 2) and equipment_chief(has level id 3), upon registration the scoutboy should choose both these two from the form.The input is in an array "levelslist". scoutboy_has_levels should be :

Scoutboy_id    levels_idlevels
500            2
500            3

I'm trying to achieve this but it isn't working. My code:

if(isset($_POST['level']))
{
    $levelslist=$_POST['level'];}
    //$levelslist[0] is in this case "nightwatcher" and at index 1 is is "equipment_chief"
 foreach($levelslist as $element)
 {
    //here I'm retreiving the id for the selected levels from `levels` table
 $idlevel=mysqli_query($mysqli,"SELECT idlevels FROM levels WHERE category='$element'");

if(!empty($element)) {
    //mysqli_real_escape_string($mysqli,$element);
mysqli_query($mysqli,"INSERT INTO scoutboy_has_levels(levels_idlevels,scoutboy_id) VALUES (mysqli_real_escape_string($mysqli,$element),$id)");
}
} 

How to fix this and produce my desired output?

shadow.T
  • 125
  • 1
  • 2
  • 11
  • what's the value of `$_POST['level']` ? – Ali Nov 25 '17 at 15:21
  • $_POST['level'] is an array of the levels the scoutboy chooses. In my case , $_POST['level'] is nightwatcher at index 0 and equipment chief at index 1 – shadow.T Nov 25 '17 at 15:25
  • 1
    You can't put `mysqli_real_escape_string()` inside a string and expect it to be evaluated. That said, don't rely on the `real_escape_string()` functions to prevent SQL injection, [they alone are not sufficient](https://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string). You should use [prepared statements](https://secure.php.net/manual/en/mysqli.prepare.php) instead. [**This post**](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) has some good examples. – Alex Howansky Nov 25 '17 at 16:46
  • Why are you using `mysqli_real_escape_string($mysqli,$element)` in the `INSERT INTO` statement at all? Is that where you meant to use `$idlevel`? Remember that `mysqli_query` returns a [mysqli_result object](http://php.net/manual/en/class.mysqli-result.php). –  Nov 25 '17 at 16:58

0 Answers0