PHP - for statement in a string - php

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);

Related

Database Error when insert data with loop

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.

PDO - SQL not working without any warning [duplicate]

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

Insert an array in the database

I want to insert an array in the database. The array can be changed all the time. I want different rows in the database.
My code:
$var = file_get_contents("test2.txt");
$test = preg_replace('/\\\\/', '', $var);
$poep = explode(" ", $test);
Yeah, there is no database connection, because I want to know how to 'split' the array to insert it in the database.
I have tried this:
foreach($poep as $row) {
$row = $mysqli->real_escape_string($row);
if($mysqli->query("insert into data('array') VALUES ($row)") == false){
echo 'Doesnt works!';
}
It returns 'Doesnt works', so I think there is a problem with query?
#NadirDev Hi. Assuming that you are using Core PHP programming. After exploding the string by the space, run foreach loop and then insert individual rows. Look at this rough code to get idea:
foreach($poep as $row) {
// $row now contains one word. Add that in database.
$row = mysql_real_escape_string($row);
$query = mysql_query("insert into tableName('fieldName') VALUES ($row)");
}
here's some code I wrote. It processes a CSV file and stores separate rows into a db table (difference is just that you have a TXT file). It does the mysql insertion in batches of 250 rows. Hope it can help you!
// read all input rows into an array
echo "Processing input..<br /><br />";
$row = 0;
$input = array();
if (($handle = fopen($file['tmp_name'], "r")) !== FALSE) {
while (($data = fgetcsv($handle, 0, ",")) !== FALSE) {
$num = count($data);
for ($c=0; $c < $num; $c++) {
$input[$row][] = addslashes($data[$c]);
}
$row++;
}
fclose($handle);
}
$count = 0;
$q = "INSERT INTO `inputs` (`keyword`, `percent`, `link`, `added_on`) VALUES ";
foreach ($input as $inp) {
$q .= "('" . addslashes($inp[0]) . "', '" . addslashes($inp[1]) . "', '" . addslashes($inp[2]) . "', '" . date('Y-m-d H:i:s') . "'), ";
$count++;
if ($count >= 250) {
$q = substr($q, 0, -2);
$q = mysqli_query($con, $q);
$q = "INSERT INTO `inputs` (`keyword`, `percent`, `link`, `added_on`) VALUES ";
$count = 0;
}
}
if ($count > 0) {
$q = substr($q, 0, -2);
$q = mysqli_query($con, $q);
}
echo "Successfully added " . count($input) . " rows to the input list.";

array data to mysql

I need to parse the following code and process the resulting data.
foreach($job as $x=>$x_value)
{
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
The above code is returning the following as expected.
Key=vca_id, Value=20130<br>Key=uuid, Value=3c87e0b3-cfa<br>Key=originate_time, Value=2013-03-15 14:30:18<br>
What I need to do is to put the values in mysql database. So the insert statement would look something like this...
insert into test.master_table (vca_id, uuid, originate_time) values ('20130', '3c87e0b3-cfa', '2013-03-15 14:30:18')
What is the correct way to save the array values to mysql database?
<?php
mysql_query("insert into test.master_table(vca_id, uuid, originate_time)values('".$job['vca_id']."','".$job['uuid']."','".$job['originate_time']."')");
?>
Well i will recommend implode
$keys = array();
$values = array();
foreach($job as $x => $x_value)
{
$keys[] = $x;
$values[] = $x_value;
}
$query = 'INSERT INTO test.master_table' . '('.implode(',',$keys) .') VALUES (' .implode(',',$values) . ')';
You can try this
$temp_value_arr = array();
$query = "INSERT into test.master_table SET ";
foreach($job as $x=>$x_value)
{
$query .= "$x = '$x_value',";
}
$query = rtrim($query, ',');
mysql_query($query);

SQL array values in php

Hi I'm really new to php/mysql.
I'm working on a php/mysql school project with 39 fields all in all in a single table.
I want to shorten my codes especially on doing sql queries.
$sql = "INSERT into mytable ('field_1',...'field_39') Values('{$_POST['textfield_1']}',...'{$_POST['textfield_39']}')";
I don't know how to figure out this but , i want something like:
$sql = "Insert into mytable ("----all fields generated via loop/array----") Values("----all form elements genrated via loop/array---")";
Thank you in advance.
<?php
function mysql_insert($table, $inserts) {
$values = array_map('mysql_real_escape_string', array_values($inserts));
$keys = array_keys($inserts);
return mysql_query('INSERT INTO `'.$table.'` (`'.implode('`,`', $keys).'`) VALUES (\''.implode('\',\'', $values).'\')');
}
?>
For example:
<?php`enter code here`
mysql_insert('cars', array(
'make' => 'Aston Martin',
'model' => 'DB9',
'year' => '2009',
));
?>
try this it i thhink it il work
You could use implode:
$sql = "
INSERT into mytable
('" . implode("', '", array_keys($_POST) . "')
VALUES
('" . implode("', '", $_POST . "')";
(This assumes the indices of the POST array are also the names of the db table fields)
However, this is extremely insecure since you would directly insert post data into the database.
So the least you should do beforehand is escape the values and make sure they are ok/valid table fields:
// Apply mysql_real_escape_string to every POST value
array_walk($_POST, "mysql_real_escape_string");
and
// Filter out all POST values with invalid indices
$allowed_fields = array('field_1', 'field_2', /* ... */ );
$_POST = array_intersect_key($_POST, $allowed_fields);
<?php
$sql = "Insert into mytable (";
for ($i = 1; $i < 40; $i++) {
if ($i == 39) {
$sql .= "field_$i";
} else {
$sql .= "field_$i,";
}
}
$sql .= "Values(";
for ($i = 1; $i < 40; $i++) {
if ($i == 39) {
$sql .= "'" . $_POST[textfield_$i] . "'";
} else {
$sql .= "'" . $_POST[textfield_$i] . "',";
}
}
?>
< ?php
$sql = "Insert into mytable (";
for ($i = 1; $i < 40; $i++) {
if ($i == 39) {
$sql .= "field_$i";
} else {
$sql .= "field_$i,";
}
}
$sql .= "Values(";
for ($i = 1; $i < 40; $i++) {
if ($i == 39) {
if(is_int($POST[textfield$i])){
$sql .= $POST[textfield$i];
}
else{
$sql .= "'" . $POST[textfield$i] . "'";
}
} else {
if(is_int($_POST[textfield_$i])){
$sql .= $_POST[textfield_$i] .",";
}
else{
$sql .= "'" . $_POST[textfield_$i] . "',";
}
}
}
?>
it will work for numeric values. you can insert numeric values in single quotes but some times it will create some problems

Categories