updating each row with previous values plus current values - php

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

Related

How to pass multiple variables in foreach php

I'd like to pass multiple variables in a foreach loop to add the value from $array_sma[] into my database. But so far I can only insert the value from $short_smas, while I'd also like to insert the values from $mid_smas. I have tried nested foreach but it's multiplying the values.
$period = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15);
$sma = array(6,9);
foreach ($sma as $range) {
$sum = array_sum(array_slice($period, 0, $range));
$result = array($range - 1 => $sum / $range);
for ($i = $range, $n = count($period); $i != $n; ++$i) {
$result[$i] = $result[$i - 1] + ($period[$i] - $period[$i - $range]) / $range;
}
$array_sma[] = $result;
}
list($short_smas,$mid_smas)=$array_sma;
foreach ($short_smas as $short_sma) {
$sql = "INSERT INTO sma (short_sma)
VALUES ('$short_sma') ";
if ($con->query($sql) === TRUE) {
echo "New record created successfully<br><br>";
} else {
echo "Error: " . $sql . "<br>" . $con->error;
}
}
The code in my question works fine i.e. the value from the first sub array ($short_smas) of $array_sma[] gets inserted into the column short_sma of my msql database. The problem I have is when I try to insert the second sub array $mid_smas (see list()) from $array_sma[] in my second column of my database call mid_sma.
I think this is closed to what I want to achieve but still nothing gets inserted in the DB, source: php+mysql: insert a php array into mysql
I don't have any mysql syntax error.
$array_sma[] = $result;
$sql = "INSERT INTO sma (short_sma, mid_sma) VALUES ";
foreach ($array_sma as $item) {
$sql .= "('".$item[0]."','".$item[1]."'),";
}
$sql = rtrim($sql,",");
Main problem is that $short_smas and $mid_smas have different size. Moreover they are associative arrays so either you pick unique keys from both and will allow for empty values for keys that have only one value available or you pick only keys present in both arrays. Code below provides first solution.
// first lets pick unique keys from both arrays
$uniqe_keys = array_unique(array_merge(array_keys($short_smas), array_keys($mid_smas)));
// alternatively we can only pick those present in both
// $intersect_keys = array_intersect(array_keys($short_smas),array_keys($mid_smas));
// now lets build sql in loop as Marcelo Agimóvel sugested
// firs we need base command:
$sql = "INSERT INTO sma (short_sma, mid_sma) VALUES ";
// now we add value pairs to coma separated list of values to
// insert using keys from prepared keys array
foreach ($uniqe_keys as $key) {
$mid_sma = array_key_exists($key, $mid_smas)?$mid_smas[$key]:"";
$short_sma = array_key_exists($key, $short_smas)?$short_smas[$key]:"";
// here we build coma separated list of value pairs to insert
$sql .= "('$short_sma', '$mid_sma'),";
}
$sql = rtrim($sql, ",");
// with data provided in question $sql should have string:
// INSERT INTO sma (short_sma, mid_sma) VALUES, ('3.5', ''), ('4.5', ''), ('5.5', ''), ('6.5', '5'), ('7.5', '6'), ('8.5', '7'), ('9.5', '8'), ('10.5', '9'), ('11.5', '10'), ('12.5', '11')
// now we execute just one sql command
if ($con->query($sql) === TRUE) {
echo "New records created successfully<br><br>";
} else {
echo "Error: " . $sql . "<br>" . $con->error;
}
// don't forget to close connection
Marcelo Agimóvel also suggested that instead of multiple inserts like this:
INSERT INTO tbl_name (a,b,c) VALUES (1,2,3);
its better to use single:
INSERT INTO tbl_name
(a,b,c)
VALUES
(1,2,3),
(4,5,6),
(7,8,9);
That's why I append value pairs to $sql in foreach loop and execute query outside loop.
Also its worth mentioning that instead of executing straight sql its better to use prepared statements as they are less prone to sql injection.

Can i use Multiple Array in a foreach loop?

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.

Divide array contents on multiple lines MySQL table with PHP

