Create a Dynamic insert statement - PHP - Mysql

387

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 countcount($_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 extracommas

$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;
578

Answer

Solution:

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!

People are also looking for solutions to the problem: crawling different languages of a page which is depending on sessions in php

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.