I use of codeigniter. how can insert several value (array) <input name="ok[]"> in database and get they of database. (what is the best way?)
type rows in database is "VARCHAR" and "utf-8".
<input type="text" name="ok[]">
Values: (This is just one example of what I want)
ok[1] => hi, how are you?, 5426, assd, 54568
ok[2] => what, your name?, 548568a, 684a45ade
ok[3] => asdwhasdat, fine, 85as454se, 4e748sd
ok[3] => 85as454se, George, asdwhasdat, 4e748sd
Etc. ....
Now after it, i want inputs ok[1], ok[2], ok[3] together insert in a row (column) on database.
NEXT:
I want get (the second part) they of database and each they in foreach as:
how are you? fine your name? George
how is it?
$inserts = array();
foreach ($_REQUEST['ok'] as $key => $val)
{
$parts = explode(',', $val);
$inserts[] = "('" . mysql_real_escape_string($parts[1]) . "')";
}
$inserts = implode(',', $inserts);
$sql = "INSERT INTO yourtable (fieldname) VALUES $inserts;";
$result = mysql_query($sql) or die(mysql_error());
Related
For example the message is in this format:
PDP=222, APC=423, FTC=789
My database table columns are: PDP, APC FTC. I want a script that would copy the value of each column respectively, from the inbox of the modem usb and store it into corresponding column in a database.
For example for PDP column it would copy the value assigned to PDP form the message (i.e 222) and store it in the database table and do the same for the rest of the columns.
Thanks in advance
You can use expode() and implode() functions for that in order to build your query:
<?php
$query = '';
$qParams = [];
$qValues = [];
$message = 'PDP=222, APC=423, FTC=789';
$arr = explode(',', $message);
foreach ($arr as $value) {
$tmp = explode("=", $value);
$qParams[] = $tmp[0];
$qValues[] = $tmp[1];
}
$query = "
INSERT INTO modem_table
(" . implode(",", $qParams) . ")
VALUES
('" . implode("','", $qValues) . "')";
echo $query;
?>
Output query:
INSERT INTO modem_table (PDP, APC, FTC) VALUES ('222','423','789')
I have 3 input that can be added dynamically. So the name of input is array, like:
<input type="text" name="qty1[]">
<input type="text" name="qty2[]">
<input type="text" name="qty3[]">
(Each of these input texts can be generated by javascript)
In my php file, I get them and want to insert to database (my controller in codeigniter):
$address = $this->input->post("qty1");
$LocX = $this->input->post("qty2");
$LocY = $this->input->post("qty3");
In my db part, where I want to use foreach and add to database:
Edit
foreach ($address as $key) {
// I want to add $LocX and $LocY to the table
// LocX and LocY are column names.
$query = $this->db->query("INSERT INTO address (Comp_ID, Value, LocX, LocY)
VALUES(?, ?)", array($Comp_ID, $key ,? ,?));
}
I want to add all of them into foreach as parameter. As I searched it's not possible. What shoud I do? Thanks.
Edit2
The result of arrays, for example for $LocX :
Array
(
[0] => test1
[1] => test2
[2] => test3
)
You can use the index in the foreach to get to the other elements. But you need to carefully check if the index value exists in the other arrays (isset check)
For example:
foreach ($address as $key => $value) {
if(isset($LocX[$key], $LocY[$key]) {
$a_LocX = $LocX[$key]; // This will be the locx of the address
$a_LocY = $LocY[$key]; // This will be the locy of the address
// Change your query to fit the table and fill in the locx and y.
$query = $this->db->query("INSERT INTO address (Comp_ID, Value)
VALUES(?, ?)", array($Comp_ID, $key));
}
You can also use a for loop for this.
$address = $this->input->post("qty1");
$LocX = $this->input->post("qty2");
$LocY = $this->input->post("qty3");
$n=count($address);
for($i=0;$i<$n;$i++){
$a=$address[$i];
$x=$locX[$i];
$y=$locY[$i];
//insert here
}
I will suggest you to use Codeigniter syntax, and this will make your insert work,
foreach($address as $k => $v)
{
$insert = array(
'Comp_ID' => $Comp_ID,
'Value' => $v,
); // insert array
if(in_array($LocX[$k], $LocX)) // existance check
$insert = array_merge($insert, array('LocX' => $LocX[$k]));
if(in_array($LocY[$k], $LocY)) // existance check
$insert = array_merge($insert, array('LocY' => $LocY[$k]));
$this->db->insert('address', $insert); // No need to write full query
}
I have researched several related question in this forum and google, Kindly assist . I am trying to insert some values into database from several arrays stored in session. I also have some single values stored in some session also which i want to insert into multiple rows of dbase table.
//First, I recall the values stored in sessions from previous pages into the current page as below.
//take note of the comment in front of the sessions and All array contains the same number of values except for the first two sessions.
$ticketid="t".date('dmyHis').mt_rand (1000,9999);
$bettime= date('d/m/y H:i');
$_SESSION['bettime']=$bettime;//Not array, contains single value
$_SESSION['ticketid']=$ticketid;//Not array, Contains single value
$_SESSION['gamecode'];//array
$_SESSION['starttime'];//array
$_SESSION['optioncode']//array
$_SESSION['home'];//array
$_SESSION['away'];//array
$_SESSION['odd'];//array
Here, I connected to dbase. //Works fine.
require('gumodb.php');
Here i try to start a loop using one array session as key
foreach($_SESSION['starttime'] as $ro => $col){
mysql_query("INSERT INTO reg_bet (bettime, ticketid,matchcode,starttime,home,away,optionodd,optioncode) VALUES('$_SESSION[bettime]','$_SESSION[ticketid]','$_SESSION[gamecode]', '$_SESSION[starttime]','$_SESSION[home]','$_SESSION[away]','$_SESSION[odd]','$_SESSION[optioncode]' ) ")
or die(mysql_error());
}
It returns Notice: Array to string conversion in C:\xampp\htdocs\gumo\consel.php on line 61
EDIT QUESTION
I am trying to achieve something like this.
foreach($_SESSION['gamecode'] as $gc => $gcvalue && $_SESSION['starttime'] as $st =>$stvalue && $_SESSION['optioncode'] as $oc => $ocvalue ){
mysql_query("INSERT INTO reg_bet (matchcode,starttime,optioncode) VALUES('$gcvalue','$stvalue','$ocvalue') ")
or die(mysql_error()); }
$x = json_encode($_SESSION);
$query = "INSERT INTO ".$TABLE_NAME data "VALUES ("$x");";
$mysqli->query( $query );
Encode the session array into a single string and insert in to the table on a row of data.
When you fetch the same data use json_decode to convert the string into array.
Assuming the arrays in the $_SESSION variable are numeric, you could try something like this:
for ($i = 0; $i < $max_index_count; $i++) {
$query = "INSERT INTO ".$TABLE_NAME;
$query += "VALUES (".$_SESSION['index'][$i].");";
$mysqli->query( $query );
}
The above is pseudo code, but the problem is you are trying to use an array as a string. The $_SESSION variable is a multidemsional array, therefore, specify two ibdexes.
After so many trials, i was able to get it done with this
$ticketid="t".date('dmyHis').mt_rand (1000,9999);//ticket id generateed
$bettime= date('d/m/y H:i');
$_SESSION['bettime']=$bettime;
$_SESSION['ticketid']=$ticketid;
$_SESSION['gamecode'];
$_SESSION['starttime'];
$_SESSION['optioncode'];
$_SESSION['home'];
$_SESSION['away'];
$_SESSION['odd'];
require('gumodb.php');
foreach ($_SESSION['gamecode'] as $index => $value)
{
$ge = $_SESSION['gamecode'][$index];
$se = $_SESSION['starttime'][$index];
$oe = $_SESSION['optioncode'][$index];
$he = $_SESSION['home'][$index];
$ay = $_SESSION['away'][$index];
$od = $_SESSION['odd'][$index];
This post the arrays and non array into table row and display
mysql_query("INSERT INTO reg_bet (matchcode,ticketid,bettime,starttime,home,away,optionodd,optioncode) VALUES('$ge','$ticketid','$bettime','$se','$he' ,'$ay','$od' ,'$oe' ) ")
or die(mysql_error());
echo $_SESSION['gamecode'][$index] .'-'. $_SESSION['starttime'][$index].'- '. $_SESSION['optioncode'][$index].' -'. $_SESSION['home'][$index].'- '. $_SESSION['away'][$index].'- '. $_SESSION['odd'][$index].$bettime.' -' .$ticketid.'</br>' ;
}
Thanks for your contributions.
sorry for the complicated heading.i am doing learning php and got stuck.i have a database table table_name
id(primary key) name ip
1 a 192.168.0.1,192.168.0.5,171.87.65 //separated by comma's
2 b 192.168.0.1,175.172.2.6,164.77.42
now i want to add an array of values ip[0] and ip[1] coming from a two different text-area to the end of the ip's of each name and just updating the ip column of each row.so it will just append new values with previous one.
name a<textarea rows="4" cols="40" name="ip[]"></textarea>
name b<textarea rows="4" cols="40" name="ip[]"></textarea>
<input type="submit" />
this is how its inserted
if(isset($_POST['submit'])) {
$ip_details = $_POST['ip'];
$values = array(
array('id' => '"1"', 'name' => '"a"', ip => '"'.$ip_details[0].'"'),
array('id' => '"2"','name' => '"b"', ip => '"'.$ip_details[1].'"'),
);
$columns = implode(', ', array_keys($values[0]));
foreach($values as $value) {
$value = implode(', ', $value);
$statement = "INSERT INTO `center_listt` (id,name,ip) VALUES ($value)";
$res=mysql_query($statement);
echo "success";
}
}
i need to update each rows of namea and b with new values coming from text-area with previous values.
i am thinking of array_push after fetching ip from table in while loop but could not really do it.warning: array_push expects parameter 1 to be array integer given its because the $row['ip'] fetched in while loop is not valid array which array_push expects.
and it will only add new values in different new rows each time which i don't want.can someone please help what to do.
<?php
if(isset($_POST['submit'])) {
//print_r($ips); die;
$i = 0;
foreach($_POST['ip_details'] as $ipaddr) {
$ips[$i] = $ips[$i].$ipaddr;
$i++;
}
$r = 1;
foreach($ips as $ip){
//echo "UPDATE center_listt SET ipdetails = '$ip' WHERE `id_center` = '$r'"; die;
if(mysql_query("UPDATE center_listt SET ipdetails = '$ip' WHERE `id_center` = '$r'")) echo "IP Address Updated <br />";
else echo 'error occurred';
$r++;
}
}
$sql="select * from center_listt";
$res=mysql_query($sql);
if(!$res) {
die('could not connect'.mysql_error());
}
while($row=mysql_fetch_assoc($res))
{
echo $row['ipdetails']; }
?>
its a bad practise to insert form values from array.you can fetch it from db bcoz if in future you want to add new form values you need to rewrite again with array values while fetching from db will only need you to insert new values in db.
my query will add ip's in your specific column in a single row only updating the ip with new values.
You could do this:
$values = array(...); // WARNING: escape `$ip_details` here!!
$to_insert = array();
foreach($values as $row) {
$to_insert[] = "(".implode(", ",$row).")";
}
$statement = "insert into `center_listt` (`id`, `name`, `ip`)
values ".implode(", ",$to_insert)."
ON DUPLICATE KEY UPDATE `ip`=concat(`ip`,',',values(`ip`))
";
mysql_query($statement);
This will perform a multi-insert (far more efficient than individual queries), and when you try to insert the same ID twice it will instead concatenate the values.
It should be noted that this is bad database design, though :p
Hello i have a JSon array like this
Array
(
[NTAy] => ALFA ROMEO
[NTA0] => AUDI
[NTEx] => BMW
[NjAy] => CHEVROLET
[NTEz] => CHRYSLER
[NTE0] => CITROËN
[NjAz] => DACIA
[NjQ5] => DAEWOO
[NTE3] => DAIHATSU
)
and I have to insert it in a database row by row, I used
foreach ($mata as $marca_id => $marca_name){
$line = $line. "','" . $marca_id . "','". $marca_name . "','". $marca_name;
}
$line = substr($line, 0, strlen($line)-1);
$values[$i] = $line;
++$i;
$values =implode ( $values);
echo $values;
echo "<br />";
but at the mysql insert
$data = mysql_query(" INSERT INTO jos_virtuemart_categories_ro_ro (virtuemart_category_id, category_name, slug)
VALUES " .$values)
I get an error and can't get it to work. Can someone help me please?
foreach ($mata as $marca_id => $marca_name) {
$id = intval($marca_id);
$name = mysql_real_escape_string($marca_name);
$values = "$id, '$name', '$name'";
mysql_query("INSERT INTO jos_virtuemart_categories_ro_ro (virtuemart_category_id, category_name, slug) VALUES ($values)");
}
Why not use prepared statements? Especially if you're taking user generated data and entering it into your database.
That and it looks like you're final SQL query will look like this
INSERT INTO jos_virtuemart_categories_ro_ro (virtuemart_category_id, category_name, slug)
VALUES 'NTAy','ALFA ROMEO','ALFA ROMEO','NTA0','AUDI','AUDI' etc
You would have to break this up into multiple queries