How to fill session array with data from database? - php

I know this question might be very basic for someone experienced. But I'm still in the learning process so I need some help.
I want to populate a session array with data that's coming from the database. There can be multiple items in the session array. I'm trying to do it like this -
$sql = mysqli_query($con, "SELECT * FROM `purchase_info_details` WHERE `purchase_details_id` = '$pur_det_id'");
while ($row = mysqli_fetch_array($sql)) {
$data[$i]['purchase_details_id'] = $row['purchase_details_id'];
$data[$i]['cid'] = $row['id'];
$data[$i]['item_id'] = $row['item_id'];
$data[$i]['unit_id'] = $row['unit_id'];
$data[$i]['quantity'] = $row['quantity'];
$data[$i]['price'] = $row['price'];
$data[$i]['conv_rate'] = $row['conv_rate'];
$_SESSION['list1_data']['purchase_details_id'] = $data[$i];
}
FYI: purchase_details_id is the primary key. This code works partially. What I mean is I only get one row from the table in my session array but I need to get all the rows from the table that matches my SQL query.
I've been searching for a relevant example on the internet but yet to find any. I'm really stuck with it and couldn't find any solution. Please help!
Thanks!!

The problem is that your are always overwriting the same data in your session array. When your loop is finished, you will have the last row from your dataset in your session array.
To add a new row in your session array everytime you can proceed with either:
$_SESSION['list1_data'][] = $data[$i];
or if you want a specific key from your data (assuming it is unique):
$_SESSION['list1_data'][$row['purchase_details_id']] = $data[$i];

try something like this
while ($row = mysqli_fetch_array($sql)) {
$data[$i]['purchase_details_id'] = $row['purchase_details_id'];
$data[$i]['cid'] = $row['id'];
$data[$i]['item_id'] = $row['item_id'];
$data[$i]['unit_id'] = $row['unit_id'];
$data[$i]['quantity'] = $row['quantity'];
$data[$i]['price'] = $row['price'];
$data[$i]['conv_rate'] = $row['conv_rate'];
$_SESSION["db_data"][$i] = $data[$i];// or just $_SESSION[$i] = $data[$i]
}

$_SESSION['list1_data']['purchase_details_id'] = $data[$i]; always overwrite and you get only last value . use $_SESSION['list1_data'][$row['purchase_details_id']] = $data[$i];
just assign array to session when you finish your loop . like below
$_SESSION['list1_data'] = $data;
or as you say product_id is unique then why you use $i ? (use $data[$row['purchase_details_id']]['purchase_details_id'] = value , use $data[$row['purchase_details_id']]['cid'] = value etc ...)

Do this:
$_SESSION['list1_data'][$row['purchase_details_id']] = $data[$i];
This way you can directly access specific details id from the session. For example:
$row = $_SESSION['list1_data'][1]; //row for the id = 1
Pro tip: Always check if the key is set or else you will get warnings =)

make sure that you are initialize the session() method, and you can make a 2 or 3 dimensional array as you need to keep the database value as #B-and-P mention in his comments.
thanks

Related

while loop into in array

