Store Session Array in Database - php

I have the array-ed session....
$_SESSION['Names'] = array (11,15,26);
$_SESSION['Location'] = array (35,42,10);
and I want to store them in my database...
$que = "Insert into tblpeople (DateTimePosted, first, second, third) VALUES(now(),'$_SESSION['Names'][0], $_SESSION['Location'][0])','$_SESSION['Names'][1], $_SESSION['Location'][1])','$_SESSION['Names'][2], $_SESSION['Location'][2])')";
$exec = mysql_query($que);
After Saving, my database (tblpeople) shows the following values:
DateTimePosted: 2014-01-03 16:23:02
first: Array[0],Array[0]
second: Array[1],Array[1]
third: Array[2],Array[2]
Instead, I want my output to be...
DateTimePosted: 2014-01-03 16:23:02
first: 11,35
second: 15,42
third: 26,10
What's wrong?

To expand multidimensional arrays in a string, you need to wrap them in curly braces:
$que = "Insert into tblpeople (DateTimePosted, first, second, third)
VALUES(now(),
'{$_SESSION['Names'][0]}, {$_SESSION['Location'][0]}',
'{$_SESSION['Names'][1]}, {$_SESSION['Location'][1]}',
'{$_SESSION['Names'][2]}, {$_SESSION['Location'][2]}')";
You also had some extra parentheses in the values.
However, this seems like a pretty strange way to store data into a database. Why do you have two values separated by commas in each column, rather than splitting each into separate columns? And why are you storing array elements into different columns, rather than using separate tables with each value in a row?

use this function
$x=serialize($_SESSION['Names']);
it return a string that you can save any where
and this function reverse it
$_SESSION['Names']=unserialize($x);

Try this
<?php
session_start();
$_SESSION['Names'] = array (11,15,26);
$_SESSION['Location'] = array (35,42,10);
$refNumbers = $_SESSION['Names'];
$partIds = $_SESSION['Location'];
$combined = array();
foreach($refNumbers as $index => $refNumber) {
if(!array_key_exists($index, $partIds)) {
throw OutOfBoundsException();
}
$combined[] = array(
'Names' => $refNumber,
'Location' => $partIds[$index]
);
}
print_r($combined);
$combine1 = implode(",",$combined[0]);
$combine2 = implode(",",$combined[1]);
$combine3 = implode(",",$combined[2]);
$que = "insert into tblpeople (DateTimePosted, first, second, third) VALUES(now(),'$combine1','$combine2','$combine3')";
//$exec = mysql_query($que);
?>

Related

perform two different fetch on the same query result

