Undefined index when trying to get information from a 2nd page - php

I use my session with sql Information but I get a really weird error.
I have 2 pages at the moment. Now I have this in my 1st page:
while ($thread = mysqli_fetch_assoc($sql_result)) {
echo"<div id='question'<h2>
{$thread['title']}</br>
</h2>
<p style='font-size:16; text-align:left;'>
{$thread['description']}
</p>
<center>
<a href=profile.php?thread_username={$thread['username']}> {$thread['username']}</a></br>
{$thread['date_made']} </center></div>";
$_SESSION['profileuser']=$thread['username'];
}
So when you click the link, $_SESSION['profileuser'] will get the thread username.
Here's what I have in my 2nd page:
$profileusername = $mysqli2->real_escape_string($_SESSION['profileuser']);
The error I get is:
Undefined index
My other sessions work perfectly but this probably just wont do.
Of course I have session_start(); on every page...
When I press this button(on the 2nd page) it gives me the error:
if ( isset( $_POST['submit'] ) ) {
$about = $_POST['about'];
$sql_result2 = $mysqli->query("update account_information SET about='".$about."' WHERE username = '".$_SESSION["username"]."'");
$edit=false;
}
EDIT: I fixed it.

Paste this code to your second page:
<?php
session_start();
$var=$_SESSION['profileuser'];
if(empty($var))
{
die("Session variable is empty");
}
?>
it will help you to know the root of problem

Change:
$profileusername = $mysqli2->real_escape_string($_SESSION['profileuser']);
To:
$profileusername = mysqli_real_escape_string($_SESSION['profileuser']);

Related

Pagination in PHP during passing a value at the first time when the page loads

This is a simple code which I am using in PHP. But the problem is every time I run the page, it says undefined index page. But after clicking a href link, it works perfectly. Can anyone help me out how to resolve the error?
Actually the $_GET['page'] isn't having a value at the first time when the page loads. But I need this to execute the query to take out data from the database. Here's the code:
<?php
require 'db_connect.php';
$page=$_GET["page"];
if($page=="" || $page=="1") {
$page1=0;
} else {
$page1=($page*5)-5;
}
$sql="SELECT * FROM tbl_product WHERE deletion_status=1 limit $page1,5";
$res=mysqli_query($db_connect,$sql);
while($row=mysqli_fetch_assoc($res)) {
echo $row['product_id']." ".$row['product_name'];
echo "<br>";
}
$sql1="SELECT * FROM tbl_product WHERE deletion_status=1";
$res1=mysqli_query($db_connect,$sql1);
$count=mysqli_num_rows($res1);
echo'<br>';
//echo $count;
$a=$count/5;
echo'<br>';
$a=ceil($a);
for($b=1;$b<=$a;$b++){
?><?php echo " "; echo $b;?><?php
}
?>
Before trying to use the value, check if it exists:
$page = "1";
if (isset($_GET["page"])) {
$page = $_GET["page"];
}
That way it's initialized with a default value, but if a value has been provided it will use that one instead.
Simply check whether $_GET['page'] is set or not, and assign the initial $page value accordingly.
So change $page=$_GET["page"]; to
$page=isset($_GET["page"]) ? $_GET["page"] : "1";

How to store a value in a session?

I am displaying the user names as links on a php page like this which on clicking navigates on particular user home page:
$msql=$db->prepare("SELECT * from users where id=? order by id desc");
$msql->bind_param("i",$user_id);
$msql->execute();
$msql = $msql->get_result();
$msql = $msql->num_rows;
while($usercount=$msql->fetch_assoc())
{
$Email = $usercount['email'];
$FirstName = $usercount['first_name'];
$LastName = $usercount['last_name'];
?>
<strong><?php echo $FirstName.' '.$LastName;?></strong>
<?php
}
?>
And for the navigation to the user home page on clicking the link, I am using like this :
<?php
if(isset($_GET['navigate']) && $_GET['navigate'] == "true"){
$_SESSION['email'] = $Email;
header('location: nextpage.php');
}
?>
So my page looks like this as link
user1
user2
user3
.
.
.
usern
My issue is whenever I click on any of the links it always stores the first email in the session variable.
So, if I output the SESSION in nextpage.php
echo $_SESSION['email'];
it always echoes the first link email.
My guess for this because of the while loop I am using it always picks up the first link data and stays with it, but my question is how do i get the data for others as well. I want to navigate to that user page for which the link is clicked and that can only be done if I get the correct email on clicking the link.
As you said id is not primary key, and i assume that your same id will contain different emails, you have to do below changes:-
<?php
$msql=$db->prepare("SELECT * from users where id=? order by id desc");
$msql->bind_param("i",$user_id);
$result = $msql->execute(); // assign to a variable
//$msql = $msql->get_result(); //you are over-writing to one variable which is not correct
//$msql = $msql->num_rows; //you are over-writing to one variable which is not correct
while($usercount=$result->fetch_assoc()){
$Email = $usercount['email'];
$FirstName = $usercount['first_name'];
$LastName = $usercount['last_name'];
?>
<strong><?php echo $FirstName.' '.$LastName;?></strong> <!-- send mail id to the url too otherwise how's you will get the email id to save it into SESSION-->
<?php } ?>
AND
<?php
if(isset($_GET['navigate']) && $_GET['navigate'] == "true"){
$_SESSION['email'][] = $_GET['email']; // assign each mail to SESSION ARRAY not SESSION variable
header('location: nextpage.php');
}
?>
AND
echo "<pre/>";print_r($_SESSION['email']); //to see all emails.
Note:- You have to write session_start(); on top of your php page just after <?php if you want to work with SESSION on that page.