What am I trying to do is collect data from a while loop, store it into a variable. Then later in my code I see if some variable is equal to one of the values in the array and then to echo out the two other column values I got from the while loop but equal to the row that the value came from. I have tried a bunch different things and am so close but cant get it exactly.
while($row = mysql_fetch_assoc($query)){
$team[] .= "{$row['team']}";
$winslosses .= "({$row['wins']} - {$row['losses']})";
}
this returns something like
$team = (bears, badgers, wildcats)
$winslosses = ((42-24), (55-23), (32-21))
Then later in my code I want to see if its equal to a value in the array then echo $winslosses.
if(in_array(bears, $team) ) {echo '$winslosses';}
This shows all the wins and losses from each team. I want it only show me the record of the bears.
Any help would be great.
You can use array_search() to get the index of an item in an array. You can then use that index when querying $winlosses:
$team = array(bears, badgers, wildcats);
$winslosses = array("(42-24)", "(55-23)", "(32-21)");
$key=array_search(bears, $team);
echo $winslosses[$key]
results in:
(42-24)
Your best bet would be to store them in an associative array.
while($row = mysql_fetch_assoc($query)){
$winslosses[$row['team']] = "({$row['wins']} - {$row['losses']})";
}
Hope this helps
Your main problem is that you currently have $winslosses as a string, not an array, so you can't easily pull out the win/loss record for just one team.
There are several ways you could do this. The one that seems easiest to me would be to put it together as one array up front.
Something like...
while($row = mysql_fetch_assoc($query)){
$teams[$row['team']] = "({$row['wins']} - {$row['losses']})";
}
Then later on...
if(array_key_exists("bears",$teams)) {
echo $teams["bears"];
}
Or even better, store the wins/losses as a sub-array, so you have structured data that you can format however you want later on.
while($row = mysql_fetch_assoc($query)){
$teams[$row['team']] = array("wins" => $row['wins'], "losses" => $row['losses']);
}
echo $teams['bears']['wins']; // for example
Use associative array:
while($row = mysql_fetch_assoc($query)){
$team[] = {$row['team']};
$winslosses[$row['team']] = "{$row['wins']} - {$row['losses']}";
}
Then retrieve it like this:
if(in_array(bears, $team) ) {
echo $winslosses['bears'];
}
As a matter of fact, if you do not need the names of the teams in a separate array, you can just use one associative array and then retrieve it.
if (array_key_exists('bears', $winslosses)) {
echo $winslosses['bears'];
}

Neat and tidy way to solve php code?

