TSCAmerica.com
TSCAmerica.com

Reputation: 5387

Create a Dynamic insert statement - PHP - Mysql

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;

Upvotes: 4

Views: 1963

Answers (1)

Gary Mathis
Gary Mathis

Reputation: 171

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!

Upvotes: 4

Related Questions