I am attempting to display the contents of an array. I have a SELECT query that transfers two rows from the data base with a WHERE statement;
<?php
session_start();
include 'connection.php';
$inspectit = array();
$update1 = $_POST['inspect'];
$query1 = "SELECT title, reason FROM daysoff WHERE DATE(start) = '$update1' AND gighold = 1";
$day = mysql_query($query1);
while($requesting = mysql_fetch_array($day)) {
$inspectit[] = $requesting;
}
$_SESSION['inspect'] = $inspectit;
header('Location: '. $_SERVER['HTTP_REFERER']) ;
?>
I place the session variable into a new variable,$inspect, defined on a different page. I then try to display the array using;
<?php
session_start();
$inspect = $_SESSION['inspect'];
if($inspect == true) {
echo " </br>Name: </br><a> ". implode($inspect) ."</a></br></br>";
unset ($_SESSION['inspect']);
}
?>
If i var_dump($inspect) all the expected data is there, but it looks like an array holding another array. If i execute code as shown above, this gives a notice of array to string conversion. Where am i going wrong?
<?php
session_start();
$inspect = $_SESSION['inspect'];
if($inspect) {
echo " </br>Name: </br><a> ". implode($inspect) ."</a></br></br>";
unset ($_SESSION['inspect']);
}
?>
You are adding an array of query result into an array. try to change:
from:
while($requesting = mysql_fetch_array($day)) {
$inspectit[] = $requesting;
}
to:
$inspectit = mysql_fetch_array($day);
$_SESSION['inspect'] is an array, so you can used check like
$inspect = $_SESSION['inspect'];
if(count($inspect)>0) {
instead of
if($inspect == true) {
try
<?php
session_start();
$inspect = $_SESSION['inspect'];
if($inspect) {
echo " </br>Name: </br><a> ". implode("-",$inspect) ."</a></br></br>";
unset ($_SESSION['inspect']);
}
?>
or you can use empty() function too like
<?php
session_start();
$inspect = $_SESSION['inspect'];
if(!empty($inspect)) {
echo " </br>Name: </br><a> ". implode("-",$inspect) ."</a></br></br>";
unset ($_SESSION['inspect']);
}
?>
With $inspectit = array(); you are setting $inspectit to an array, then you are trying to set the string (or non-array) $_SESSION['inspect'] to equal that array. You can iterate multiple $_SESSION variables to each iteration of $inspectit as follows:
$n=0;
while($requesting = mysql_fetch_array($day)) {
$_SESSION['inspect'+$n] = $requesting;
$n++;
}
$_SESSION['inpect_count']=$n;
Thus you will know how many variables you setup with the $_SESSION['inpect_count']
I tried all above methods to no avail. I did however get it to work by doing;
<?php
session_start();
include 'connection.php';
$inspectname = array();
$inspectreason = array();
$update1 = $_POST['inspect'];
$query1 = "SELECT title, reason FROM daysoff WHERE DATE(start) = '$update1' AND gighold = 1";
$day = mysql_query($query1);
while($requesting = mysql_fetch_array($day)) {
$inspectname[] = $requesting['title'];
$inspectreason[] = $requesting['reason'];
}
$_SESSION['inspectname'] = $inspectname;
$_SESSION['inspectreason'] = $inspectreason;
header('Location: '. $_SERVER['HTTP_REFERER']) ;
?>
then to call and display the arrays;
<?php
if($inspectname == true) {
$size = sizeof($inspectname) - 1;
for($count = 0; $count <= $size; $count++){
echo " </br>Name: </br><a> ". $inspectname[$count] ."</a>";
echo " </br>Details: </br><a> ". $inspectreason[$count] ."</a></br></br>";
unset ($_SESSION['inspectname']);
unset ($_SESSION['inspectreason']);}
}
?>
Related
How do I get fname from the result of SQL query and store it in $_SESSION['fname'].
<?php
include('init.php');
session_start();
if(isset($_POST))
{
$loginemail=$_POST["loginemail"];
$loginpassword=$_POST["loginpassword"];
$fname="";
$sql = "select count(*),fname from users where password='$loginpassword' and email='$loginemail'";
$result=mysqli_query($con,$sql);
if($result){
$response =array();
while($row=mysqli_fetch_array($result))
{
array_push($response,array("Count"=>$row[0],"name"=>$row[1]));
}
$_SESSION["fname"]=$fname;
echo json_encode(array("server_response"=>$response),JSON_FORCE_OBJECT);
}
else{
echo "error";
}
mysqli_close($con);
}
?>
This is my php code to get the count and fname(username) from database using sql query
init.php has the connection details
my aim here is to retrieve fname using emailid and password
i get the count which is always 1 as per my database restrictions and a fname i want to declare a session variable as this fname
how do i decode the array to get fname
thanks in advance
Seems that you don't assign a value to $fname
<?php
include('init.php');
session_start();
if(isset($_POST))
{
$loginemail=$_POST["loginemail"];
$loginpassword=$_POST["loginpassword"];
$fname="";
$sql = "select count(*),fname from users where password='$loginpassword' and email='$loginemail'";
$result=mysqli_query($con,$sql);
if($result){
$response =array();
while($row=mysqli_fetch_array($result))
{
array_push($response,array("Count"=>$row[0],"name"=>$row[1]));
//
// try assign $fname here if you want the first you can
//
if($fname ==""){
$fname = $row[1];
}
//
}
$_SESSION["fname"]=$fname;
echo json_encode(array("server_response"=>$response),JSON_FORCE_OBJECT);
}
else{
echo "error";
}
mysqli_close($con);
}
?>
Since you are making an associative array, you need to access Count and name as keys. Like:
foreach($response as $key => $value) {
echo "Key=" . $key . ", Value=" . $value;
echo "<br/>";
}
But if you are sure that you will always get a single row, why don't you just store them in scalar variables like $count and $fname and inside your code do this:
$count; $fname = "";
while($row=mysqli_fetch_array($result))
{
$count = $row[0];
$fname = $row[1];
}
I am having a bit of an issue passing array variables that are fetched from the database and stored in variables and passing them into session variables to use all over the site.
Code:
$rid=$_SESSION['SESS_MEMBER_ID'] ;
$recquery = 'SELECT * FROM clinic_receptionist,clinic_table where clinic_receptionist.recep_clinic_id = clinic_table.ID AND recep_id ='.$rid;
$recresult = mysqli_query($conn,$recquery);
if(mysqli_num_rows($recresult)>0)
{
while($row = mysqli_fetch_assoc($recresult))
{
$cid = $row['clinic_id'];
$cname = $row['clinic_name'];
$name = $row['recep_full_name'];
$phone = $row['recep_mobile'];
$email = $row['recep_email'];
$address = $row['recep_address'];
$gender = explode(",",$row['recep_gender']);
$dob = $row['recep_dob'];
$doj = $row['recep_doj'];
}
}
?>
The above code is where the select query is happening. I wanted to know how do I assign $cid and $cname to a $_SESSION variable in different pages. Any help would be much appreciated. Thanks
CODE:
<?php session_start();
include('header.php');
include('menu.php');
include('config.php');
$appquery = 'SELECT * FROM appointment_table,clinic_table where clinic_table.ID = appointment_table.clinic_id';
$appresult = mysqli_query($conn,$appquery);
if(mysqli_num_rows($appresult)>0)
{
while($row = mysqli_fetch_array($appresult))
{
$_SESSION['cid'] = $row['ID'];
$_SESSION['cname'] = $row['clinic_name'];
$ptdate = $row['date'];
$pttime = $row['time'];
$ptname = $row['pt_name'];
$ptphone = $row['pt_ph_num'];
$ptemail = $row['pt_email_id'];
}
}
?>
The above code is the place from where I want to receive the id and clinic name.
<?php
// Start the session
session_start();
//Assigning the values to $_SESSION
$_SESSION['cid'] = $row['clinic_id'];
$_SESSION['cname'] = $row['clinic_name'];;
?>
session_start
You need to call session_start() on each page to initialize the session, of course; after that you can just
$_SESSION['cid'] = $cid;
$_SESSION['cname'] = $cname;
to store those values in $_SESSION.
By the way, someone's going to tell you to use a prepared statement for that query, so it might as well be me.
Perhaps an illustration is in order.
page1.php:
<?php
session_start(); // find session, or create new one
include('header.php');
include('menu.php');
include('config.php');
$appquery = 'SELECT * FROM appointment_table,clinic_table where clinic_table.ID = appointment_table.clinic_id';
$appresult = $conn->query($appquery);
if(($rowcount = $appresult->num_rows()) > 0)
{
// create arrays to pass data
$cids = array($rowcount);
$cnames = array($rowcount);
$i = 0;
while($row = $appresult->fetch_array())
{
// add values to arrays
$cids[$i] = $row['ID'];
$cnames[$i] = $row['clinic_name'];
$i++;
}
// add arrays to session
$_SESSION['cids'] = $cids;
$_SESSION['cnames'] = $cnames;
}
page2.php:
<?php
session_start(); // find session, or create new one
include('header.php');
include('menu.php');
include('config.php');
// retrieve arrays from session
$cnames = $_SESSION['cnames'];
$cids = $_SESSION['cids'];
// ... and print them
$count = count($cids);
for ($i = 0; $i < $count; $i++)
{
echo "cid = " . $cid[$i] . "; cname = " . $cname[$i] . "<br>";
}
page1.php performs the query and stores cid and cname values in arrays which are then stored in $_SESSION. page2.php retrieves the arrays from $_SESSION and echoes them out. In production, of course, it would be considered more efficient to run the query on the page where it is displayed, and only pass key values between pages.
I've also used object syntax instead of procedural syntax for mysqli, just to show what it looks like. As usual, I leave error handling as an exercise for the reader.
Below is my code , I am trying to append values of $vid ,and than next time when my file loads i am trying to find currently passed value of $vid in array $ids, but every time i am getting success msg ,where i am going wrong, am i not able to append values properly ?
process.php
session_start();
if(isset($_POST)) {
$reason_data = trim($_POST['abuse_data']);
if($reason_data == "Video is offensive")
{
$reason = 'a:1:{i:0;s:18:"' . $reason_data .'";}';
}
else
{
$reason = 'a:1:{i:0;s:19:"' . $reason_data .'";}';
}
$motive = trim($_POST['remark_data']);
$uid = trim($_POST['abuse_uid']);
$vid = trim($_POST['abuse_vid']);
if(trim($_SESSION['abuse_vdo_id']) == '')
{
$_SESSION['abuse_vdo_id'] = $vid;
$str = $_SESSION['abuse_vdo_id'];
}
else {
$str = $str."," .$vid;
$_SESSION['abuse_vdo_id'] = $str;
}
print_r($_SESSION['abuse_vdo_id']);
echo "break";
print_r($str);
$ids = explode(',',$_SESSION['abuse_vdo_id']);
echo "break 2";
print_r($ids);
if(in_array($vid, $ids))
{
echo "already abused";
}
else
{
echo "success";
$query = "INSERT INTO ".DB_PREFIX."reports ( reason, motive, uid, vid ) VALUES ( '{$reason}','{$motive}', '{$uid}', '{$vid}' )";
$result = mysql_query($query);
}
}
In my example below the for loop is not executed and / or my data is not being inserted into the database. What can I change?
<?php
include('connection.php');
{
if(isset($_POST['Submit']))
{
date_default_timezone_set('Asia/Calcutta');
$date = date('Y-m-d H:i:s', time());
for ($i=1; $i<=$_POST["NUM_STUDENTS"]; $i++) {
$STD = "STUDENT_ID".$i;
$DS = "DISCOUNT".$i;
$LV = "LEAVE".$i;
$FN = "FINE".$i;
$sql = "INSERT INTO ATTENDANCE";
$sql .= "(SESSION_ID,ORG_ID,GRADE_ID,MONTH,STUDENT_ID,DISCOUNT,LEAVE,FINE,SOURCE,CREATEDTTM,UPDDTTM,DELETE_FLAG)";
$sql .= "VALUES ";
$sql .= "('".$_POST["SESSION_ID"]."','".$_POST["ORG_ID"]."','".$_POST["GRADE_ID"]."','".$_POST["MONTH"]."','".$_POST[$STD]."','".$_POST[$DS]."','".$_POST[$LV]."','".$_POST[$FN]."' ";
$sql .= ",'".$_SESSION['login_name']."','".$date."','".$date."','N')";
$objQuery_2 = mysql_query($sql);
if($objQuery_2)
{
echo"<script>alert('Attendance Fine Added Successfully')</script>";
header("refresh:0;url=attendance_srch.php");
exit();
}
else
{
echo"<script>alert('Please Check Data')</script>";
header("refresh:0;url=attendance_srch.php");
exit();
}
}
}
mysql_close($bd);
ob_flush();
}
?>
You have left a lot space here between ? and > must be ?> . [This is one of the errors]
<?=$objResult["OPERATOR_ID"];? >">
^^^
must be
<?=$objResult["OPERATOR_ID"];?>">
Array keys are case sensitive. If the actual names of the input is OPERATOR_ID, then you can't access it with $_GET['operator_id'], you have to use $_GET['OPERATOR_ID'].
Another problem is that you have an extra set of braces. So you're doing all the database code even if the if (isset($_GET['OPERATOR_ID']) is false.
I am passing the string value through link in the URL to the next page like this <a href="ApplicationRegister.php?plan=trial">
In the ApplicationRegister.php page, i am getting this value like this $plan = $_GET["plan"];
and i will put this into a session variable like this $_SESSION['plans'] = $plan;
Here i am getting the value. but after the if statement i am not getting the value for this plan even after using Session variable.
My complete code is like this
$plan = $_GET["plan"];
echo $plan;
$_SESSION['plan'] = $plan;
$plans = $_SESSION['plan'];
echo $_SESSION['plans'];
include('connect.php');
If (isset($_POST['submit']))
{
$CompanyName = $_POST['CompanyName'];
$CompanyEmail = $_POST['CompanyEmail'];
$CompanyContact = $_POST['CompanyContact'];
$CompanyAddress = $_POST['CompanyAddress'];
$StoreName = $_POST['StoreName'];
echo $plans;
$myURL ="$_SERVER[HTTP_HOST]";
$myURL =$StoreName.'.'.$myURL;
if (stripos($myURL, 'www.') !== 0) {
$myURL = 'www.' . $myURL;
}
if (stripos($myURL, 'http://') !== 0) {
$myURL = 'http://' .$myURL;
}
if(stripos($myURL, '.com') !== 0) {
$myURL = $myURL . '.com';
}
echo $plans;
$RegistrationType = $_POST['RegistrationType'];
$Status = "Active";
$sql = "select * from plans where planname = '$plans'";
echo $sql;
mysql_query($sql) or die (mysql_error());
$planID = $row['planid'];
$query1 = "select count(CompanyEmail) from ApplicationRegister where CompanyEmail = '$CompanyEmail'" ;
$result1 = mysql_query($query1) or die ("ERROR: " . mysql_error());
$msg = "";
while ($row = mysql_fetch_array($result1))
{
if($row['count(CompanyEmail)'] > 0)
{
$msg = "<font color='red'> <b>This E-mail id is already registered </b></font> ";
break;
}
}
if($msg == "")
{
$query2 = "select count(URL) from ApplicationRegister where URL = '$myURL' ";
$result2 = mysql_query($query2) or die ("ERROR: " . mysql_error());
$msg = "";
while ($row = mysql_fetch_array($result2))
{
if($row['count(URL)'] > 0)
{
$msg = "<font color='red'> <b>This Stroename is already registered </b></font> ";
break;
}
}
if($msg == "")
{
$sql = "INSERT INTO ApplicationRegister(planid, CompanyName, CompanyEmail, CompanyContact, CompanyAddress, RegistrationType, ApplicationPlan, ApplicationStatus, URL, CreatedDate) VALUES ('$planID', '$CompanyName', '$CompanyEmail', '$CompanyContact', '$CompanyAddress', '$RegistrationType', '$plans', '$Status', '$myURL', NOW() )";
mysql_query($sql) or die(mysql_error());
$id = mysql_insert_id();
$_SESSION['application_id'] = $id;
if($plans == "trail")
{
header("Location: userRegister.php");
exit();
}
else
{
header("Location : PaymentGateway.php");
exit();
}
}
}
}
?>
Only in the beginning it holds the value , if i try to display it within theIf (isset($_POST['submit'])) it shows blank value for plans. Do not know what to do. Plz suggest
EDITED
Even after using like this, its the same. i do not know what may be the problem :(
$plan = $_GET["plan"];
echo $plan;
$_SESSION['plans'] = $plans;
echo $_SESSION['plans'];
// $plan = +$plan;
include('connect.php');
If (isset($_POST['submit']))
{
$CompanyName = $_POST['CompanyName'];
$CompanyEmail = $_POST['CompanyEmail'];
$CompanyContact = $_POST['CompanyContact'];
$CompanyAddress = $_POST['CompanyAddress'];
$StoreName = $_POST['StoreName'];
echo $_SESSION['plans'];
EDITED
In ApplicationRegister.php, i have passed the hiddenvalue which i got fro\m previous page like this
<input type="hidden" name="plan" value="<?php echo $plan ?>"/>
then POST method i have used this. Now i am getting the value for it. Thanks to all
EDITED
if($PlanName == "trail")
{
header("Location: userRegister.php");
exit();
}
else
{
header("Location : PaymentGateway.php");
exit();
}
It's because you're not calling session_start() at the top of the page. You need that for your sessions to persist across requests (which is the point of sessions)
As well as not calling session_start();, this code is wrong:
$plan = $_GET["plan"];
echo $plan;
$_SESSION['plan'] = $plan;
$plans = $_SESSION['plan'];
echo $_SESSION['plans'];
It should be:
$plan = $_GET["plan"];
echo $plan;
$_SESSION['plan'] = $plan;
$plans = $_SESSION['plans'];
echo $_SESSION['plans'];
You are setting $_SESSION['plan'] and then trying to access $_SESSION['plans'].
Also, are you clicking a link or submitting a form? You say that you have a link, yet your code tries to access values passed from a form.
If you are using a form, don't use links. Instead, use a select element to select a plan, and then change $plan = $_GET["plan"]; to $plan = $_POST["plan"];.
EDIT:
For the redirection problem, try this code:
echo "<pre>** Plan Name: **\n";
var_dump($PlanName);
echo "</pre>";
if($PlanName == "trail")
{
header("Location: userRegister.php");
exit();
}
else
{
header("Location: PaymentGateway.php");
exit();
}
and see what it outputs.
When someone clicks the link, it's going to set the variable properly. However, it's not going to hit the $_POST['submit'] logic, because it's not a post, just a get. Then, assuming your actually posting to that page at a later point, trying to access anything in $_GET will be null, and will then reset the session variable to null.
Your first page should have code something like this
<form action="ApplicationRegister.php" method="post">
<select name="plan">
<option value="trial">Trial</option>
</select>
<input type="submit"/>
</form>
Then, you check for $_POST['plan'] and $_POST['submit']