issue in session variables

I am new to php.
I want to use form data that are sent through <form method="POST" action="formdata.php"> to formdata.php be used in another file called main.php. For this I ucerated session variables in formdata.php
Hers's my code in formdata.php
<?php
session_start();
include_once("connect.php");
$n=$_POST['name'];
$p=$_POST['password'];
$sql=mysql_query**strong text**("SELECT * FROM member WHERE `userName`='$n' AND `password`='$p'");
if(mysql_num_rows($sql)==1){
$_SESSION['user']=mysql_fetch_array(mysql_query("SELECT * FROM member WHERE `userName`='$n' AND `password`='$p'"));
if($_SESSION['user']){
$user=$_SESSION['user'];
$_SESSION['userN']="$user(['userName'])";;
$_SESSION['level']="$user(['level'])";
//header("location:mainPage.php");
echo $user['level'];
echo $_SESSION['level'];
}
}
else{
echo "invalid user name or password" ;
}
?>
But when I echo $user['level'];
echo $_SESSION['level']; all I get printed is 3Array(['level']). Here echo $user['level'] gives the desired out put 3, but echo $_SESSION['level'] gives an array as Array(['level']). What can I do to make it print 3?
My next question is I want to use this level value in another php file (main.php). I lerant that session variables are global. So can I use $user['level'] or should I use $_SESSION['level']. In main.php I want to check the condition
if($user['level'] == 3) {
echo "level 3 user";
}
The issue is this line: $_SESSION['userN']="$user(['userName'])";;
You're setting $_SESSION['userN'] equal to whatever $user is in string form which is Array, and (['username']).
Why are you even setting userN? $_SESSION should already contain the user in question, and you can just retrieve it anywhere to get the contents.
This should be all you need:
<?php
session_start();
include_once("connect.php");
$n=mysql_escape_string($_POST['name']);
$p=mysql_escape_string($_POST['password']);
$sql = mysql_query("SELECT * FROM member WHERE `userName`='$n' AND `password`='$p'");
if(mysql_num_rows($sql)==1)
{
//You can reuse the original $sql here. No need to run another query.
$_SESSION['user']=mysql_fetch_array($sql);
//If mysql_num_rows($sql) returns 1, $_SESSION['user'] should always be equal to a user array (Which is true).
header("location:mainPage.php");
}
else{
echo "invalid user name or password" ;
}
?>
On the other page (mainPage.php), just use session_start(), and check to see what is inside $_SESSION. This script should give you a jump start:
<?php
session_start();
print_r($_SESSION);
//This will get the level you're looking for
$level = $_SESSION['user']['level'];
?>
It should contain the user/level and any other information you need.

Loading more results from database using $_POST (or $_GET?)

