I have an HTML form that has 2 dynamic fields which are:
<input type="text" name="ingredients[]" placeholder="Ingredients"/></div>
<input type="text" name="quantity[]" placeholder="Quantity"/></div>
Look here this is how the db table should be for those inputs in the form
Ing 1 1001 1KG
Ing 2 1001 2KG
ing 3 1001 3KG
now check the image and you'll see what's happening
DB Ingredients TABLE
I have the recipe-ID in my php file I just want a PDO code that help me to INSERT "ingredients", "quantity" and "$recipe_ID" each one on a row.
<?php
header('Content-type: application/json');
require_once 'db/pdoconnect.php';
if($_POST)
{
$sth = $con->prepare("SELECT `recipeid` FROM Recipes ORDER BY `recipeid` DESC");
$sth->execute();
$previousid = $sth->fetchColumn();
$offset=1;
$generatingid=$previousid+$offset;
$newid=$generatingid;
//print("Last Id=$previousid\n");
//print("New Id=$newid\n");
$title = $_POST['title'];
$preptime = $_POST['preptime'];
$cocktime = $_POST['cocktime'];
$level = $_POST['level'];
$serving = $_POST['serving'];
$recipetype = $_POST['recipetype'];
$intro = $_POST['intro'];
$details = $_POST['details'];
$image = $_POST['image'];
try
{
$stmt = $con->prepare("INSERT INTO Recipes (recipeid,title,preptime,cocktime,level,serving,recipetype,intro,details,recipeimg) VALUES( :newid, :title, :preptime, :cocktime, :level, :serving, :recipetype, :intro, :details, :image)");
$stmt->bindParam(":newid",$newid);
$stmt->bindParam(":title",$title);
$stmt->bindParam(":preptime",$preptime);
$stmt->bindParam(":cocktime",$cocktime);
$stmt->bindParam(":level",$level);
$stmt->bindParam(":serving",$serving);
$stmt->bindParam(":recipetype",$recipetype);
$stmt->bindParam(":intro",$intro);
$stmt->bindParam(":details",$details);
$stmt->bindParam(":image",$image);
if($stmt->execute()) { //check if main query has been executed
$sql = "INSERT INTO Ingredients VALUES";
for($i = 1 ; $i <= count($_POST['ingredients']) ; $i++){
$sql .= " (:recipeid" .$i. ", :ingredient" .$i. ", :quantity" .$i. "),";
}
// remove the last (,) from the $sql
$sql = rtrim($sql, ',');
$sth = $con->prepare($sql);
// binding parameters
for($i = 1 ; $i <= count($_POST['ingredients']) ; $i++){
$varIng = $_POST['ingredients'][$i];
$varQnty = $_POST['quantity'][$i];
$sth->bindParam(':recipeid' .$i , $newid , PDO::PARAM_STR);
$sth->bindParam(':ingredient' .$i , $varIng , PDO::PARAM_STR);
$sth->bindParam(':quantity' .$i , $varQnty , PDO::PARAM_STR);
}
if ($sth->execute()) {
$response_array['status'] = 'success';
}
}//END OF FIRST IF STATEMENT
else{
$response_array['status'] = 'error';
}
echo json_encode($response_array); //SEND THE RESPONSE
}//END OF TRY
catch(PDOException $e){
echo $e->getMessage();
}
}
?>
Assuming the table's name shown in the image you posted in your question ingredient_quantity in your database, and you said you already have the recipe-ID PHP Fiddle
<?php
$newid = 'A10';
//considering this is your table shown in the picture
$sql = "INSERT INTO ingredient_quantity VALUES";
for($i = 1 ; $i <= count($_POST['ingredients']) ; $i++){
$sql .= " (:newid" .$i. ", :ingredient" .$i. ", :quantity" .$i. "),";
}
// remove the last (,) from the $sql
$sql = rtrim($sql, ',');
$sth = $con->prepare($sql);
// binding parameters
for($i = 1 ; $i <= count($_POST['ingredients']) ; $i++){
$varIng = $_POST['ingredients'][$i];
$varQnty = $_POST['quantity'][$i];
$sth->bindParam(':newid' .$i , $newid , PDO::PARAM_STR);
$sth->bindParam(':ingredient' .$i , $varIng , PDO::PARAM_STR);
$sth->bindParam(':quantity' .$i , $varQnty , PDO::PARAM_STR);
}
$sth->execute();
?>
EDIT 1:
for the above code I have an error as the ingredients[] array starts from 0 and not 1, the final index of the for loop will be undefined, so work around it make the last for loop like the following:
for($i = 0 ; $i < count($_POST['ingredients']) ; $i++){
$varIng = $_POST['ingredients'][$i];
$varQnty = $_POST['quantity'][$i];
$j = $i + 1;
$sth->bindParam(':newid' .$j , $newid , PDO::PARAM_STR);
$sth->bindParam(':ingredient' .$j , $varIng , PDO::PARAM_STR);
$sth->bindParam(':quantity' .$j , $varQnty , PDO::PARAM_STR);
}
EDIT 2:
You may try doing it with ? placeholders instead of named placeholders like this PHP Fiddle 2:
//considering this is your table shown in the picture
$sql = "INSERT INTO ingredient_quantity VALUES";
for($i = 0 ; $i < count($_POST['ingredients']) ; $i++){
$sql .= " ( ? , ? , ? ) , ";
}
// remove the last (,) from the $sql
$sql = rtrim($sql, ',');
$sth = $con->prepare($sql);
// binding parameters
$j = 1;
for($i = 0 ; $i < count($_POST['ingredients']) ; $i++){
$varIng = $_POST['ingredients'][$i];
$varQnty = $_POST['quantity'][$i];
$sth->bindValue( $j , $varIng);
$sth->bindValue( $j + 1, $newid);
$sth->bindValue( $j + 2, $varQnty);
$j += 3;
}
$sth->execute();
Related
I have an HTML form that has 2 dynamic fields which are:
<input type="text" name="ingredients[]" placeholder="Ingredients"/></div>
<input type="text" name="quantity[]" placeholder="Quantity"/></div>
Look here this is how the db table should be for those inputs in the form
Ing 1 1001 1KG
Ing 2 1001 2KG
ing 3 1001 3KG
now check the image and you'll see what's happening
DB Ingredients TABLE
I have the recipe-ID in my php file I just want a PDO code that help me to INSERT "ingredients", "quantity" and "$recipe_ID" each one on a row.
<?php
header('Content-type: application/json');
require_once 'db/pdoconnect.php';
if($_POST)
{
$sth = $con->prepare("SELECT `recipeid` FROM Recipes ORDER BY `recipeid` DESC");
$sth->execute();
$previousid = $sth->fetchColumn();
$offset=1;
$generatingid=$previousid+$offset;
$newid=$generatingid;
//print("Last Id=$previousid\n");
//print("New Id=$newid\n");
$title = $_POST['title'];
$preptime = $_POST['preptime'];
$cocktime = $_POST['cocktime'];
$level = $_POST['level'];
$serving = $_POST['serving'];
$recipetype = $_POST['recipetype'];
$intro = $_POST['intro'];
$details = $_POST['details'];
$image = $_POST['image'];
try
{
$stmt = $con->prepare("INSERT INTO Recipes (recipeid,title,preptime,cocktime,level,serving,recipetype,intro,details,recipeimg) VALUES( :newid, :title, :preptime, :cocktime, :level, :serving, :recipetype, :intro, :details, :image)");
$stmt->bindParam(":newid",$newid);
$stmt->bindParam(":title",$title);
$stmt->bindParam(":preptime",$preptime);
$stmt->bindParam(":cocktime",$cocktime);
$stmt->bindParam(":level",$level);
$stmt->bindParam(":serving",$serving);
$stmt->bindParam(":recipetype",$recipetype);
$stmt->bindParam(":intro",$intro);
$stmt->bindParam(":details",$details);
$stmt->bindParam(":image",$image);
if($stmt->execute()) { //check if main query has been executed
$sql = "INSERT INTO Ingredients VALUES";
for($i = 1 ; $i <= count($_POST['ingredients']) ; $i++){
$sql .= " (:recipeid" .$i. ", :ingredient" .$i. ", :quantity" .$i. "),";
}
// remove the last (,) from the $sql
$sql = rtrim($sql, ',');
$sth = $con->prepare($sql);
// binding parameters
for($i = 1 ; $i <= count($_POST['ingredients']) ; $i++){
$varIng = $_POST['ingredients'][$i];
$varQnty = $_POST['quantity'][$i];
$sth->bindParam(':recipeid' .$i , $newid , PDO::PARAM_STR);
$sth->bindParam(':ingredient' .$i , $varIng , PDO::PARAM_STR);
$sth->bindParam(':quantity' .$i , $varQnty , PDO::PARAM_STR);
}
if ($sth->execute()) {
$response_array['status'] = 'success';
}
}//END OF FIRST IF STATEMENT
else{
$response_array['status'] = 'error';
}
echo json_encode($response_array); //SEND THE RESPONSE
}//END OF TRY
catch(PDOException $e){
echo $e->getMessage();
}
}
?>
Assuming the table's name shown in the image you posted in your question ingredient_quantity in your database, and you said you already have the recipe-ID PHP Fiddle
<?php
$newid = 'A10';
//considering this is your table shown in the picture
$sql = "INSERT INTO ingredient_quantity VALUES";
for($i = 1 ; $i <= count($_POST['ingredients']) ; $i++){
$sql .= " (:newid" .$i. ", :ingredient" .$i. ", :quantity" .$i. "),";
}
// remove the last (,) from the $sql
$sql = rtrim($sql, ',');
$sth = $con->prepare($sql);
// binding parameters
for($i = 1 ; $i <= count($_POST['ingredients']) ; $i++){
$varIng = $_POST['ingredients'][$i];
$varQnty = $_POST['quantity'][$i];
$sth->bindParam(':newid' .$i , $newid , PDO::PARAM_STR);
$sth->bindParam(':ingredient' .$i , $varIng , PDO::PARAM_STR);
$sth->bindParam(':quantity' .$i , $varQnty , PDO::PARAM_STR);
}
$sth->execute();
?>
EDIT 1:
for the above code I have an error as the ingredients[] array starts from 0 and not 1, the final index of the for loop will be undefined, so work around it make the last for loop like the following:
for($i = 0 ; $i < count($_POST['ingredients']) ; $i++){
$varIng = $_POST['ingredients'][$i];
$varQnty = $_POST['quantity'][$i];
$j = $i + 1;
$sth->bindParam(':newid' .$j , $newid , PDO::PARAM_STR);
$sth->bindParam(':ingredient' .$j , $varIng , PDO::PARAM_STR);
$sth->bindParam(':quantity' .$j , $varQnty , PDO::PARAM_STR);
}
EDIT 2:
You may try doing it with ? placeholders instead of named placeholders like this PHP Fiddle 2:
//considering this is your table shown in the picture
$sql = "INSERT INTO ingredient_quantity VALUES";
for($i = 0 ; $i < count($_POST['ingredients']) ; $i++){
$sql .= " ( ? , ? , ? ) , ";
}
// remove the last (,) from the $sql
$sql = rtrim($sql, ',');
$sth = $con->prepare($sql);
// binding parameters
$j = 1;
for($i = 0 ; $i < count($_POST['ingredients']) ; $i++){
$varIng = $_POST['ingredients'][$i];
$varQnty = $_POST['quantity'][$i];
$sth->bindValue( $j , $varIng);
$sth->bindValue( $j + 1, $newid);
$sth->bindValue( $j + 2, $varQnty);
$j += 3;
}
$sth->execute();
I want to insert data in database with dynamic php variable and when I check the script in database I have only one record :(
$low_0 = 0;
$low_1 = 1;
$low_2 = 2;
$nr = 9;
for ($i = 0; $i < $nr; $i++) {
$sql = 'INSERT INTO prognoza_curenta (ora, prognoza, min, max, reg_date)
VALUES (' . "${'low_' . $i}, " . "11," . "22," . "33," . "'$timp')";
echo "$sql" . "<br>";
}
if (mysqli_query($db, $sql)) {
echo 'Data send' . "<br>";
} else {
echo 'Error send.' . mysqli_error($sql) . "<br>";
}
Change your loop to this:
$sql = 'INSERT INTO prognoza_curenta (ora, prognoza, min, max, reg_date) VALUES';
for ($i = 0; $i < $nr; $i++) {
$sql .= ' (' . "${'low_' . $i}, " . "11," . "22," . "33," . "'$timp')";
}
The Solution With prepared Statement:
$stmt = $conn->prepare("INSERT INTO prognoza_curenta (ora, prognoza, min, max, reg_date) VALUES (?, ?, ?, ?, ?)");
$stmt->bind_param("sssss", $ora, $prognoza, $min, $max, $reg_date);
// set parameters and execute
for ($i = 0; $i < $nr; $i++) {
$ora= ${'low_' . $i};
$prognoza= "11";
$min= '22';
$max = '33';
$reg_date = $timp;
$stmt->execute();
}
As Suggested by #MarkBaker, This is procedure of prepare statement. Please let me know.
This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 6 years ago.
I wrote a function to insert what i want in any database :
public function insert($db, $array_label, $array_value){
$DB = new PDO('mysql:host='.$_SESSION['mysql'][0].';dbname='.$_SESSION['mysql'][1].';charset=utf8', $_SESSION['mysql'][2], $_SESSION['mysql'][3]);
$sql = "INSERT INTO '".$db."' (";
for($i = 0; $i < count($array_label); $i++){
if($i > 0)
$sql .= ", ";
$sql .= "'".$array_label[$i]."'";
}
$sql .= ") VALUES (";
for($i = 0; $i < count($array_label); $i++){
if($i > 0)
$sql .= ", ";
$sql .= ":".$array_label[$i];
}
$sql .= ")";
$stmt = $DB->prepare($sql);
echo '\$DB->prepare("'.$sql.'");';//DEBUG
for($i = 0; $i < count($array_label); $i++){
$label = ":".$array_label[$i];
$stmt->bindParam("$label", $array_value[$i]);
echo '</br>\$stmt->bindValue("'.$label.'", '.$array_value[$i].')';//DEBUG
}
$stmt->execute;
echo "</br></br>Requête OK.";
}
}
Then, i use it like this :
$array_label = array('ID', 'ID_lang', 'ID_entry_cat', 'date', 'label', 'content');
$array_value = array($ID, $ID_lang, $ID_entry_cat, "2016-03-03 00:00:00", $label, $content);
$DB->insert('entry', $array_label, $array_value);
After doing a lot of test, it may have a syntax problem, but i wasn't able to figure out where.
Here is what i got from the echo's(//DEBUG) :
$DB->prepare("INSERT INTO 'entry' ('ID', 'ID_lang', 'ID_entry_cat', 'date', 'label', 'content') VALUES (:ID, :ID_lang, :ID_entry_cat, :date, :label, :content)");
\$stmt->bindValue(":ID", 1)
\$stmt->bindValue(":ID_lang", 1)
\$stmt->bindValue(":ID_entry_cat", 1)
\$stmt->bindValue(":date", 2016-03-03 00:00:00)
\$stmt->bindValue(":label", dsqfsdq)
\$stmt->bindValue(":content", sdqfdsqf)
I know there is plenty topics on PDO not returning error but :
After reading a lot of them, it didn't help me at all.
Let say this : I'm a complete noob with PDO.
The echo i showed to you is what my function is doing.
I enclosed some pictures of my db to help :
PS: i leaved out "date" but it's not supposed to make troubles. I tested the same thing with it and it did the same thing : nothing.
Replace bindparam with bindvalue since you are passing values of that array:
EDIT
you also have quotes for table and column names,I replaced them with backticks and also you are missing brackets for execute
function insert($db, $array_label, $array_value){
$DB = new PDO('mysql:host='.$_SESSION['mysql'][0].';dbname='.$_SESSION['mysql'][1].';charset=utf8', $_SESSION['mysql'][2], $_SESSION['mysql'][3]);
$sql = "INSERT INTO `".$db."` (";
for($i = 0; $i < count($array_label); $i++){
if($i > 0)
$sql .= ", ";
$sql .= "`".$array_label[$i]."`";
}
$sql .= ") VALUES (";
for($i = 0; $i < count($array_label); $i++){
if($i > 0)
$sql .= ", ";
$sql .= ":".$array_label[$i];
}
$sql .= ")";
$stmt = $DB->prepare($sql);
echo '\$DB->prepare("'.$sql.'");';//DEBUG
for($i = 0; $i < count($array_label); $i++){
$label = ":".$array_label[$i];
$stmt->bindValue("$label", "$array_value[$i]");
echo '</br>\$stmt->bindValue("'.$label.'", "'.$array_value[$i].'")';//DEBUG
}
$stmt->execute();
echo "</br></br>Requête OK.";
}
Try running PDO in Exception mode, you can then catch PDO exceptions:
$db_pdo = new PDO($db_dsn, $dbuser, $dbpassword);
$db_pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// its function
$stmt->execute();
Also turn on error reporting in PHP to see whats going on
I have the following script:
<?php
ini_set('max_execution_time', 0);
include("../includes/mysqli.php");
$pointsvar = 50000;
$inserts = 0;
$locationvar = 32000006;
while($locationvar <= 32000260){
while($pointsvar >= 20000){
$url = "http://185.112.249.77:9999/Api/Search?search=&level=0&min=1&max=50&points=$pointsvar&loc=$locationvar";
$jsondata = file_get_contents($url);
$data = json_decode($jsondata, true);
$in=$data['clanList'];
$results = $data['results']; //max is 64
$i = 0;
while($i + 1 <= $results){
$clanid = $in[$i]['id'];
$clanname = mysqli_real_escape_string($con,$in[$i]['name']);
$clanplayerCount = $in[$i]['playerCount'];
$clanwarswon = $in[$i]['warsWon'];
$clanwarslost = $in[$i]['warsLost'];
$clanwarstied = $in[$i]['warsTied'];
$clanLocation = mysqli_real_escape_string($con,$in[$i]['clanLocation']);
$clanlevel = $in[$i]['level'];
$score = $in[$i]['score'];
$sql = "INSERT INTO activeclans(id, name, location, playercount, clanlevel, warswon, warslost, warstied, score)
VALUES('$clanid', '$clanname', '$clanLocation', '$clanplayerCount', '$clanlevel', '$clanwarswon', '$clanwarslost', '$clanwarstied', $score)";
mysqli_query($con, $sql);
$i++;
$inserts++;
}
$pointsvar = $pointsvar-500;
sleep(1);
}
$locationvar++;
sleep(1);
}
echo "Inserted $inserts";
?>
When I run it I am expecting it to go through each location and in each location I expect it to -500 from the $pointsvar until it reaches 20000. It was working until I made it go through each location in a while loop and now it just outputs Inserted 0
I have increased the max_execution_time as it could possible take a looong time to run. This script will be run on a cron around every day or week.
The expected output would be Inserted and a very very very big number..
Thanks for any help you can provide :D
Use for loops instead of while loops to ensure that your variables get initialized properly each time.
$inserts = 0;
for ($locationvar = 32000006; $locationvar <= 32000260; $locationvar++){
for ($pointsvar = 50000; $pointsvar >= 20000; $pointsvar -= 500){
$url = "http://185.112.249.77:9999/Api/Search?search=&level=0&min=1&max=50&points=$pointsvar&loc=$locationvar";
$jsondata = file_get_contents($url);
$data = json_decode($jsondata, true);
$in=$data['clanList'];
$results = $data['results']; //max is 64
for ($i = 0; $i < $results; $i++){
$clanid = $in[$i]['id'];
$clanname = mysqli_real_escape_string($con,$in[$i]['name']);
$clanplayerCount = $in[$i]['playerCount'];
$clanwarswon = $in[$i]['warsWon'];
$clanwarslost = $in[$i]['warsLost'];
$clanwarstied = $in[$i]['warsTied'];
$clanLocation = mysqli_real_escape_string($con,$in[$i]['clanLocation']);
$clanlevel = $in[$i]['level'];
$score = $in[$i]['score'];
$sql = "INSERT INTO activeclans(id, name, location, playercount, clanlevel, warswon, warslost, warstied, score)
VALUES('$clanid', '$clanname', '$clanLocation', '$clanplayerCount', '$clanlevel', '$clanwarswon', '$clanwarslost', '$clanwarstied', $score)";
mysqli_query($con, $sql);
$inserts++;
}
sleep(1);
}
sleep(1);
}
echo "Inserted $inserts";
Also, maybe the innermost loop should be foreach ($data['clanList'] as $clan) -- can the number of clans in the clanList array be different from $data['results']?
And you can speed up INSERT queries by inserting multiple rows with a single query:
INSERT INTO tablename (columns...) VALUES (...), (...), (...), ...
So in your script, you could concatenate all the values during the loop over clans, and then insert that batch at the end of that loop. So it would look like:
$values = array();
for ($i = 0; $i < $results; $i++){
$clanid = $in[$i]['id'];
$clanname = mysqli_real_escape_string($con,$in[$i]['name']);
$clanplayerCount = $in[$i]['playerCount'];
$clanwarswon = $in[$i]['warsWon'];
$clanwarslost = $in[$i]['warsLost'];
$clanwarstied = $in[$i]['warsTied'];
$clanLocation = mysqli_real_escape_string($con,$in[$i]['clanLocation']);
$clanlevel = $in[$i]['level'];
$score = $in[$i]['score'];
$values[] = "('$clanid', '$clanname', '$clanLocation', '$clanplayerCount', '$clanlevel', '$clanwarswon', '$clanwarslost', '$clanwarstied', $score)";
}
$sql = "INSERT INTO activeclans(id, name, location, playercount, clanlevel, warswon, warslost, warstied, score)
VALUES " . implode(', ', $values);
mysqli_query($con, $sql);
$inserts += count($values);
You are not resetting $pointsvar = 50000; when the second loop is completed. I would expect that the second loop would therefore only run on the first time round the outer loop. So
<?php
ini_set('max_execution_time', 0);
include("../includes/mysqli.php");
$pointsvar = 50000;
$inserts = 0;
$locationvar = 32000006;
while($locationvar <= 32000260){
while($pointsvar >= 20000){
$url = "http://185.112.249.77:9999/Api/Search?search=&level=0&min=1&max=50&points=$pointsvar&loc=$locationvar";
$jsondata = file_get_contents($url);
$data = json_decode($jsondata, true);
$in=$data['clanList'];
$results = $data['results']; //max is 64
$i = 0;
while($i + 1 <= $results){
$clanid = $in[$i]['id'];
$clanname = mysqli_real_escape_string($con,$in[$i]['name']);
$clanplayerCount = $in[$i]['playerCount'];
$clanwarswon = $in[$i]['warsWon'];
$clanwarslost = $in[$i]['warsLost'];
$clanwarstied = $in[$i]['warsTied'];
$clanLocation = mysqli_real_escape_string($con,$in[$i]['clanLocation']);
$clanlevel = $in[$i]['level'];
$score = $in[$i]['score'];
$sql = "INSERT INTO activeclans(id, name, location, playercount, clanlevel, warswon, warslost, warstied, score)
VALUES('$clanid', '$clanname', '$clanLocation', '$clanplayerCount', '$clanlevel', '$clanwarswon', '$clanwarslost', '$clanwarstied', $score)";
mysqli_query($con, $sql);
$i++;
$inserts++;
}
$pointsvar = $pointsvar-500;
sleep(1);
}
$locationvar++;
// RESET The pointsvar counter
$pointsvar = 50000;
sleep(1);
}
echo "Inserted $inserts";
?>
I have a MySQL statement that I want to execute and inside this statement I would like to include a for loop to define the columns that data will be entered into etc.
The code I currently have is
$stmt = $conn->prepare('INSERT into DATA ('.
for($i = 0; $i < count($columns); $i++) {
echo $columns[$i];
}
.') VALUES ('.
for($i = 0; $i < count($columns); $i++) {
echo ':'.$columns[$i].' , ';
}
.')');
Obviously this doesn't work but if it was to work also in the second for statement it echos a comma at the end of each loop, which will cause an error for the last loop so also is there a way to fix this to?
Thanks in advance!
Use the join/implode function:
$params = array_map(function($var){return ':'.$var;}, $columns);
$sql = 'INSERT into DATA ('.join(',', $columns).') VALUES ('.join(',', $params).')';
$stmt = $conn->prepare($sql);
Another approach using implode:
$sql = "INSERT into DATA (`" . implode('`,`', $columns) . "`) values (:" . implode(',:', $columns) . ")"
$stmt = $conn->prepare($sql);
Example result:
// Input array
$columns = array('A', 'B', 'C');
// Output
INSERT into DATA(`A`,`B`,`C`) values (:A,:B,:C)
You should create the query outside of the prepare() function to make it easier.
Something like that would be better/clearer :
$count = count ($columns); // Avoid using count in your loop init (Performances)
$query = 'INSERT INTO DATA (' .
for($i = 0; $i < $count; $i++) {
$query .= $columns[$i];
}
$query .= ') VALUES (';
for($i = 0; $i < $count; $i++) {
if ($i != $count - 1) $query.= ':'.$columns[$i].' , ';
else $query .= ':'.$columns[$i]; // No coma for the last value
}
$query .= ')';
$stmt = $conn->prepare($query);