I almost managed to split the different arrays and to prepare them in the table in the MySQL database, I'll explain the situation:
On the main page, the user has the ability to add and remove rows in a table. The table for each line carries with it these inputs:
input1.name = "product[]";
input2.name = "seller[]";
input3.name = "description[]";
input4.name = "quantity[]";
input5.name = "priece[]";
so if the user inserts two rows in each array will be included descriptions of two products, for example:
product: "PS3", "PS4";
seller: "AMAZON", "SONY";
description: "100Gb", "200Gb";
quantity: "1", "2";
price: "100", "200";
This is the layout table:
http://www.mediafire.com/view/ux0su8ssdixfmgc/Cattura2.JPG
The problem arises. I capture the data entered via a post, but I can't distribute these data on several lines. I want you to PS3 both into the first row of MySQL table, and PS4 in the second row of the table. Until now arrays are instantiated only on the first line, in this way, however, there is only one product. It is therefore necessary to prepare each box in the appropriate row of the array. I do not know if I was clear, but I would like to achieve something like this:
http://www.mediafire.com/view/d6f6ahy834jv0p2/Cattura.JPG
Obviously, the data in table I've entered manually and not through code. Was it right for you to understand.
This is the code that I currently use to send multiple arrays on different lines, but it doesn't work.
if(isset($_POST['sending']))
{
if($_POST['sending'] == "save")
{
$row_data = array();
foreach($_POST['sending'] as $key => $value)
{
$product=mysqli_real_escape_string($con,($_POST['product'][$row]));
$seller=mysqli_real_escape_string($con,($_POST['seller'][$row]));
$description=mysqli_real_escape_string($con,($_POST['description'][$row]));
$quantity=mysqli_real_escape_string($con,($_POST['quantity'][$row]));
$priece=mysqli_real_escape_string($con,($_POST['priece'][$row]));
$user=mysqli_real_escape_string($con,($_POST['user'][$row]));
$row_data[] = "('$product', '$seller', '$description','$quantity', '$priece', '$user')";
}
if (!empty($row_data))
{
$sql = 'INSERT INTO test(product,seller,description,quantity,priece,user) VALUES '.implode(',', $row_data);
$result = mysqli_query($con, $sql );
if ($result)
echo 'ADD COMPLETE!: ' . mysqli_affected_rows($con);
else
echo 'ERROR' ;
}
} // if ($_POST['sending'] == "save")
} // if (isset($_POST['sending']))
}//close method
if I understood it well this is how it should work
if(isset($_POST['sending']))
{
if($_POST['sending'] == "save")
{
$row_data = array();
foreach($_POST['sending'] as $key => $value)
{
$product=mysqli_real_escape_string($con,($_POST['product'][$row]));
$seller=mysqli_real_escape_string($con,($_POST['seller'][$row]));
$description=mysqli_real_escape_string($con,($_POST['description'][$row]));
$quantity=mysqli_real_escape_string($con,($_POST['quantity'][$row]));
$priece=mysqli_real_escape_string($con,($_POST['priece'][$row]));
$user=mysqli_real_escape_string($con,($_POST['user'][$row]));
array_push($row_data, "('$product', '$seller', '$description','$quantity', '$priece', '$user')");
}
foreach($row_data as $value){
if (!empty($value))
{
$sql = 'INSERT INTO test(product,seller,description,quantity,priece,user) VALUES '.$value;
$result = mysqli_query($con, $sql );
if ($result)
echo 'ADD COMPLETE!: ' . mysqli_affected_rows($con);
else
echo 'ERROR' ;
}
} // if ($_POST['sending'] == "save")
} // if (isset($_POST['sending']))
}//close method

insert an array into mysql database

I have the following array which I would like to insert into mysql database.
Item[0] = Soccer
Item[1] = Rugby
Item[2] = Football
Item[3] = Netball
Item[4] = Hockey
I am using the following function to insert into the database, located in functions.php:
//Capture items
function item($register_data)
{
array_walk($register_data,'array_clean');
$fields = ' '.implode(',',array_keys($register_data)).' ';
$data = '\''.implode('\',\'',$register_data).'\'';
//Insert user Data into the database
$query = "INSERT INTO items ($fields) VALUES ($data)";
mysql_query($query);
}
Now this is how I insert:
for($i =0;$i<4;$i++)
{
$item = array($i = item[i]);
}
//Call the function to insert into the database
item($item);
This method doesn't seem to work. Please assist
PHP has a built in serialize & deserialize functions (http://php.net/manual/en/function.serialize.php) for that. You can pass any object or array to it, and it will return a serialized string, which you can store in a single field in the database.
Since your items table has two columns, one of which is id (auto increment) you're going to want to skip over it and only specify the second column ItemName. This is described in the mysql documentation on this page.
Lets say you want to insert 5 sports in this table:
$sports[0] = "Soccer";
$sports[1] = "Rugby";
$sports[2] = "Football";
$sports[3] = "Netball";
$sports[4] = "Hockey";
You'll want the query to look something along these lines:
INSERT INTO items (ItemName) VALUES ('Soccer'), ('Rugby'), ('Football'), ('Netball'), ('Hockey');
The code would look something like this:
function insert($insert_data)
{
$fields = implode(', ', $insert_data);
$data = '(\''.implode('\'), (\'', $insert_data).'\')';
//mysql_query("INSERT INTO items (ItemName) VALUES $data;");
echo "INSERT INTO items (ItemName) VALUES $data;";
}
$sports = array();
$sports[0] = "Soccer";
$sports[1] = "Rugby";
$sports[2] = "Football";
$sports[3] = "Netball";
$sports[4] = "Hockey";
insert($sports);
You may also want to sanitize the strings first and take a look at mysqli since mysql is pretty outdated.

insert value array in database and next get(each) part of it?

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

Categories