I have a blog page "plugin" in my own little cms and it's displayed with return() on the index.php.
Part of the index.php:
$id = (isset($_GET['m_id'])) ? $_GET['m_id'] : 1; //menu id
$sql = "SELECT m_cim, m_tartalom, m_plugin
FROM menu
WHERE m_s_id = (SELECT s_id FROM statusz WHERE s_nev='aktiv')
AND m_id = ".$id;
$eredmeny = mysql_query($sql);
if (#mysql_num_rows($eredmeny) == 0) {
$tartalom = "<h1>404!</h1>\n";
}
else {
$sor = mysql_fetch_assoc($eredmeny);
$tartalom = "<h2>{$sor['m_cim']}</h2>
<span class=\"tart\">{$sor['m_tartalom']}</span>\n";
if(!empty($sor['m_plugin'])){
$tartalom.=include("./modul/{$sor['m_plugin']}");
}
}
<section id="content">
<?php print $tartalom; ?>
</section>
The posts come from a database and the news.php is included in the index.php.
This is the "plugin" news.php
$aktiv="(SELECT s_id FROM statusz WHERE s_nev='aktiv')";
$sql = "SELECT hir_id, hir_cim, hir_tartalom, hir_ido
FROM hirek
WHERE hir_s_id=".$aktiv."
ORDER BY hir_id DESC";
$eredmeny = mysql_query($sql);
$kimenet = "";
while ($sor = mysql_fetch_assoc($eredmeny)) {
$kimenet.= "<article class=\"hirek\">
<h3>{$sor['hir_cim']}</h3>
<span class=\"hido\">{$sor['hir_ido']}</span>
<p class=\"htart\">".substr(strip_tags($sor['hir_tartalom']),0,200)."</p>
Tovább...
</article>\n";
}
return $kimenet;
If I use a php pagination, I only saw, that the page number is posted via the ‘GET’ method, but in that case, I use the GET method for the menu id, and when I want to post something else with get, the result will be the menu item with the actual id. Is it possible to use $_GET method for this?
I think this technique can solve my problem, but I don't know if it's outdated/not-so-good/do-not-use-it or not.
When I find somewhere a solution for my actual problem, somebody always says that "do not use it, because..." "it's not the best idea, because..." "this is not the best solution,because.."
Can I trust in this?

Using Post/Redirect/Get but when page gets re-directed back I still have to refresh

I have a simple Post/Redirect/Get thing functioning so when a user adds a product to their cart, it doesnt add another one when they refresh the page afterwards.
Here is my code:
<?php
include("wfcart.php"); ?>
<?php session_start(); ?>
<?php $cart =& $_SESSION['cart'];
if(!is_object($cart)) $cart = new wfCart();
$user_id = get_current_user_id();
$query = mysql_query("SELECT SUM(value) FROM wp_scloyalty WHERE userid = '$user_id'");
$totalpoints = mysql_result($query, 0);
$purchasevalue=array(); ?>
<?php $sqlprize="SELECT prizeid FROM wp_scloyalty_orders WHERE userid = '$user_id'";
$resultprize=mysql_query($sqlprize); ?>
<?php while($rows=mysql_fetch_array($resultprize)){
query_posts('post_type=prizes&showposts=-1&p='.$rows['prizeid'].''); while (have_posts()) : the_post();
$my_meta = get_post_meta($post->ID,'_my_meta',TRUE);
$purchasevalue[] = $my_meta['pointsvalue'];
endwhile;
wp_reset_query();
}
$calctotalnew = $totalpoints - array_sum($purchasevalue);
if($_POST['purchase']) {
foreach($cart->get_contents() as $item) {
$sql="INSERT INTO wp_scloyalty_orders VALUES (".$user_id.", ".$item['id'].")";
$result=mysql_query($sql);
}
$cart->empty_cart();
unset($_SESSION['cart']);
}
$err = array();
if($_POST['add']) {
query_posts('post_type=prizes&showposts=-1&p='.$product_id.''); while (have_posts()) : the_post();
$my_meta = get_post_meta($post->ID,'_my_meta',TRUE);
if($calctotalnew > $my_meta['pointsvalue']){
$cart->add_item(get_the_id(), 1, $my_meta['pointsvalue'], get_the_title());
}else{
//echo 'You do not have sufficient points to redeem this product...';
$err[] = "You do not have sufficient points to redeem this product...";
}
endwhile;
wp_reset_query();
if (!$err) {
// if no errors - saving data
// and then redirect:
header("Location: ".$_SERVER['PHP_SELF']."/my-account");
exit;
} else {
// all field values should be escaped according to HTML standard
foreach ($_POST as $key => $val) {
$form[$key] = htmlspecialchars($val);
}
}
}// else {
// $form['add'] = $form['add'] = '';
//}
?>
So my problem is that when I confirm purchase from the cart, there is a section on the page that shows the users remaining funds.In order to see the new balance they have to refresh the page aftet the purchase.
I just wondered if I am doing something really wrong here... maybe something to do with the header:location thing? I noticed that things really depend on the order of the IF statements for the different $_POSTs but cant seem to make it so it automatically updates the balance when they purchase :/
Thanks! Sorry for huge amounts of code btw, just didnt know what was important or not.
Not sure if this is the answer but I found this online:
"The header() is used to send a raw HTTP/1.1 specification specific
header. header() must be called before any actual output is sent, the
following example will not work:"
Now I know in the past this caused problems for me on sites that were hosted on a Linux webserver. On a Windows hosted server, I had more leeway with redirect code it seems (it wasn't nearly as picky where it was placed within the HTML).
If you can, try the code out on a Windows-based server. If it still has issues, it may not be the header.
Also, try redirecting to the php page you're using (such as example.php) instead of $_SERVER['PHP_SELF']. That may be causing issues as well because the code is trying to do an extra step that may be throwing things off.

Categories