How would i go about the following problem which involves running an update query for every row in the array defined below? I hope it becomes clear...
<?php
//Some code
user = array();
while ($row = mysql_fetch_array ($auctioncheck)){
$fdt[] = $row['finish_time'];
if ($date_time >= $fdt) {
$user[] = $row['current_bidder'];
{
{
I then want to update a table which sets the value as "user[]". What is the neatest way of doing this? I presume it requires a while loop only i don't know how to do it in this context. So it would be like...
<?php
//Above while loop and then...
$update = mysql_query("UPDATE homepage SET username = '$user[]'...so on");
Basically i want the update to be performed for every user[] in the above array. I might be able to figure it out if i knew how to determine the number of rows in the the user array. Any help would be much appreciated. Cheers.
It looks like the for each will come into play. Only i am now concerned with the elements of multiple arrays being used in the update.
$user = array();
$seller = array();
while ($row = mysql_fetch_array ($auctioncheck)){
$fdt[] = $row['finish_time'];
if ($date_time >= $fdt) {
$user[] = $row['current_bidder'];
$seller[] = $row['seller'];
}
}
$update = mysql_query("UPDATE homepage SET username = '$user[]'...WHERE username = '$seller'");
Any ides anyone for the multiple elements and arrays.
It should be $user = array();
Is this what you're looking for?
<?php
//Above while loop and then...
foreach($user as $value){
$update = mysql_query("UPDATE homepage SET username = '$value'");
}
?>
This is not PHP
user = array();
You are missing the $
Besides
where is
{
{
come into play?

Query results stored into one variable

I've read through some other posts that were similar but I can't seem to get a good implementation of them. I'm calling a php script from another program that needs the results returned in one variable, space or comma separated. The php connects to a db (no problem there) and runs a query that will return 2 to 6 or so matching rows. I need those results together in one variable but can't seem to get it.
Here's where I'm stuck.
$t = "SELECT user FROM call_times WHERE client='$clientid' AND start <= $date AND end >= $date";
$result = mysql_query($t) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$temp = $row['user'];
}
echo $temp;
The query runs fine, but you can see from the code what I'm trying (and failing) to do in the lower part. I need $temp to hold a list of results (ex: 5567889 57479992 4335780 (each of which is a different entry in user column)).
Thanks so much!
$array = array();
while ($row = mysql_fetch_array($result)) {
$array[] = $row['user'];
}
$string = implode(" ", $array);
Now $string has the space-separated values of the user column.
Good luck!
Try group_concat() and you won't need PHP to manipulate the results.

How to load a selected cell from sql table PHP

sorry my code is a bit long, please bear with me. i am trying to load the link stored inside a cell from my sql table via php. The user is able to click a checkbox and choose which link to load. however, what i have is a bit off. it loads all the links present in the sql table instead of the one the user chooses. what did i do wrong? please guide. Thank you!
$sql = "SELECT * FROM previousbroadcast ORDER BY id DESC";
$result=mysql_query($sql);
$count = mysql_num_rows($result);
while ($row = mysql_fetch_assoc($result)) {
if (isset($_POST['re_b'])){
$xml = simplexml_load_file($row['bclink']);
}
}
and the HTML is like
<input name="checkbox[]" type="checkbox" id="checkbox[]" value="<? echo $row['id']; ?>">
OK, a new try with the additional information you gave:
This solution is based on the following assumptions:
The value of the checkboxes you get is in some way related to a field in the database
For the sake of simplicity, I have named that field id - it can be named differently in the database, but only you would know that...
That being said:
$sql = "SELECT * FROM previousbroadcast ORDER BY id DESC";
$result=mysql_query($sql);
$count = mysql_num_rows($result);
// in this array, we now have all the values of the checkboxes the user selected
$checkboxvalues = $_REQUEST['checkbox'];
while ($row = mysql_fetch_assoc($result)) {
if (isset($_POST['re_b'])){
// if the ID of this row is mentioned in the checkboxes the user clicked
// then - and only then - load the file
if (in_array($row[id], $checkboxvalues)) {
$xml = simplexml_load_file($row['bclink']);
}
}
}
ok, your code didn't come quite well, it's incomplete.
but for what I can see the $del_record value is the checkbox array with key $i
problem there is that you are calling the database every time, so it's easy to get lost.
you should store the fetched arrays in another array and then iterate there, instead of making lots of requests to the database, that will make your code run faster and you will have more control over it.
I would get SQL to do all the filtering for you:
if (isset($_POST['re_b'])) {
$checkboxvalues = isset($_REQUEST['checkbox']) ? $_REQUEST['checkbox'] : array();
$myCheckboxes = array();
foreach ($checkboxvalues as $cbv) {
$myCheckboxes[] = mysql_real_escape_string($cbv);
}
$sql = "SELECT * FROM previousbroadcast WHERE id IN ('" . implode(",", $myCheckboxes) . "') ORDER BY id DESC";
$result=mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) {
$xml = simplexml_load_file($row['bclink']);
// do something here with $xml or it will get overwritten
}
}

Store a value from a database into a variable for use outside of a "while" in PHP

This is the relevant bit of my code:
while($row1 = mysql_fetch_array($result1)){
$pro_no = $row1['project_no'];
So outside of this "WHILE" i want to use $pro_no. How do i go about doing this?
Thanks
EDIT: Thanks, didn't realise i would not need a while loop
If you have only one row you can do
$row1 = mysql_fetch_array($result1));
$pro_no = $row1['project_no'];
or if you have mamy rows you can accumulate values in an array
$pro_no = array();
while($row1 = mysql_fetch_array($result1)){
$pro_no[] = $row1['project_no'];
}
At the end of while all the values from column project_no will be in your array
After the loop it will be filled with the last value from inside the loop. Therefore it makes sense to set it to a default value to make sure it ran trough the while().
Example:
$pro_no = 'DEFAULT VALUE';
while($row1 = mysql_fetch_array($result1)){
$pro_no = $row1['project_no'];
}
var_dump($pro_no);
// shorter and faster way of finding the last value:
$row1 = mysql_fetch_array($result1);
rsort($row1);
var_dump($row1[0]);
I'm guessing you're problem is that the value of $pro_no changes for each loop and you only reach the last one after the loop. Save them to an array instead to be able to use all later:
$pro_no[] = $row['project_no'];
Hope I understood the problem correctly
Since $proj_no will change each time the loop runs, you need to assign the values to an array, and access the array.
while($row1 = mysql_fetch_array($result1)){
$proj_array[] = $pro_no = $row1['project_no'];

Categories