Hello. I am writing a function for working with a database. A question has arisen that has not yet found a solution. How to put the value from the loop into the query. Here is an example of my code.

foreach($fields as $value) : print_r($value); endforeach; $sql ="INSERT INTO ".$table_name." ("..") VALUES ('".$values['0']."','".$values['1']."','".$values['2']."')"; 

    3 answers 3

    It is possible in the spirit of this:

     /* $columns = array("foo", "bar"); $values = array("value foo", "value bar"); */ assert(count($columns) == count($values)); $sql = sprintf("INSERT INTO %s (%s) VALUES (%s)", $table_name, implode(", ", $columns), implode(", ", array_map("mysql_real_escape_string", $values)); 

    If it is necessary to do an insert on many rows, then a variation:

     $sql_t = sprintf("INSERT INTO %s (%s) VALUES (%s)", $table_name, implode(", ", $columns), substr(str_repeat("%s,", count($columns)), 0, -1)); for ($all_values as $values) { $r = mysql_query(vsprintf($sql_t, array_map("mysql_real_escape_string", $values))); ... } 

    But this is necromancy. It is better to use PDO, in the spirit of

      $q = $db->prepare("INSERT INTO foo (bar, baz) VALUES (:bar, :baz)"); $q->execute($values); // $values = array("bar" => ..., "baz" => ...); 

    For several rows, repeat the $q->execute() call.

    If there are a lot of similar requests, the same thing, only prepared statements should be generated dynamically. Very rough sketch:

      /* $tables = array( "foos" => array("foo", "bar", "baz"), "eggs" => array("spam", "ham"), ); */ function prepend_colon($x) { return ":" . $x; } foreach($tables as $t => $c) { $q[$t] = $db->prepare(sprintf("INSERT INTO %s (%s) VALUES (%s)", $t, implode(",", $c), implode(",", array_map("prepend_colon", $c)))); } 

      The request to place in the loop body probably, if I understood correctly:

       foreach ($fileds as $value) { $sql = "INSERT INTO `table` (vlaue1, value2, value3) VALUES ('".$value[0]."', '".$value[1]."', '".$value[2]."')"; mysql_query($sql); } 

      Something like that, but in general the question is vague.

        Try this:

         foreach($fields as $value) : $value.=", "; if (count($value)>0) for($i=0;$i<count($value);$i++) $text.="'{$value["$i"]}'"; endforeach; $sql ="INSERT INTO ".$table_name." ("..") VALUES ( $text );"; 

        As an option, if I understand you correctly.