Can you store multiple arrays in one session? - php

Can you push multiple arrays to one session?
For example
array_push($_SESSION['mySession'], $array);
Problem: When i push another array to my session it removes tha last one in the session.
My case:
Get specific item from database
$meubel = $_GET['meubel'];
$sql = "SELECT * FROM mphp6_meubels WHERE naam LIKE '$meubel' ";
$stm = $pdo->prepare($sql);
$stm->execute();
Make new session if its does not exists:
if(!isset($_SESSION['meubels'])){
$_SESSION['meubels'] = array();
}
Make specific array
while($row = $stm->fetch()){
$meubel = [
'naam' => $row['naam'],
'type' => $row['type'],
'omschrijving' => $row['omschrijving'],
'prijs' => $row['prijs'],
];
}
push it to session
array_push($_SESSION['meubels'], $meubel);
When a button is clicked an ajax reqeust is made:
var url = 'test.php?meubel=' + meubel;
Output the session in a div
document.getElementById("div3").innerHTML = result;
If all ajax code is required please tell me.
Example:
When you buy a seat add it to the session. A seat has property's like: name, description and price. So the session must contain multiple arrays.

You are redefining $meubel each time through the loop so there is only one array. You want to dynamically append each row []:
while($row = $stm->fetch()){
$meubel[] = [
'naam' => $row['naam'],
'type' => $row['type'],
'omschrijving' => $row['omschrijving'],
'prijs' => $row['prijs'],
];
}
Then you probably want to merge instead of push, not sure what end result you want:
$_SESSION['meubels'] = array_merge($_SESSION['meubels'], $meubel);

Related

Conditionally use fallback value if value in resultset does not match currently logged in user

I have the php script below to get data from a database and return it to a calendar as part of a booking system. The title field, $row["title"], is actually the username of different people for each booking.
Everything works well, but I want to change things so that each user can only see their own username on the calendar, not each other’s. I want them to see 'booked' instead.
I’m pretty new to php, but my guess is that I need to iterate over the created $data array, changing only the title field if it doesn’t match the logged in user. I’m thinking this would come from this in my login script:
$_SESSION["username"] = $username; <=== I think this needs to be incorporated into the script and the php loop.
What I am trying to do is replace the title field with ‘booked’ if it doesn’t match the logged in user.
I also need to allow all users to see public entries too, say, unavailable, holiday -- so those title values should always be shown.
<?php
$connect = new PDO('mysql:host=localhost;dbname=xxx', 'xxx', 'xxx');
$data = array();
$query = "SELECT * FROM events ORDER BY id";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row)
{
$data[] = array(
'id' => $row["id"],
'title' => $row["title"],
'start' => $row["start_event"],
'end' => $row["end_event"]
);
}
echo json_encode($data);
?>
Let's say Mary is logged in. The data array will look like this:
[
{"id":"365","title":"Kerry","start":"2021-08-19 20:00:00","end":"2021-08-19 20:40:00"},
{"id":"366","title":"John","start":"2021-08-19 19:00:00","end":"2021-08-19 19:40:00"},
{"id":"367","title":"Mary","start":"2021-08-20 10:00:00","end":"2021-08-20 10:40:00"},
{"id":"368","title":"Mary","start":"2021-08-20 12:00:00","end":"2021-08-20 12:40:00"},
{"id":"369","title":"Betty","start":"2021-08-20 15:00:00","end":"2021-08-20 15:40:00"}
]
But I want to change it to this before sending it to the calendar:
[
{"id":"365","title":"booked","start":"2021-08-19 20:00:00","end":"2021-08-19 20:40:00"},
{"id":"366","title":"booked ","start":"2021-08-19 19:00:00","end":"2021-08-19 19:40:00"},
{"id":"367","title":"Mary","start":"2021-08-20 10:00:00","end":"2021-08-20 10:40:00"},
{"id":"368","title":"Mary","start":"2021-08-20 12:00:00","end":"2021-08-20 12:40:00"},
{"id":"369","title":"booked","start":"2021-08-20 15:00:00","end":"2021-08-20 15:40:00"}
]
If you want to access session data you'd first need to start the session. Then you can just use the session variables in the script
<?php
session_start();
$connect = new PDO('mysql:host=localhost;dbname=xxx', 'xxx', 'xxx');
$data = array();
$query = "SELECT * FROM events ORDER BY id";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row) {
$data[] = array(
'id' => $row['id'],
'title' => isset($_SESSION['username']) && $row['title'] == $_SESSION['username'] ? $row['title'] : 'booked',
'start' => $row['start_event'],
'end' => $row['end_event']
);
}
echo json_encode($data);
sidenote, this will only work properly if all the usernames are unique though
If the the username in the SESSION is the same as the row's title, then show the title, otherwise show booked.
Extension: To show the title value when it matches the logged in user's name OR if it matches so communal/public strings, pile them all into an IN() condition.
Recommendation:
$sql = "SELECT id,
IF(title IN (?,'unavailable','holiday'), title, 'booked') AS title,
start_event AS start,
end_event AS end
FROM events
ORDER BY id";
$statement = $connect->prepare($sql);
$statement->execute([$_SESSION['username']]);
echo json_encode($statement->fetchAll(PDO::FETCH_ASSOC));
If you want this to be a dynamic condition, you can prepare your whitelist array in advance:
$allowTitles = [
$_SESSION['username'],
'unavailable',
'holiday',
];
Then you create the necessary number of placeholders and feed the array to execute().
$placeholders = implode(',', array_fill(0, count($allowTitles), '?'));
$sql = "SELECT id,
IF(title IN ($placeholders), title, 'booked') AS title,
start_event AS start,
end_event AS end
FROM events
ORDER BY id";
$statement = $connect->prepare($sql);
$statement->execute($allowTitles);
echo json_encode($statement->fetchAll(PDO::FETCH_ASSOC));
P.S. I share #DarkBee's concern regarding unique names in your db table. Typically you should use ids to avoid any chance of data collisions.

