How to Use foreach with 2 array variable in php - php

i have codes like this
<?php
include "assets/config/connect.php";
foreach( $_POST['nim'] as $nim ){
$kode_mk= $_POST['kode_mk'] ;
$nilai= $_POST['nilai'] ;
$tahun_akademik= $_POST['tahun_akademik'] ;
$sql = " INSERT INTO nilai (nim, kode_mk, nilai, tahun_akademik, id_nilai) VALUES ('$nim', '$kode_mk', '$nilai', '$tahun_akademik', NULL) ";
if (!mysql_query($sql)){
die('Error: ' . mysql_error());
}
}
?>
but the result is not same with my expectation
this is the result
please help me

$kode_mk = $_POST['kode_mk'];
$nilai = $_POST['nilai'];
$tahun_akademik = $_POST['tahun_akademik'];
all variables are arrays, not strings as you expect, you should
var_dump($_POST);
to see the entire structure of POST array

The Error
So assuming kode_mk, nilai, tahun_akademik are all arrays in $_POST you are trying to insert the object of an array as a string. First convert the array to a string using a function like implode().
Solution: Using PHP Implode()
$array = array('hi', 'my', 'name', 'is');
$string = implode(',', $array); // string = 'hi,my,name,is'
Implode works like this implode(glue, array) the glue is a string that is inserted between each element of the array to separate them in a string. You can use explode(delimiter, string) to then reverse the string to an array!
Example Using your code
<?php
include "assets/config/connect.php";
foreach( $_POST['nim'] as $nim ){
$kode_mk= implode(', ', $_POST['kode_mk']);
$nilai= implode(', ', $_POST['nilai']);
$tahun_akademik= implode(', ', $_POST['tahun_akademik']);
$sql = " INSERT INTO nilai (nim, kode_mk, nilai, tahun_akademik, id_nilai) VALUES ('$nim', '$kode_mk', '$nilai', '$tahun_akademik', NULL) ";
if (!mysql_query($sql)){
die('Error: ' . mysql_error());
}
}
?>
Notes:
Try Using mysqli not the mysql extension for security reasons mentioned by: #messy
Looks like you are looping over $_POST['nim'], but then pulling the same $_POST values for the columns of the database.
We could really use the format and syntax of the $_POST variable

You have to show us what your input data looks like. You can do that with print_r() or var_dump():
print_r($_POST);
From the looks of it, your form inputs are arrays (checkboxes?) and you need to either pull them together into a single string or use each one separately.
Also, there is no reason to continue to gather your POST values inside the loop if there is no change in their values. Pull them up outside the loop.
Finally, the mysql_ extension is deprecated and highly discouraged - you shouldn't be using it to write new code. You also need to validate and sanitize your data before doing any inserts. Easiest way to do the latter is parameterized queries.

Related

Getting values inside an array to the database

hi im trying to fill a database table from the code below, but afterwards it fills the table coloumn just saying "Array" is there anyway to get the values inside this array and make them print in the table.
$query_new = "INSERT INTO red_message (message) VALUES ('$attributes')";
$result = mysql_query($query_new, $link_local);
P.S i use the print_r once it returns 1.. so print_r diont work either.. can anybody help me to get the values inside this $attributes array
Do you mean the implode()?
http://php.net/manual/en/function.implode.php
Example code from php.net:
$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);
echo $comma_separated; // lastname,email,phone
try to use json_encode. If your array will be of several steps it is better to initially encode rhis array and then insert into the database. You also keep structure of the array.
Example:
$farr=array('user1'=>array('name'=>$name,'phone'=>$phone),'user2'=>array('name'=>$name,'phone'=>$phone));
$sarr=json_encode($farr);
mysql_query("Insert INTO .......");
After:
$query=mysql_query("SELECT ......");
$res=mysql_fetch_assoc($query);
$finaly=json_decode($res, true);
print_r($finaly);
This simply means that $attributes is of Array type. You should make sure that $attributes is of String type (which you can achieve with implode()) before using it in mysql_query().

Assign POST values to an array in a loop and put array into a database

