I keep getting an 'Undefined variable' notice when I call on an object I 'think' I have instantiated, but apparently haven't. I can't put a finger on my the error. The object is $fgmembersite, according to my error messages it doesn't exist, I'm confused about why. It maybe a simple case of me messing up my directories in the include/require portion of my scripts but I've been looking at them and can't see anything wrong. Tell me if you guys want to look at my file hierarchy.
And again thanks for the help!
I have three PHP files that are at play.
First one is login-home.php
<?PHP
require_once("./profile_settings/view.php");
if(!$fgmembersite->CheckLogin())
{
$fgmembersite->RedirectToURL("login.php");
exit;
}
?>
/*a bunch of stuff*/
<img id="profile_avatar" src="profile_settings/<?php echo fetchAvatarLocation(); ?>"></img>
/*a bunch of stuff*/
Next I have view.php which holds a function I use to generate the path-name of where I store my picture.
<?php
include("./include/membersite_config.php");
function fetchAvatarLocation()
{
$user_id = $fgmembersite->UserId();
$query = mysql_query("SELECT * FROM ddmembers WHERE id_user = '$user_id'");
if(mysql_num_rows($query)==0)
die("User not found!");
else
{
$row = mysql_fetch_assoc($query);
$location = $row['imagelocation'];
return $location;
}
}
?>
And finally I have membersite_config.php
<?PHP
include("fg_membersite.php");
$fgmembersite = new FGMembersite();
//Provide your site name here
$fgmembersite->SetWebsiteName('Mysitename.com');
//Provide the email address where you want to get notifications
$fgmembersite->SetAdminEmail('My.Email#Provider.net');
//Provide your database login details here:
//hostname, user name, password, database name and table name
//note that the script will create the table (for example, fgusers in this case)
//by itself on submitting register.php for the first time
$fgmembersite->InitDB(/*hostname*/'localhost',
/*username*/'user',
/*password*/'password',
/*database name*/'database',
/*table name*/'table');
//For better security. Get a random string from this link: http://tinyurl.com/randstr
// and put it here
$fgmembersite->SetRandomKey('**************');
?>
fg_membersite is a file that contains the class fgmembersite that stores a bunch of functions, the ones that I need it for are...
function UserId()
{
return isset($_SESSION['userid_of_user'])?$_SESSION['userid_of_user']:'';
}
function UserName()
{
return isset($_SESSION['username_of_user'])?$_SESSION['username_of_user']:'';
}
The object is not in the scope of the function, so it is undefined. You need to pass it in as a parameter:
function fetchAvatarLocation( $fgmembersite)
Then call it with the object as a parameter:
<img id="profile_avatar" src="profile_settings/<?php echo fetchAvatarLocation( $fgmembersite); ?>"></img>
An alternative is to use global variables, but I wouldn't recommend it.
Related
Im currently doing login and result are worked fine. However , I wish to get the firstname and lastname of the user from DB.
As I know getState() able to get the variable data from the DB.
Following bellow is the code for login:
$username = $_POST['username'];
$userpass = $_POST['userpass'];
$record=Games::model()->findByAttributes(array('email'=>$username));
if($record===null){
//somethings
}else if($this->checkPassword($record->password,$userpass)){
//somethings
}else
{
$this->_id=$record->id;
$this->_email=$record->email;
Yii::app()->user->setState('id', $record->id);
Yii::app()->user->setState('email', $record->email);
Yii::app()->user->setState('firstname', $record->firstname);
Yii::app()->user->setState('lastname', $record->lastname);
//go to somethings
}
In View
<?php
$username_first = Yii::app()->user->getState('firstname');
$username_last = Yii::app()->user->getState('lastname');
?>
<a href="#" ><?php echo $username_first.' '.$username_last; ?></a>
What is the problem of my code in view ? Any better suggestion to getState() the data I need ?
Updated :
I tried print out in controller ... it worked ... but why view cant ?
print_r(Yii::app()->user->getState('firstname'));
getState() is not dedicated to get variable from database. As Yii's official document defines it:
Returns the value of a variable that is stored in user session.
By setting state you store your variable's value into user session and you can get that value via getState().
As a suggestion, when you use getState(), pass a default value into the second parameter like below:
$email=Yii::app()->user->getState('email',NULL);
if(!is_null($email)) //do something
It is even better to check state before getting it by hasState() like below:
if(Yii::app()->user->hasState('email')){
$email=Yii::app()->getState('email',NULL);
}
Another note is that, it is better to get stored values in Controller and pass them to the view, not getting them in view. Take a look:
Controller
$email=Yii::app()->user->getState('email'); //it is better to check it via has state, and also passing a default value
$this->render('view',array(
'userEmail'=>$email
));
View
<h2><?php echo $email; ?></h2>
UPDATE
There is a condition that you may need to just get stored value into session (by setState()), So you can just do like below in view:
if(Yii::app()->user->hasState('firstname')) { echo Yii::app()->user->getState('firstname'); } //All done
Here is my question
I have a class say ABC and a function XYZ defined inside it and that function is returning something based on the above logic in it.
class ABC {
function XYZ{
..........
.......
return "--- ";
}
}
Now there is an object on another page of this class which calls this method.
$z= new ABC;
if( $z->XYZ() )
{
some output
}
else{
another output
}
My problem is i dont have access to PAGE 2. but i need to change the output of else statement. I have only access to class ABC because i am overriding it in a module. so, in short i can only alter function XYZ. Whats the solution??
If its of any significance, i am working on MAGENTO ECOMMERCE Platform and class is a block class and page 2 is a template
You can alter the output html with an observer with the http_response_send_before event.
Capture the html and do your stuff.
You have a good explanation here
I hope this can help you
you can also do as follow :
<?php
ob_start();
// do your stuff
// ...
// here you capture all the output that it is generated by your scripts
$v = ob_get_contents();
// alter the value of $v by detecting if it should be changed. you can user regex for example to
// detect and update
// ...
// here you clean all data stored in buffer
ob_clean();
// and put the updated data in buffer
print $v;
// end of buffer operations
ob_end_flush();
?>
hope it helps,
You need a way to differentiate PAGE1 from PAGE2, lets say by the URL if it's possible. So you would have to change your method that will check on which page is currently and according to it, it will change the output, but you must write the output in the method itself instead of writing it in the template.
class ABC {
function XYZ {
$result = $this->getResult(); //Helper method to get the result.
if ($result) {
//Do something when result is true.
} else {
$url = $this->checkUrl(); //Check URL of the page.
if ($url == PAGE2) { //If you are on PAGE2
//Do something specific for the PAGE2
} else {
//Do something for all other pages
}
}
}
}
I know it's not the perfect solution, but I hope it will help you somehow.
The page number has to be specified somewhere in the $_GET or the $_POST array (or in another query). Check that variable and implement the alternative logic.
I've built a contest system where users submit tickets then one is randomly chosen to win, and now I'm trying to figure out a way to display to users the tickets they have already submitted. Each ticket has an id, a date, and an invoicenumber. I want to display all the invoice numbers that a user has submitted so far.
Here is the method I have in my methods page. (I've organized my methods into one php file and then i just call them when needed.)
function GetSubmittedBallots()
{
if(!$this->CheckLogin())
{
$this->HandleError("Not logged in!");
return false;
}
$user_rec = array();
if(!$this->GetUserFromEmail($this->UserEmail(),$user_rec))
{
return false;
}
$qry = "SELECT invoicenumber FROM entries WHERE user_id = '".$user_rec['id_user']."'";
$result = mysql_query($qry,$this->connection);
while($row = mysql_fetch_array($result))
{
echo $row['invoicenumber'];
}
}
and then on my html page that I want it to echo on, i just call it
<?php GetSubmittedBallots(); ?>
Sadly, this doesn't work. So my question is, how would i go about displaying the $row array on my html page?
<?php
require("methods.php"); // Include the file which has the "GetSubmittedBallots" function or method, if it's in a separate file
GetSubmittedBallots(); // Run the function / method
?>
If this doesn't work, please let us know any errors you receive.
Does it echo "Array"?
That's because you are trying to echo an array.
You should use something like print_r or var_dump, given that you are just trying to access the queried results. In my opinion the method should build a multidimensional array with the records, and then the template logic should loop through them and echo the values in a nice way. Be it a table or nicely arranged HTML.
If I'm not wrong, $this keyword is indicating you're in a class? If so, you need first to init that class and try to call GetSubmittedBallots function after init;
// assuming that class's name is Users
$users = new Users();
$users->GetSubmittedBallots();
To practice PHP and MySQL development, I am attempting to create the user registration system for an online chess game.
What are the best practices for:
How I should handle the (likely) possibility that when a user tries to register, the username he has chosen is already in use, particularly when it comes to function return values? Should I make a separate SELECT query before the INSERT query?
How to handle varying page titles?($gPageTitle = '...'; require_once 'bgsheader.php'; is rather ugly)
(An excerpt of the code I have written so far is in the history.)
Do a separate SELECT to check whether the username is already in use before attempting to INSERT.
More importantly, I would suggest something like the following structure for the script you're writing. It has a strong separation of presentation logic (e.g. HTML) from your other processing (e.g. validation, database, business logic.) This is one important aspect of the model-view-controller paradigm and is generally considered a best-practice.
<?php
// The default state of the form is incomplete with no errors.
$title = "Registration";
$form_completed = false;
$errors = array();
// If the user is submitting the form ..
if ($_POST) {
// Validate the input.
// This includes checking if the username is taken.
$errors = validate_registration_form($_POST);
// If there are no errors.
if (!count($errors)) {
// Add the user.
add_user($_POST['username'], $_POST['password']);
// The user has completed.
$form_completed = true;
// Optionally you could redirect to another page here.
} else {
// Update the page title.
$title = "Registration, again!"
}
}
?>
<html>
<head>
<title>Great Site: <?= $title ?></title>
<body>
<?php if ($form_complete): ?>
<p>Thanks for registering!</p>
<?php else: ?>
<?php if (count($errors)): ?>
<ul>
<?php foreach ($errors as $error): ?>
<li><?= $error ?></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
<form method="post">
Username: <input type="text" name="username">
Password: <input type="password" name="password">
<input type="submit">
</form>
<?php endif; ?>
</body>
</html>
Well, one thing you can do instead of repeating code down near the bottom is this:
if( $result === true ) {
$gPageTitle = 'Registration successful';
$response = <p>You have successfully registered as ' . htmlspecialchars( $username ) . ' on this site.</p>';
} elseif( $result == 'exists' ) {
$gPageTitle = 'Username already taken';
$response = '<p>Someone is already using the username you have chosen. Please try using another one instead.</p>';
} else {
trigger_error('This should never happen');
}
require_once 'bgsheader.php';
echo $response;
require_once 'bgsfooter.php';
Also, you can return false rather than the string 'exists' in the function, not that it makes much difference.
Checking the error number isn't bad, I'm sure that's why it's an included feature. If you really wanted to do something different, you could check if there already is a user by that name by selecting the username. If no result exists, then insert the user, otherwise, give the error.
One thing I like to do with error handling on forms is save all the error strings into an array like $error['username'], $error['email'], etc., and then have it run through the error checking on each input individually to set all the error strings, and then have a function that does something like this:
function error($field)
{
global $error;
if(isset($error[$field]))
{
echo $error[$field];
}
}
and then call that after each field in the form to give error reporting on the form. Of course, the form page must submit to itself, but you could have all the error checking logic in a separate file and do an include if $_POST['whatever'] is set. If your form is formatted in a table or whatever, you could even do something like echo '<tr><td class="error">' . $error[$field] . '</td></tr>, and automatically insert another row directly below the field to hold the error if there is one.
Also, always remember to filter your inputs, even if it should be filtered automatically. Never pass post info directly into a DB without checking it out. I'd also suggest using the specific superglobal variable for the action, like $_POST rather than $_REQUEST, because $_REQUEST contains $_GET, $_POST, and $_COOKIE variables, and someone could feasibly do something strange like submit to the page with ?username=whatever after the page, and then you have both $_POST['username'] and $_GET['username'], and I'm not sure how $_REQUEST would handle that. Probably would make there be a $_REQUEST['username'][0] and $_REQUEST['username'][1].
Also, a bit about the page titles. Don't know if you have it set up like this but you can do something like this in your header:
$pageTitle = "My Website";
if(isset($gPageTitle))
{
$pageTitle .= "- $gPageTitle";
}
echo "<title>$pageTitle</title>";
Which would make the page load normally with "My Website" as the title, and append "- Username already exists" or whatever for "My Website - Username already exists" as the title when $gPageTitle is set.
I think the answer from Mr. Neigyl would require a separate trip to the database, which is not a good idea because it would only add performance overhead to yuor app.
I am not a PHP guru, but I know my way around it, although I don't recall the === operator. == I remember.
You could pass the function call directly into the IF statement.
if (addUser($username, $passwd));
I don't see anything wrong with using the $gPageTitle variable, but you will probably have to declare it "global" first and then use namespaces so you can actually access it within the "header.php" because "header.php" will not know how to address this page's variables.
Although I personally don't like messing with namespaces and I would rather call a function from the "header.php" and pass the page title into it
display_title($pgTitle);
or
display_title("Registration Successfull");
or
$header->display_title("Registration Successfull")
if you like OO style better
Let me know if that helps. :)
You should get into forms and allow your page to redirect to another page where you have there the 'insert username to database'.
Suppose the username entered is in a post variable such as $_POST['username'].
Have your database check where that username exist:
$res = mysql_query("SELECT * FROM table WHERE username='$_POST['username']'") or die(mysql_error());
if(mysql_num_rows($res) > 0) {
echo "Username exists.";
// more code to handle username exist
} else {
// ok here.
}
What is basically done is we check if your table already contains an existing username. mysql_num_rows($res) will return 0 if no username exist.
I have to show a page from my php script based on certain conditions. I have an if condition and am doing an "include" if the condition is satisfied.
if(condition here){
include "myFile.php?id='$someVar'";
}
Now the problem is the server has a file "myFile.php" but I want to make a call to this file with an argument (id) and the value of "id" will change with each call.
Can someone please tell me how to achieve this?
Thanks.
Imagine the include as what it is: A copy & paste of the contents of the included PHP file which will then be interpreted. There is no scope change at all, so you can still access $someVar in the included file directly (even though you might consider a class based structure where you pass $someVar as a parameter or refer to a few global variables).
You could do something like this to achieve the effect you are after:
$_GET['id']=$somevar;
include('myFile.php');
However, it sounds like you are using this include like some kind of function call (you mention calling it repeatedly with different arguments).
In this case, why not turn it into a regular function, included once and called multiple times?
An include is just like a code insertion. You get in your included code the exact same variables you have in your base code. So you can do this in your main file :
<?
if ($condition == true)
{
$id = 12345;
include 'myFile.php';
}
?>
And in "myFile.php" :
<?
echo 'My id is : ' . $id . '!';
?>
This will output :
My id is 12345 !
If you are going to write this include manually in the PHP file - the answer of Daff is perfect.
Anyway, if you need to do what was the initial question, here is a small simple function to achieve that:
<?php
// Include php file from string with GET parameters
function include_get($phpinclude)
{
// find ? if available
$pos_incl = strpos($phpinclude, '?');
if ($pos_incl !== FALSE)
{
// divide the string in two part, before ? and after
// after ? - the query string
$qry_string = substr($phpinclude, $pos_incl+1);
// before ? - the real name of the file to be included
$phpinclude = substr($phpinclude, 0, $pos_incl);
// transform to array with & as divisor
$arr_qstr = explode('&',$qry_string);
// in $arr_qstr you should have a result like this:
// ('id=123', 'active=no', ...)
foreach ($arr_qstr as $param_value) {
// for each element in above array, split to variable name and its value
list($qstr_name, $qstr_value) = explode('=', $param_value);
// $qstr_name will hold the name of the variable we need - 'id', 'active', ...
// $qstr_value - the corresponding value
// $$qstr_name - this construction creates variable variable
// this means from variable $qstr_name = 'id', adding another $ sign in front you will receive variable $id
// the second iteration will give you variable $active and so on
$$qstr_name = $qstr_value;
}
}
// now it's time to include the real php file
// all necessary variables are already defined and will be in the same scope of included file
include($phpinclude);
}
?>
I'm using this variable variable construction very often.
The simplest way to do this is like this
index.php
<?php $active = 'home'; include 'second.php'; ?>
second.php
<?php echo $active; ?>
You can share variables since you are including 2 files by using "include"
In the file you include, wrap the html in a function.
<?php function($myVar) {?>
<div>
<?php echo $myVar; ?>
</div>
<?php } ?>
In the file where you want it to be included, include the file and then call the function with the parameters you want.
I know this has been a while, however, Iam wondering whether the best way to handle this would be to utilize the be session variable(s)
In your myFile.php you'd have
<?php
$MySomeVAR = $_SESSION['SomeVar'];
?>
And in the calling file
<?php
session_start();
$_SESSION['SomeVar'] = $SomeVAR;
include('myFile.php');
echo $MySomeVAR;
?>
Would this circumvent the "suggested" need to Functionize the whole process?
I have ran into this when doing ajax forms where I include multiple field sets. Taking for example an employment application. I start out with one professional reference set and I have a button that says "Add More". This does an ajax call with a $count parameter to include the input set again (name, contact, phone.. etc) This works fine on first page call as I do something like:
<?php
include('references.php');`
?>
User presses a button that makes an ajax call ajax('references.php?count=1'); Then inside the references.php file I have something like:
<?php
$count = isset($_GET['count']) ? $_GET['count'] : 0;
?>
I also have other dynamic includes like this throughout the site that pass parameters. The problem happens when the user presses submit and there is a form error. So now to not duplicate code to include those extra field sets that where dynamically included, i created a function that will setup the include with the appropriate GET params.
<?php
function include_get_params($file) {
$parts = explode('?', $file);
if (isset($parts[1])) {
parse_str($parts[1], $output);
foreach ($output as $key => $value) {
$_GET[$key] = $value;
}
}
include($parts[0]);
}
?>
The function checks for query params, and automatically adds them to the $_GET variable. This has worked pretty good for my use cases.
Here is an example on the form page when called:
<?php
// We check for a total of 12
for ($i=0; $i<12; $i++) {
if (isset($_POST['references_name_'.$i]) && !empty($_POST['references_name_'.$i])) {
include_get_params(DIR .'references.php?count='. $i);
} else {
break;
}
}
?>
Just another example of including GET params dynamically to accommodate certain use cases. Hope this helps. Please note this code isn't in its complete state but this should be enough to get anyone started pretty good for their use case.
You can use $GLOBALS to solve this issue as well.
$myvar = "Hey";
include ("test.php");
echo $GLOBALS["myvar"];
If anyone else is on this question, when using include('somepath.php'); and that file contains a function, the var must be declared there as well. The inclusion of $var=$var; won't always work. Try running these:
one.php:
<?php
$vars = array('stack','exchange','.com');
include('two.php'); /*----- "paste" contents of two.php */
testFunction(); /*----- execute imported function */
?>
two.php:
<?php
function testFunction(){
global $vars; /*----- vars declared inside func! */
echo $vars[0].$vars[1].$vars[2];
}
?>
Try this also
we can have a function inside the included file then we can call the function with parametrs.
our file for include is test.php
<?php
function testWithParams($param1, $param2, $moreParam = ''){
echo $param1;
}
then we can include the file and call the function with our parameters as a variables or directly
index.php
<?php
include('test.php');
$var1 = 'Hi how are you?';
$var2 = [1,2,3,4,5];
testWithParams($var1, $var2);
Your question is not very clear, but if you want to include the php file (add the source of that page to yours), you just have to do following :
if(condition){
$someVar=someValue;
include "myFile.php";
}
As long as the variable is named $someVar in the myFile.php
I was in the same situation and I needed to include a page by sending some parameters... But in reality what I wanted to do is to redirect the page... if is the case for you, the code is:
<?php
header("Location: http://localhost/planner/layout.php?page=dashboard");
exit();
?>