I am trying to store the result from a MySQL statement for later use in PHP. I have this code which gets me the result:
// Get the categories from the db.
$categories = array();
$catSql = "SELECT id, name FROM categories";
if ($catStmt = mysqli_prepare($db, $catSql))
{
$catStmt->execute();
$result = $catStmt->get_result();
// Fetch the result variables.
while ($row = $result->fetch_assoc())
{
// Store the results for later use.
}
}
So I know i will have the results in $row["id"] and $row["name"] and I want to save all of the rows so whenever i need them i can loop through them and for example echo them. I have searched for structures and arrays for keeping them in PHP but I cannot seem to find any information about that or maybe I am not searching in the right direction. Can anyone point me where i should read about this to find out how to do this efficiently and if possible post a small example?
Use sessions:
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
// Get the categories from the db.
$categories = array();
$catSql = "SELECT id, name FROM categories";
if ($catStmt = mysqli_prepare($db, $catSql))
{
$catStmt->execute();
$result = $catStmt->get_result();
// Fetch the result variables.
while ($row = $result->fetch_assoc())
{
// Store the results for later use.
$_SESSION['category_' . $row['id']] = $row['name'];
}
}
Then access it later from a different page
$_SESSION['session_variable_name']
You can also create an array of the information and store the entire array in a single session variable.
Just make sure you add the session_start function at the beginning of each page. The if statement prevents you from trying to start it multiple times.
$categories = array();
$catSql = "SELECT id, name FROM categories";
if ($catStmt = mysqli_prepare($db, $catSql))
{
$catStmt->execute();
$result = $catStmt->get_result();
while ($row = $result->fetch_assoc())
{
$categories[$row['id']]=$row['name'];
}
}
And If you want the name anywhere use below :
$categories[$id]
Trying to insert multiple "ids" into cookie from mysql database. So, i am pressing a few links and collect their ids in an array. And then trying to implode this array and give it to a function, which should take an info from sql database and write it down to cookie $basket.
But in showbasket.php i've got only one, last pressed id. The main problem is in ids i think, but i can't figure it out.
p.s. this is just a cookie-training, not a real implementation.
this is a file add2basket.php:
<?php
require 'functions.php';
$id = $_GET['id'];
$arr = [];
$arr[]=$id;
$ids = implode(",", $arr);
save2basket($ids);
header("Location: catalog.php");
?>
This is a function save2basket:
function save2Basket($ids){
global $conn, $basket, $ids;
if(!isset($_COOKIE['basket']))
$basket = setcookie('basket', $sel);
$sql = "SELECT * FROM catalog WHERE id IN ($ids)";
$result = mysqli_query($conn, $sql);
$select = mysqli_fetch_all($result, MYSQLI_ASSOC);
mysqli_free_result($result);
$sel = base64_encode(serialize($select));
$basket = setcookie('basket', $sel);
}
This is a showbasket.php file:
<?php
$basket = unserialize(base64_decode($_COOKIE['basket']));
print_r($basket);
Replace your PHP code with below code. You should have to save your selected ids in session. Currently each time php page will called your array will be initialized blank and it will contain only recent id. Don't forget to unset session after your entire operation get complete.
<?php
session_start();
require 'functions.php';
$id = $_GET['id'];
$_SESSION['arr'] = $id;
$ids = implode(",", $_SESSION['arr']);
save2basket($ids);
header("Location: catalog.php");
?>
I have an array which I have put into a SESSION, but for some reason when I click a button on the page, instead of the list of items showing again using the id numbers from the array stored in the session, it returns to main.php (which is what I have told it to do when it isn't set)
$games= $_POST['games'];
if (!empty($games)){
$_SESSION["gamelist"] = $games;
$list = implode(',', $games);
}else {
header('Location:./main.php');
}
Printing the result out is the code:
$conn = pg_connect("host=*** port=*** dbname=*** user=*** password=*****");
$sql = "SELECT column1, column2, column3 FROM table WHERE Id IN ($list)";
$result = pg_query($conn, $sql);
Any help would be amazing, thanks.
Uhm, you are checking the content of $_POST['games'], which is obviously not a session variable.
I can't see where you are retrieving data from the session variable. I only see you set it. $list needs to come from your session variable if it exists, and not just from your $_POST variable.
$games= $_POST['games'];
if (!empty($games)){
$_SESSION["gamelist"] = $games;
}else {
header('Location:./main.php');
}
if ( isset( $_SESSION['gamelist'] ) ) $games = $_SESSION['gamelist'];
$list = implode(',', $games);
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?
I have an odd issue. I have one PHP script that is used for multiple forms. It takes in all the requests and then puts the data in the appropriate table in a database. As it stands, it looks like this:
$fields = "";
$values = "";
foreach ($_REQUEST as $key=>$value)
{
$key = str_replace(":","",$key);
$fields .= "$key,";
$values .= "'$value ',";
}
//remove the ending comma from $fields and $values
$fields = substr($fields, 0, -1);
$values = substr($values, 0, -1);
$sql = "INSERT INTO " . $survey . " ($fields) VALUES ($values)";
mysql_query($sql)
or die(mysql_error());
And this works well. The problem is, there are some forms with checkboxes (i.e. a person can select more than one option). If I were to use a get method, the query string would look like:
www.somesite.php?V9=1&V9=2&V9=4
With the current script, only 4 is taken, since it was the last value.
Now, I know a reason this is happening is because of the way the name of the checkbox is defined in the form. It says name="V9" instead of name="V9[]" However, I cannot change the forms. They are generated by software, and the idea is that any user can create an HTML form, point it to the script and their information will be recorded in a table. So, changing the HTML is not an option for me.
So, I need a way to detect whether a key has been submitted, and if so, append the value. I tried this:
$fields = "";
$values = "";
foreach ($_REQUEST as $key=>$value)
{
//check to see if the key has already been used for multi-choice questions
$key_check = strpos($fields, "$key,");
if($key_check !== false){
$values = substr($values, 0, -2);
$values .= "\;$value ',";
}else{
$key = str_replace(":","",$key);
$fields .= "$key,";
$values .= "'$value ',";
}
}
//remove the ending comma from $fields and $values
$fields = substr($fields, 0, -1);
$values = substr($values, 0, -1);
$sql = "INSERT INTO " . $survey . " ($fields) VALUES ($values)";
mysql_query($sql)
or die(mysql_error());
But I get the same results. $key_check never seems to be valid. Any help would be appreciated. Someone here has a working ASP version that does a similar thing, but it emails the data, rather than saving it in a DB.
You could try this if you are using $_GET:
function convertInput($qs=""){
$rtn = "";
$holdingArray = array();
if(trim($qs)!=""){
$vars = explode("&", $qs);
foreach($vars as $val){
$kv = explode("=", $val);
if(count($kv)==2){
if(isset($holdingArray[$kv[0]])){
$holdingArray[$kv[0]] .= "," . $kv[1];
}else{
$holdingArray[$kv[0]] = $kv[1];
}
}
}
$rtn = $holdingArray;
}
return $rtn;
}
print_r(convertInput($_SERVER["QUERY_STRING"]));
Try this:
$keys = array();
$values = array();
foreach ($_POST as $key=>$value){ //So, it will loop through the form data
if (!array_search($key, $keys)){ //Checking to see if the key has been used yet
$keys[] = $key;
} else {
$values[$key][] = array($key=>$value);
}
}
This should build an array of your FORM SELECT choices built from the same form, provided that the data is preserved from the browser and is logically eliminated (when accessed as an array, only the last element of the same associated key is preserved, but otherwise the data is there to be had) instead of procedurally eliminated.
I have no idea if this works, because this is building from a theory, not from any kind of documentation or code expertise.
PHP parses the request string (query string or x-www-form-urlencoded) into $_GET, $_POST, and $_REQUEST arrays using the rule that when the same key is present multiple times, later key values overwrite previous ones. So if you cannot change the key names on the forms to append [] like PHP expects, you have to access the raw query string and parse it by hand.
Note that repeating the key name without [] creates ambiguity as to whether a query string key is meant to be a scalar or an array. You will have to decide how to resolve that. E.g., you can use a server-defined hardcoded list of names with array values.
This is how you could process a query string into a list of values:
function paramlist($querystring, $raw=false) {
$plist = array();
$decoder = ($raw) ? 'rawurldecode' : 'urldecode';
$pairs = explode('&', $querystring);
foreach ($pairs as $pair) {
$plist[] = array_map($decoder, explode('=', $pair, 2));
}
return $plist;
}
If you have a query string like a=1&b=2&a=3, this function will return array(array('a','1'),array('b','2'),array('a','3')). You can then turn that to an associative array using any logic you want.
However, you need to get the query or form string in the first place:
if ($_SERVER['REQUEST_METHOD']==='POST'
and $_SERVER['CONTENT_TYPE']==='application/x-www-form-urlencoded') {
// form body
$qs = trim(file_get_contents('php://input'));
} else {
// url query string
$qs = $_SERVER['QUERY_STRING'];
}
Note that if you send a form encoded with multipart/form-data, PHP will not let you access the raw request (even php://input will not work), so in this case there is no way to reprocess the form variables. Sorry!