I have an array containing the names of form input names:
$minmax = array('bed_min', 'bed_max', 'rec_min', 'rec_max', 'bath_min', 'bath_max', 'value_min', 'value_max');
The names are identical to the corresponding columns in a database. Instead of using an sql query like so:
$bed_min=$_POST['bed_min'];
$bed_max=$_POST['bed_max'];
$rec_min=$_POST['rec_min'];
$rec_max=$_POST['rec_max'];
$bath_min=$_POST['bath_min'];
$bath_max=$_POST['bath_max'];
$value_min=$_POST['value_min'];
$value_max=$_POST['value_max'];
$query = "UPDATE first_page SET bed_min='$bed_min', bed_max='$bed_max', rec_min='$rec_min', rec_max='$rec_max', bath_min='$bath_min', bath_max='$bath_max', value_min='$value_min', value_max='$value_max', WHERE email_address='$email' ";
Is there a way to automate all this into a smaller lump of code? I know the POST values should not be added to the query diectly, so maybe a loop to assign the POST values to a corresponding array of variables using something like:
foreach ($minmax as $var){
$var = $_POST[$var]
}
(nb i dont think this snippet will work but ive added it because I think with a bit of editing it might!)
After the list of variables have been assigned the POST values, do the update in the $query using two arrays, one with the list of values and one with the list of database columns. Again I dont know how this will work, so pointers would be helpful!
You don't really need the $minmax array of form input names since you can get those from the keys of $_POST.
If the values are all numbers, like they seem to be, then you could do it all in one line like this:
$query = "UPDATE first_page SET " . vsprintf(implode("='%d', ", array_keys($sanitized_POST))."='%d'", array_values($sanitized_POST))." WHERE email_address='$email'";
That's assuming you have already sanitized the items from $_POST into a new array named $sanitized_POST. I know you said in the above comment to ignore sanitization, but I thought I'd add it so you know I'm not suggesting to use the values straight from $_POST.
You could sanitize the $_POST array with something like this:
$sanitized_POST = array_map(function($item) {
return mysqli::real_escape_string($item);
}, $_POST);
Honestly though, you should try to come up with a solution that uses prepared statements.
On a side note, if you have the sanitized post array, then this one line will essentially do what Quixrick has done with variable variables in one of the other answers:
extract($sanitized_POST);
If you assume that all of the values in post have the same names (array keys) as your columns, then something like this could work for you:
$query = "UPDATE first_page SET ";
foreach ($_POST as $key => $var){
$query .= " $key='$var',";
}
$query = rtrim($query,',') . " WHERE email_address='$email' ";
You probably want to use 'Variable Variables' here. Basically, you'd use a double dollar sign $$ to create a variable with the name of the array value.
$_POST['bed_min'] = 'Rick';
$minmax = array('bed_min', 'bed_max', 'rec_min', 'rec_max', 'bath_min', 'bath_max', 'value_min', 'value_max');
foreach ($minmax as $var){
$$var = $_POST[$var];
}
print "<BR>BED MIN: ".$bed_min;
This outputs:
BED MIN: Rick

php array implode for insert

I'm passing an html array to php using jquery serializearray() function.
In php I can access the array using $_POST like
$a = $_POST['htmlarray']
The html array, however, is an array of arrays like so
htmlarray[] = [[1,2,3,4,5,6],[7,8,9,10,11,12],[13,14,15,16,17,18]]
I want to format the variable $a so that I can insert all the html array values in one single insert query like
INSERT INTO table
(val1, val2, val3, val4, val5, val6)
VALUES
(1,2,3,4,5,6),
(7,8,9,10,11,12),
(13,14,15,16,17,18)
I know I have to use an implode function, can anyone show how this could be done.
I'm not quite sure what an html array is, but try the following:
$a = $_POST['htmlarray'];
// unserialize $a
// build sql query up to '...VALUES '
foreach ($a as $row) {
$sql .= '(';
$sql .= implode(',', $row);
$sql .= ')',
}
This should iterate through the arrays and append all your rows to the string. Note, however, that this code does not take care of SQL Injections at all! Not to be meant for production.

how to construct a mysql query that puts quotes around strings but not numbers?

