4

I have a form which has multiple drop downs (16) speed[] and some other fields

The data from the dropdown boxes has to be inserted into a Mysql table

What I did is I took the count count($_POST["speed"]);and then loop through until the end of the speed array.

The problem is:

  1. If Anyone of the dropdown is not selected it returns "-1", if used `($_POST["speed"][$i]!="-1")for that but it does not compare and goes into the IF loop

  2. The Insert Query is not a valid not sure how to append the extra commas

$sql when printed

INSERT INTO mytablename (w_name,wtype,speed1,speed2, speed3, speed4, speed5, speed6, speed7, speed8, speed9, speed10, speed11, speed12, speed13, speed14, speed15, speed16, coach_id) VALUES ('name', '', ''-1''800''-1''-1''200''-1''-1''-1''-1''-1''-1''-1''-1''-1''-1''200'', '208')

My PHP code

 $itemCount = count($_POST["speed"]);
        $itemValues=0;
        $query = "INSERT INTO mytablename (w_name,wtype,speed1,speed2, speed3, speed4, speed5, speed6, speed7, speed8, speed9, speed10, speed11, speed12, speed13, speed14, speed15, speed16, coach_id) VALUES ";
        $bldSpltString="";
        $queryValue = "";
        for($i=0;$i<$itemCount;$i++) {
            if(($_POST["speed"][$i]!="-1") || !empty($_POST["speed"][$i])) {

                $bldSpltString .= "'" .  $_POST["speed"][$i] ."'";
            }
        }
        $queryValue .= "('" . $wkout . "', '" . $wtype . "', '" . $bldSpltString . "', '" .$_SESSION['id']."')";

        $sql = $query.$queryValue;
        echo $sql;
        exit;
1
  • 2nd level sql injection. People don't even need your form to inject. Commented Jun 17, 2016 at 21:49

1 Answer 1

4

I would do something like this:

<?php
    function dynamicInsert($table_name, $assoc_array){
        $keys = array();
        $values = array();
        foreach($assoc_array as $key => $value){
            $keys[] = $key;
            $values[] = $value;
        }
        $query = "INSERT INTO `$table_name`(`".implode("`,`", $keys)."`) VALUES('".implode("','", $values)."')";
        echo $query;
    }
    dynamicInsert("users", array(
        "username" => "Test User",
        "password" => "Password123"
    ));
?>

WARNING: This code is not secure, I would run a mysql_real_escape_string and any other necessary sanitation on the variables being sent to mysql. I would also steer clear of allowing this script to run on anything public facing as a dynamic insert could allow for huge security risks!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.