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");
?>
Related
Hello i selected all records from users and returned them using a php whileloop and array, using implode i could get all the records outside the loop, what i wish to do actually is to access individual record and assign them to a variable individually to be used later in the same page.
this is what i came up with already, it works, but i don't know how to assign the recorded to individual variables, since all the records are displayed using implode
`<?php
$data = array();
$query = "SELECT * FROM users ";
$queryResult = mysqli_query($conn,$query);
while($_row = mysqli_fetch_array($queryResult)){
$data[] = $_row['first_name'];
$data[] = $_row['email'];
$data[] = $_row['amount'];
?>
<?php }?>
<?php
echo "<br />";
$request = implode("<br />", $data);
echo $request;?>`
please i need assistance on how to achieve or a better way to access whileloop records outside the loop this thanks in advance
This is what i intended doing with that result of the loop in the next query
`<?php
$profit = 10;
$query = "UPDATE storage SET ";
$query .="store_profit = '{$profit}' ";
$query .= "WHERE email = '{$email_from_loop_above}' ";?>`
for clarity purposes.. this script will be executed by a cronjob every 1 minute, initially this is what is did..
`
<?php
$query = "SELECT * FROM users WHERE email = $_SESSION['email'] ";
$queryResult = mysqli_query($conn,$query);
while($_row = mysqli_fetch_array($queryResult)){
$first_name = $_row['first_name'];
$email_from_loop_above = $_row['email'];
$amount = $_row['amount'];
?>
<?php }?>`
Then for the update query this is what i did
`<?php
//The profit below was gotten from a percent from the amount i return from the loop above.
$profit = 10;
$query = "UPDATE storage SET ";
$query .="store_profit = '{$profit}' ";
$query .= "WHERE email = '{$_SESSION['email']}' ";
?>`
Now this code above works perfectly, but when the user logout out the store_profit would not update anymore simply because this you know would require an active user SESSION to work, so what i am trying to do now is is make it work accordingly even when the user is logged out of the account, if i use the following method
`<?php
$query = "SELECT * FROM users ";
$queryResult = mysqli_query($conn,$query);
while($_row = mysqli_fetch_array($queryResult)){
$first_name = $_row['first_name'];
$email_from_loop = $_row['email'];
$amount = $_row['amount'];
?>
<?php }?>`
`
<?php
$profit = 10;
$query = "UPDATE storage SET ";
$query .="store_profit = '{$profit}' ";
$query .= "WHERE email = '{$email_from_loop}' ";
?>`
it would only return the last user data only, simply because i am outside the loop, now when i try to update inside the loop, it works but it adds 10 to store_profit to the first user and adds 20 to the second user also adds 30 to third user... simply because it inside the loop
now what is want to do is make this work accordingly so i decided to use array, however i am not to familiar with array that why i became confused.
An explanation of how i can achieve this purpose would be very much appreciated thanks.
however i was thinking of not destroying all the user session maybe i create session for that purpose and not distroy it.. but i don't if that method would be safe or good.
As a result of your loop you have a $data array which you then turn into a string by gluing all its elements using implode function.
You can of course still access every individual element of $data array outside of the loop by addressing to its direct index.
For instance:
echo $data[0]['email'];
will output the email record of first (arrays are 0 based in PHP) element of your array.
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]
This question already has answers here:
MySQL query pulling one row and displaying first letter of result
(3 answers)
Closed 3 years ago.
<?php
if($_POST)
{
include 'config.php';
$referencenumber=$_POST['reference_number'];
$fullname=$_POST['full_name'];
$sRef=mysqli_real_escape_string($conn,$referencenumber);
$sName=mysqli_real_escape_string($conn,$fullname);
$query="SELECT * From customers where reference_number='$sRef' and
full_name='$sName'";
$result=mysqli_query($conn,$query);
if(mysqli_num_rows($result)==1)
{
session_start();
$_SESSION['id'] = $query['id'];
$_SESSION['refnumber'] = $query['reference_number'];
header('location:index.php');
}
}
?>
The above code is what I have written on my login.php page. After a successful login, the user arrives at the index.php page.
var lz_data = {overwrite:true,111:'<?php
print_r($_SESSION['refnumber'])?>',
I am then attempting to print the reference number on the next page here, which will set a value that matches the one in $_SESSION['refnumber'] but for some reason the output of this code always seems to be 'S' when printing, just the letter S. I get the same output when I try to print $_SESSION['id'] as well. Any ideas?
EDIT: session_start(); has been added at the start of index.php, and the double quotations didn't solve the issue.
You try to get a specific index of a string instead of the result / row array:
$query="SELECT * From customers where reference_number='$sRef' and full_name='$sName'";
$_SESSION['id'] = $query['id']; // $query is a string not an array.
$_SESSION['refnumber'] = $query['reference_number']; // $query is a string not an array.
Why you only get "S" on the session?
You can use a string value on PHP like an array. So you can use $query[0] to get the "S" and $query[1] to get the "E" and so on. In your case the $query['id'] is the same like $query[0] because var_dump('id' == 0) is true.
demo on ideone.com
How to solve this?
You can use the mysqli_result::fetch_array method to get the row with columns as index from $result:
//get the $row from $result with fetch_array.
$row = $result->fetch_array(MYSQLI_ASSOC);
//now you can use the row array to set the values to the session.
$_SESSION['id'] = $row['id'];
$_SESSION['refnumber'] = $row['reference_number'];
So your code looks like the following:
<?php
if($_POST) {
include 'config.php';
$referencenumber = $_POST['reference_number'];
$fullname = $_POST['full_name'];
$sRef = mysqli_real_escape_string($conn, $referencenumber);
$sName = mysqli_real_escape_string($conn, $fullname);
$query = "SELECT * From customers where reference_number='$sRef' and full_name='$sName'";
$result=mysqli_query($conn, $query);
if(mysqli_num_rows($result) == 1) {
//get the $row from $result with fetch_array.
$row = $result->fetch_array(MYSQLI_ASSOC);
session_start();
$_SESSION['id'] = $row['id'];
$_SESSION['refnumber'] = $row['reference_number'];
header('location:index.php');
}
}
Okay so I am trying to create a custom function that will echo a site url inside an iframe for the end user.
The script has to check whether or not the user has already seen the site and if they have seen it don't display it any more, but take another site url from the database etc.
Here's what I have come up with so far:
function get_urls() {
require 'config.php';
global $con;
global $currentUsername;
$con = mysqli_connect($hostname, $dbusername, $dbpassword, $dbname);
$query = "SELECT site_url FROM sites WHERE site_url IS NOT NULL";
$result = mysqli_query($con, $query);
// Get all the site urls into one array
$siteUrls = array();
$index = 0;
while($row = mysqli_fetch_assoc($result)) {
$siteUrls[$index] = $row;
$index++;
}
$query2 = "SELECT site_url FROM views WHERE user = '$currentUsername' AND site_url IS NOT NULL";
$result2 = mysqli_query($con, $query2);
// Get urls the user has already seen into another array
$seenUrls = array();
$index = 0;
while($row2 = mysqli_fetch_assoc($result2)) {
$seenUrls[$index] = $row2;
$index++;
}
// Compare the two arrays and create yet another array of urls to actually show
$urlsToShow = array_diff($siteUrls, $seenUrls);
if (!empty($urlsToShow)) {
// Echo the url to show for the iframe within browse.php and add an entry to the database that the user has seen this site
foreach ($urlsToShow as $urlToShow) {
echo $urlToShow;
$query = "INSERT INTO views VALUES ('', '$currentUsername', '$urlToShow')";
mysqli_query($con, $query);
break;
}
}
// Show the allSeen file when all the ads are seen
else {echo 'includes/allSeen.php';}
mysqli_free_result($result);
mysqli_close($con);
}
I have currently found two errors with this. First the $siteUrls and $seenUrls are all okay, but when I compare the two using array_diff then it returns an empty array.
Secondly the script doesn't write the site url into the database because the $urlToShow is an array not a single url?
I think the problem is in your code is at the place where you are creating your $siteUrls, $seenUrls arrays. mysqli_fetch_assoc() function will give you a result row as an associative array. So if you want to change some of your code in the while loops.
Please chnage this
while($row = mysqli_fetch_assoc($result)) {
$siteUrls[$index] = $row;
$index++;
}
To
while($row = mysqli_fetch_assoc($result)) {
$siteUrls[$index] = $row['site_url'];
$index++;
}
And in the second while loop also. Change this
while($row2 = mysqli_fetch_assoc($result2)) {
$seenUrls[$index] = $row2;
$index++;
}
To
while($row2 = mysqli_fetch_assoc($result2)) {
$seenUrls[$index] = $row2['site_url'];
$index++;
}
and try
i would not run two queries and try to merge the result array. you can use mysql itself to just return the sites that have not been seen yet:
SELECT sites.site_url FROM sites
LEFT JOIN views ON views.site_url=sites.site_url AND views.user='$currentUsername'
WHERE sites.site_url IS NOT NULL AND views.site_url IS NULL
This will return only site_urls from sites, that have no entry in the views table. The LEFT JOIN will join the two tables and for every non-matching row there will be NULL values in the views.site_url, so that is why i am checking for IS NULL.
Your saving of $urlToShow should work, if you set to $row field content and not $row itself as suggested, but if you want to check what is in the variable, don't use echo use this:
print_r($urlToShow);
If the variable is an array, you will see it's content then.
#Azeez Kallayi - you don't need to index array manually.
$seenUrls[] = $row2['site_url'];
In addition, you can fetch all result
$rows = mysqli_fetch_all($result2,MYSQLI_ASSOC);
foreach($rows as $row){
echo $row['site_url'];
}
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);