I have this query:
$all = $dbh->query("SELECT DISTINCT movimenti.nome, SUM(movimenti_carta.importo)
FROM movimenti_carta JOIN movimenti ON movimenti_carta.movimento=movimenti.id
WHERE month(data)='$mese' AND year(data)='$anno' GROUP BY movimenti.nome");
It retrieves two columns from my db. What I want to do is to put each column in a separate array.
If I do:
$labels=$all->fetchAll(PDO::FETCH_COLUMN,0);
I get the values for the first column with the format I am looking for.
I tried to do:
$values=$all->fetchAll(PDO::FETCH_COLUMN,1);
after the first fetch but $all is unset by the first fetch and the result is that $values is an empty array (I was pretty sure of this but did give it a try).
I can build the arrays in php after I fetch an array with both columns but I was wondering how to get my goal using PDO api.
Of course it will never work this way, as fetchAll() returns data only once.
The only idea I could think of is PDO::FETCH_KEY_PAIR constant:
$data = $all->fetchAll(PDO::FETCH_KEY_PAIR);
$labels = array_keys($data);
$values = array_values($data);
It feels like you are overcomplicating this. It's easily done in PHP, and if you just use PDOStatement::fetch, you don't need to worry about array manipulation; it will also be more friendly to your memory usage if you have a lot of data.
$labels = [];
$values = [];
while ($row = $all->fetch(PDO::FETCH_NUM)) {
$labels[] = $row[0];
$values[] = $row[1];
}
Maybe you could use array_column.
$all = $dbh->query("
SELECT DISTINCT movimenti.nome, SUM(movimenti_carta.importo) AS importo
FROM movimenti_carta
JOIN movimenti ON movimenti_carta.movimento=movimenti.id
WHERE month(data)='$mese'
AND year(data)='$anno'
GROUP BY movimenti.nome
");
// set of results indexed by column name
$results = $all->fetchAll(PDO::FETCH_ASSOC);
// set of values from the column 'nome'
$nomes = array_column($results, 'nome');
// set of values from the column 'importo'
$importos = array_column($results, 'importo');

passing multidimensional array to mysql using generated input fields

<?php
if (isset ($_POST['submit'])){
$name=$_POST['name'];
$sports=$_POST['sports'];
$data=array();
for($x=0,$l=count($sports); $x<$l; $x++){
$myArray = explode(',', $name[$x]);// you can use your own filter for names
foreach($myArray as $nm){
$data[]=array('name'=>$nm,'sports'=>$sports[$x]);
}
}
var_dump($data);
$query="INSERT INTO athletes (name, sports) VALUES ('".$data."')";
$result = mysqli_query($dbc, $query);
mysqli_free_result( $result);
}
?>
getting error array to string conversion.
hot do i pass that in the database in separate rows.
the output is working wonderfully when i dump just the way i want it but i cant seem to get it passed to the database.
I think you don't need to make multidimensional array name[][], you just use name[] so in your PHP code it is just like,
$name=$_POST['name'];
$sports=$_POST['sports'];
$data=array();
for($x=0,$l=count($sports); $x<$l; $x++){
$myArray = explode(',', $name[$x]);// you can use your own filter for names
foreach($myArray as $nm){
$data[]=array('name'=>$nm,'sports'=>$sports[$x]);
}
}
var_dump($data);
Demo
You can change $data while inserting in database like,
$data[]='("'.trim($nm).'","'.trim($sports[$x]).'")';
And after your loop ends you can create query like,
$sql ="INSERT INTO <table> (name,sports) VALUES ".implode(',',$data);
Demo with Query
You need to create separate array from post value for each row.
http://sandbox.onlinephpfunctions.com/code/c8aede27dc5675a8715be328dec6c5ea4c669522

PHP MySql Database Array update

I am trying to update one row in my database like this.
if (isset($_POST['submit'])) {
$sizes = array($_POST['size_king'],
$_POST['size_queen'],
$_POST['size_double']
);
mysqli_query($con, "UPDATE beds
SET `Available Sizes` = '$sizes'
WHERE ID = '$prod_id' "
);
}
Can anyone please help me?
I want this data to only update one row, and the data must be separated by a comma.
I am thinking maybe a FOR loop, but I'm not quite sure.
just use implode() function .
if (isset($_POST['submit'])) {
$sizes = array($_POST['size_king'],
$_POST['size_queen'],
$_POST['size_double']
);
$sizes=implode(",",$sizes);
mysqli_query($con, "UPDATE beds
SET `Available Sizes` = '$sizes'
WHERE ID = '$prod_id' "
);
}
The PHP implode function will serve your purpose.
implode joins array elements into a string separated by the glue we specify. The syntax is:
string implode ( string $glue , array $pieces )
Refer to: http://in3.php.net/manual/en/function.implode.php
Example:
<?php
$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);
echo $comma_separated; // lastname,email,phone
// Empty string when using an empty array:
var_dump(implode('hello', array())); // string(0) ""
?>
there is a catch when you create database never name your table as "Available Beds" i mean don't use space try using "AvailabaleSizes" or Available_Sizes or "availableSizes" after this change write your query like below.
($con, "UPDATE `beds` SET Available_Sizes = '$sizes' WHERE ID = '$prod_id'");

array to string conversion error, need to explode and then implode

I want to explode an array, read each value and print them back in an array...
I dont understand where i am getting wrong. Please help me..this is my code..
I am getting an array to string conversion error
$query="SELECT categories FROM shops";
$result = mysql_query($query);
while($column = mysql_fetch_assoc($result)){
$categories=explode(",",$column['categories']);
foreach($categories as $value){
$new_query="SELECT name from categories where id='$value'";
$name = mysql_query($new_query);
$name_column= mysql_fetch_assoc($name);
array_push($shops_list,$name_column);
}
}
echo implode(",",$shops_list);
$shop_list is not defined, before using it in this line array_push($shops_list,$name_column);. And, this line
array_push($shops_list,$name_column);
needs to be, as you need to mention the key name,
array_push($shops_list,$name_column['name']); //or better
$shop_list[] = $name_column['name'];
Several issues:
$name_column = mysql_fetch_assoc($name);
$name_column = $name_column['name'];
name_column is an array.
shops_list is never initialized.
You should use [] instead of array_push.
The other guys hit it on the nose, but when you did your array push on $name_column, since $name_column is an array, you end up with:
Array
(
[0] => Array
(
[name] => boo
)
)
Obviously doing an implode on that is going to not work.
That being said, what you really need to do here is not keep your category mappings as a comma delimited string in the database. Standard DB architecture dictates you use a mapping table.
Table shops
Table categories
Table shop_category_map that has shop_id and category_id
use group_concat to retrieve values. and after getting the result, use them directly for searching. like
$result_array = explode(",",$row['category']);
foreach($result_array as $ra)
{
//sql command. fetch here.
$new_query="SELECT name from categories where id='$value'";
$name = mysql_query($new_query);
$name_column= mysql_fetch_assoc($name);
$shops_list[] = $name_column;
}
try else go for better solution
// explode an array and then implode until a particular index of an array
$a = '192.168.3.250';
$b = explode('.',$a);
$ar = array();
for($i=0;$i<=2;$i++)
{
array_push($ar,$b[$i]);
}
$C = implode($ar,'.');
print_r($C);

php & mysql - loop through columns of a single row and passing values into array

I have a mysql table with columns id, f1, f2, f3, ..., f20 where id is productID and f1,...f20 are product features. Depending on each product, some might have all, none or only some columns filled.
Each column holds a delimited string like a#b#c#d where a,b,c,d are values in different languages (a=english, b=french etc)
I need to select a row by it's id, explode each column's value (f1,f2...) with '#' in order to get the language part I need and then pass the values to an array in order to use in my product spec page.
How do I loop through the fetched row (i'm using $row = my_fetch_array) and put the exploded value into a one dimension array like $specs=('green', 'M', '100', 'kids'...) etc?
PS:I know, is complicated but I cant come up with a better idea right now.
Try this:
$result = mysql_query("...");
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
$arr = array();
foreach ($row as $k=>$v)
{
$features = explode("#", $v);
$value = $features[1]; // get the specific language feature
$arr[] = $value;
}
$specs = join(", " , $arr);
}
Not sure this is the best way togo but you could define an array with your langs, then access the result by lang
<?php
$langs=array('eng'=>0,'fr'=>1,'ger'=>2,'geek'=>3);
while ($row=mysql_fetch_assoc($result)) {
$specs=explode('#',$row['f1']);
$other=explode('#',$row['f2']);
...
}
//Get lang from cookie that you could set elsewhere
$lang=(isset($_COOKIE['lang']))?$_COOKIE['lang']:'eng';
echo $specs[$langs[$lang]];
?>
My solution for how I understand you question:
// Make a MySQL Connection
$sQuery = "SELECT f1,f2,... FROM table WHERE id = ...";
$oResult = mysql_query($sQuery) or die(mysql_error());
//Fetch assoc to use the column names.
$aRow = mysql_fetch_assoc($oResult);
//Prepare the product properties array
$aProductProperties = array("English"=>array(),"French"=>array(),"Dutch"=>array());
//Loop over all the columns in the row
foreach($aRow as $sColName=>$sColVal){
//Explde the column value
$aExplodedCol = explode("#",$sColVal);
//The code below could be nicer when turned into a looped that looped over every language,
//But that would make the code less readable
$aProductProperties['English'][$sColName] = $aExplodedCol[0];
$aProductProperties['French'][$sColName] = $aExplodedCol[1];
$aProductProperties['Dutch'][$sColName] = $aExplodedCol[2];
}
//Done, you should now have an array with all the product properties in every language

Categories