i have use function for inserting data to my sql.
the data is
function mysql_insert($table, $arr){
if($arr!=''){
$values = array_map('mysql_real_escape_string', array_values($arr));
$keys = array_keys($arr);
$q=('INSERT INTO `'.$table.'` (`'.implode('`,`', $keys).'`) VALUES (\''.implode('\',\'', $values).'\')');
//$res = mysql_query($q)OR die(mysql_error());
return $q;
}else{
return false;
}
data and query is came from :
if($crud=='insert'){
$field= array( 'col1' => 'apel',
'c0l2' => 'box1',
'col3' => 200,//integer Quantity
);
$data=mysql_insert('wh',$field);}echo json_encode($data);
and result is
= "INSERT INTO wh (col1,c0l2,col3) VALUES ('apel','box1','200')"
that col3 have value as string. i need that col3 as integer.
what wrong with this code?
In the following code :
implode('\',\'', $values)
the implode is converting the array of values to a string, separating each value by ','
and before and after the implode code, there are also quotes, which will wrap all your values with ' make it look like all the values are strings
but like octern i don't see why the query would fail, even if you are wrapping integer values with ' if the correct data type is selected in the database it should work fine
If you still want to use quates around the string but not around the integer or boolean
try the php function json_encode()
example here: http://codepad.org/Hpvzjnjc
This is happening because the command implode('\',\'', $values) is telling it to turn the array $values into a string, with single quotes and commas between each element. If you want to not put quotes around numbers, you'll need to iterate over $values with a more specific function.
However, it doesn't actually matter. If you give MySQL a string containing a number for a numeric field, it will just convert it to a number of the appropriate type. You can leave it as-is and everything should work.

concatenate string in php foreach

I should be able to figure this out, but I keep going in circles. I have a form with checkboxes. When the checkboxes are selected they tagged to be deleted.
I process those selected checkboxes with a foreach:
foreach (array_keys($_POST['checkboxselect']) as $k) {
$str .= $k.',';
}
This is my lame attempt to put the list of videos together. The sql delete I'm using is:
DELETE FROM `videos` WHERE `video_name` IN ($str)
So I'm missing lots of things here. The $str needs to have:
Only one checkbox is returned so return string with quotes (i.e. "myvideo.mp4")
Multiple checkboxes are selected so build a string with quotes and commas (i.e. "myvideo.mp4","myvideo2.mp4","myvideo3.mp4")
Thanks for the help.
Try using PHP's implode:
// Init links
$mysqliLink = mysqli_connect('host', 'user', 'password') or die('Could not connect: ' . mysqli_error());
$mysqlLink = mysql_connect('host', 'user', 'password') or die('Could not connect: ' . mysql_error());
//-----
// Prep values for query
//-----
// Only pick one of the following depending upon the mysql library you are using
// If using mysql, passing the 2nd argument is not necessary, but for
// clarity, adding it
$deleteNames = array_map('mysql_real_escape_string', array_keys($_POST['checkboxselect']), array_fill(0, count($_POST['checkboxselect']), $mysqlLink));
// If using mysqli
// This will ensure that $mysqliLink will be passed in as first arg for
// every iteration satisfying the function signature
$deleteNames = array_map('mysqli_real_escape_string', array_fill(0, count($_POST['checkboxselect']), $mysqliLink), array_keys($_POST['checkboxselect']));
//-----
// Because you are passing strings, we need to ensure each is wrapped in quotes
$deleteNames = "'" . implode("','", $deleteNames) . "'";
// Construct query using implode
$sql = sprintf('DELETE FROM `videos` WHERE `video_name` IN (%s)', $deleteNames);
-- Update --
Using Joomla APIs:
$db = &JFactory::getDBO();
// Localize and sanitize each individual value
foreach (array_keys($_POST['checkboxselect']) as $element) {
$deleteNames[] = $db->quote($element);
}
// Because you are passing strings, we need to ensure each is wrapped in quotes
// No longer true because $db->quote taking care of quoting out each name for us
$deleteNames = implode(',', $deleteNames);
// Construct query using implode
$sql = sprintf('DELETE FROM `videos` WHERE `video_name` IN (%s)', $deleteNames);
Use implode() like this:
$str = '"' . implode('","', array_keys($_POST['checkboxselect'])) . '"';
implode() will take an array and join each value in the array with the "glue" string. In this case the "glue" is "," and the array is composed of the keys in $_POST['checkboxselect']. Finally, the resulting string is wrapped in ".
This will result in your desired example string "myvideo.mp4","myvideo2.mp4","myvideo3.mp4".

Categories