(PHP) How to fetch an array from database column and generate them to check boxes

I'm working on a web app that displays check boxes that was connected to a database, but I can only generate one check box and couldn't generate multiple check boxes based from the array fetched from a database column in mysql.
I tried to generate the multiple check boxes from an array not connected to the database and it worked. I think it has something to do when i fetched an array from the database.
CONTENT OF THE COLUMN ('instrument_name') FROM DATABASE :
("Telephones","White Board","Pen","Video Conference","Screen Projector","Laptops")
EXPECTED OUTPUT :
[] Telephones
[] White Board
[] Pen
[] Eraser
[] Screen Projector
[] Video Conference
[] Laptop
THE ERROR
[] Telephones
(it only generates one check box from the array of the database)
So here's what i've been working on
$sql = "SELECT * FROM mrbs_instrument;"; // Fetch data from table
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
//The array that's not connected to the database
//$room_inst = array("Telephones","White Board","Pen","Video Conference","Screen Projector","Laptops");
$room_inst = array($row['instrument_name']); // Fetch data from database column
// Room Instruments
echo "<div id=\"rep_type\">\n";
$params = array('label' => get_vocab("Intruments") . ":",
'name' => 'instruments',
'value' => $inst_list,
'disabled' => $disabled,
'options' => array(),
'force_assoc' => TRUE);
foreach ($room_inst as $i)
{
$params['options'][$i] = get_vocab("$i");
}
generate_checkbox_group($params); // Generate Checkboxes from Array fetched from database table
echo "</div>\n";
Where did i go wrong? and i apologize for my mistakes, i just started PHP for a couple of days and new to stack overflow
You need to parse the instrument_name list into an array. You can use a regular expression to extract the words between quotes.
preg_match_all('/"([^"])"/', $row['instrument_name'], $matches);
$room_inst = $matches[1];

why i am getting 0 at first, while parsing JSON data?

I am new to json, my aim is to maintain the history of specific columns(which are posted through $_POST in php) on every update in mysql using php. I took one json array for the history column and placed it in a while loop, after that I appended the variable which i want to merge with the previous one with array_merge() function. I am getting the output but starting with 0. Let me know how to append the required fields in a proper json format and also how to retrieve the json data in a div tag. Thanks in advance.
PHP Code:
<?php
$query = mysqli_query($conn,"SELECT `history` FROM projects WHERE `no` = '$id'");
$json_data = array();
while ($js = mysqli_fetch_assoc($query))
{
$json_data[] = $js['history'];
$j = $json_data;
}
?>
<?php
if(isset($_POST['submit'])){
if(isset($_GET['id'])){
$id = $_GET['id'];
$assign = mysqli_real_escape_string($conn,$_POST['assign']);
$end_date = mysqli_real_escape_string($conn,$_POST['end_date']);
$comments = mysqli_real_escape_string($conn,$_POST['comments']);
$end_date = [
'assigned_to' => $assign,
'end_date' => $end_date,
'comments' => $comments
];
$json = array_merge($j,$end_date);
$js = json_encode($json);
$ins = mysqli_query($conn,"UPDATE `projects` SET `assigned_to`='$assign',`end_date`='$end_date',
`status`='$status',`comments`='$comments'`history`= '$js' WHERE
`episode_no` = '$id'");
}
}
?>
JSON data in MYSQL :
{"0":"{"0":"{"0":"","assigned_to":"AAA","end_date":"2018-09-12","comments":"happy"}",
"assigned_to":"AAA","end_date":"2018-09-12","comments":"jolly"}",
"assigned_to":"AAA","end_date":"2018-09-12","comments":"xvbcvbdfghdfg"}
First of all, the answer to your question: you are loading an array of strings in $j, so the array_merge function won't work as expected:
$j[0] = 'some JSON string from DB';
$json = array_merge($j, $end_date);
the array_merge finds that the second argument is a sparse array, so it merges the keys as strings:
$json = [
'0' => 'the previous string',
'assigned_to' => ...
]
For your idea to work you probably need to store the new history item by appending to the array:
$j[] = $end_date;
$js = json_encode($j);
...
This would solve your issue.
But there is a very major issue here that you need to solve first. It's a OMG-like WTF-like issue. You are getting $id from user input (query parameters) and sending it to the DB without any fear. Suppose that the user sends
https://your.server/some/path?id=';TRUNCATE TABLE projects --'
(propery url-encoded of course). Now you are sending this to the database:
SELECT `history` FROM projects WHERE `no` = '';TRUNCATE TABLE projects --''
Bye bye projects. A user can do whatever to your database, change passwords, reassign foreign keys, set himself as administrator.
Please for the sake of whatever you believe in, use a proper ORM and never pass user input to the DB!!!

Placing database data in multidimensional array

For my webshop, I have 1 database with 3 relevant tables.
In order to display the data, I was advised to place the data out of these databases in 3 two dimensional arrays so that I could visualize what I was doing.
However, my only successful attempt of placing the data in the array resulted in the code overwriting itself, only showing the last data in the table.
Can anyone give me some suggestions on how to set up my array in a way that its automatically filled?
<?php
//Create the Multiarrays. 2D, one per table.
// Create connection
$conn = new mysqli(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Open the database
$sql = "SELECT * FROM productwindow";
$result = $conn->query($sql);
//Multiarray locatie 1. When the array starts here, the browser chokes.
if ($result->num_rows > 0) {
//multiarray locatie 2. When the array starts here, the browser also chokes.
while($row = $result->fetch_assoc()) {
$product = array( //multiarray locatie 3. The problem is that the array seems to overwrite itself.
array( //I want PHP to repeat this bit of code for every product in my database, so that I can use it later on.
"ID" => $row["ID"],
"Name" => $row["Productname"],
"Price" => $row["Pricetag"],
"Supply" => $row["Productsupply"],
"Tags" => $row["Tags"],
"Materials" => $row["Materials"],
),
);
}
//Multiarray locatie 2 end woul be placed here
} else {
echo "0 results found. Please check database connection.";
}
//Multiarray locatie 1 end woul be placed here.
$conn->close();
//
echo "<br/>";
$searchby = "Pluimstaart";//The keyword that I used in earlier concepts to filter on specific products. I now need a for loop to procedurally run through the multiarray.
$array_subjected_to_search = $product;
$key = array_search($searchby, array_column($array_subjected_to_search, "Name")); //If it cannot be done via a foreloop, I would need an alternative to "array_search" to show the contents of my array.
var_dump($array_subjected_to_search[$key]);//Used to see if I actually fill my array with data. It only shows the latest data.
//From here on out I build the website like follows;
echo "<br/>product data: " . $product[$key["Supply"]] . ".";
?>
Thank you very much for your feedback!
The $product variable is being overwritten on each loop because you are making it equal a brand new array each time:
$product = array(...
Instead you should be appending elements to the end of an array, using either array_push, or this shorthand:
$product[] = [
"ID" => $row["ID"],
"Name" => $row["Productname"],
"Price" => $row["Pricetag"],
"Supply" => $row["Productsupply"],
"Tags" => $row["Tags"],
"Materials" => $row["Materials"]
];
Try to replace your code of if else code by this code and try
$product[]=array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$product[]["ID"]=$row["ID"];
$product[]["Name"]=$row["Productname"];
$product[]["Price"]=$row["Price"];
$product[]["Supply"]=$row["Supply"];
$product[]["Tags"]=$row["Tags"];
$product[]["Materials"]=$row["Materials"];
}
} else {
echo "0 results found. Please check database connection.";
}
I am not sure if this is what you meant...
$i = 0;
$product = array();
while($row = $result->fetch_assoc()) {
$product[$i] = array(
"ID" => $row["ID"],
"Name" => $row["Productname"],
"Price" => $row["Pricetag"],
"Supply" => $row["Productsupply"],
"Tags" => $row["Tags"],
"Materials" => $row["Materials"],
);
$i++;
}

create ad multidimensional array and display it with a foreach loop

I've a problem with php and foreach...
The first query result like this:
while ($row = $s->fetch())
{
$registration[] = array(
'id_registration' => $row['id_registration'],
'discipline' => $row['discipline'],
'speciality' => $row['speciality'],
'category' => $row['category'],
'subcat' => $row['subcat']
);
}
excuse me, I was not very precise...
I have 2 table
- the first has a primary key (id_registration) that identifies the registration
- in the second table there are firstrname and lastname of the athletes which refer to the first table by id_registration.
how can I get all the registrations and the athletes of every registration and print all with one o more foreach loop?
I hope I was clear.
$iscrizioni = array();
while ($row = $s->fetch())
{
$iscrizioni['id_gara'] = $row['id_gara'];
$iscrizioni['disc'] = $row['disc'];
$iscrizioni['spec'] = $row['spec'];
$iscrizioni['cat'] = $row['cat'];
$iscrizioni['subcat'] = $row['subcat'];
}
pre($iscrizioni);

Categories