I'm trying as a school assignment building a code for a customer list for a tire company. I have made everything work but i still need a function to be able to update a single customer and also echo a string with the specific id of each post in the .txt file. Here is all my code, because when i tried writing out each id from the array i got this:
Object of class Customer could not be converted to string in /Applications/MAMP/htdocs/douglas/classes_serialisering.php on line 51
This is the code i used $key(".$obj") . ....
Here is all the code for the program:
First: classes_serialisering.php
<?php
//
// Registrera alla klassfiler som behövs.
spl_autoload_register(function ($class) {
include 'classes/' . $class . '.class.php';
});
global $company;
$company = new Company("Ragnars Däckhotell");
//
// Lägg till lagerpost i textfilen
if(isset($_REQUEST["addPart"])){
if(strlen($_REQUEST["customername"])>0){
$company->addCustomer($_REQUEST["customername"], $_REQUEST["customertfn"], $_REQUEST["customerepost"], $_REQUEST["tirebrand"], $_REQUEST["status"]);
//
//Spara information till filen med lagerinformationen.
file_put_contents("../objdata.txt",serialize($company- >getCustomerList()));
}
unset($_REQUEST["addPart"]);
header("Location: classes_serialisering.php");
exit();
}
//
// Radera en post i lagerregistret
if(isset($_REQUEST["delPart"])){
$company->removeCustomer($_REQUEST["delPart"]);
//
// Spara all ny information till textfilen med lagerinfon.
file_put_contents("../objdata.txt",serialize($company- >getCustomerList()));
unset($_REQUEST["delPart"]); // Disable button press
header("Location: classes_serialisering.php");
exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<title> Webb 2 M3 </title>
<meta charset=utf-8/>
<style>
body {font: Verdana; font-size: 1em;}
</style>
</head>
<body>
<form action="" method="post">
<p>
<?php
//
// Skriv ut alla poster i registret kopplade till array id.
foreach($company->getCustomerList() as $key => $obj){
echo "<br/>" . $key."$obj .<br>". $obj->getcustomername() . ", " . $obj->getcustomertfn() . ", " . $obj->getcustomerepost() . ", " . $obj- >gettirebrand() . ", " . $obj->getstatus() . ", " . $obj->getdate() .
" <a href='classes_serialisering.php?delPart=$key'>Radera " . $obj- >getcustomername() . " </a>";
}
?>
</p>
<p>
Namn: <input type="text" name="customername" /><br/>
Telefonnummer: <input type="text" name="customertfn" /> <br/>
E-post: <input type="text" name="customerepost" /> <br/>
Märke & Dimension: <input type="text" name="tirebrand" /> <br/>
Status: <input type="text" name="status" /> <br/>
<input type="submit" name="addPart" value="Lägg Till Kund"/>
</p>
</form>
</body>
</html>
Here is company.class
<?php
interface RegistrerCustomer {
function addCustomer($customername, $customertfn, $customerepost, $tirebrand, $status);
function getCustomerList();
}
class Company implements RegistrerCustomer {
protected $companyname = '';
private $CustomerList = array();
function __construct($companyname){
$this->foretag = $companyname;
//Hämta textfil med kundlistan.
if(file_exists("../objdata.txt"))
$this->CustomerList = unserialize(file_get_contents("../objdata.txt"));
}
function setCompanyname($companyname){
$this->Companyname = $companyname;
}
function getCompanyname(){
return $this->Companyname;
}
function addCustomer($customername, $customertfn, $customerepost, $tirebrand, $status){
$this->CustomerList[] = new Customer($customername, $customertfn, $customerepost, $tirebrand, $status, Date('c'));
}
function getCustomerList(){
return $this->CustomerList;
}
function removeCustomer($ind){
unset($this->CustomerList[$ind]);
}
}
?>
Customer.class.php:
<?php
//
// En klass för all information som skall kunna lagras i textfilen med lagerinformationen
abstract class Customerpost {
abstract public function __construct($customername, $customertfn, $customerepost, $tirebrand, $status, $datum);
abstract function setcustomername($customername);
abstract function getcustomername();
abstract function setcustomertfn($customertfn);
abstract function getcustomertfn();
abstract function setcustomerepost($customerepost);
abstract function getcustomerepost();
abstract function settirebrand($tirebrand);
abstract function gettirebrand();
abstract function setstatus($status);
abstract function getstatus();
abstract function setdate($datum);
abstract function getdate();
}
//
// En extension för klassen ovan
class Customer extends Customerpost {
protected $customername = '';
protected $customertfn = '';
protected $customerepost = '';
protected $tirebrand = '';
protected $status = '';
protected $date = '';
function __construct($customername, $customertfn, $customerepost, $tirebrand, $status, $datum){
$this->customername = $customername;
$this->customertfn = $customertfn;
$this->customerepost = $customerepost;
$this->tirebrand = $tirebrand;
$this->status = $status;
$this->date = $datum;
}
function setcustomername($customername){
$this->customername = $customername;
}
function getcustomername(){
return $this->customername;
}
function setcustomertfn($customertfn){
$this->customertfn = $customertfn;
}
function getcustomertfn(){
return $this->customertfn;
}
function setcustomerepost($customerepost){
$this->customerepost = $customerepost;
}
function getcustomerepost(){
return $this->customerepost;
}
function setPnr($pnum){
$this->tfn = $customertfn;
}
function getPnr(){
return $this->customertfn;
}
function setEpost($email){
$this->customerepost = $customerepost;
}
function getEpost(){
return $this->customerepost;
}
function settirebrand($tirebrand){
$this->tirebrand = $tirebrand;
}
function gettirebrand(){
return $this->tirebrand;
}
function setstatus($status){
$this->status = $status;
}
function getstatus(){
return $this->status;
}
function setdate($datum){
$this->date = $datum;
}
function getdate(){
return $this->date;
}
}
?>
Any ideas of why it does not work to echo each id? And also, how should i make a function to be able to update each post by a button to the right of each post after filling out the form, then pressing 'update', like the 'Radera' button i have now, which is 'delete' in swedish.
As this hasn't been answered and you have clearly made a lot of effort, your issue lies with this line:
echo "<br/>" . $key."$obj .<br>". $obj->getcustomername() . ", " .$obj->getcustomertfn() . ", " .$obj->getcustomerepost() . ", " . $obj- >gettirebrand() . ", " . $obj->getstatus() . ", " . $obj->getdate() ." <a href='classes_serialisering.php?delPart=$key'>Radera " . $obj->getcustomername() . " </a>";
Specifically, you have done:
echo "<br/>" . $key."$obj .<br>"
(which looks like a typo)
This means you are echoing the key and the value, but, the value is actually a Customer object which echo will not attempt to convert to a string unless you provide a __tostring() method in your Customer class. http://php.net/manual/en/language.oop5.magic.php#object.tostring
You should either remove the $obj in that part of your code or provide a __toString() method in your Customer class so that echo knows how to convert the Customer object to a string.
I would also suggest choosing a consistent naming convention for your methods, usually either camelCase or snake_case, as this will make your code more readable.
Please ask the second part of your question separately as it's a different issue, and you have provided a lot of code to look through, which we all have to try to decipher. I think you are asking how to unserialize, update and then re-serialize your object, so those pages will be a good starting point.
Related
I'm trying to create a to do list. When creating new posts it should encode the information to json and put the information in a json array. But somehow it seems the information isn't encoded correctly and when trying to print the posts I get the error message "Invalid argument supplied for foreach()". I just can't find where the mistake is.
I'm fairly new at this so to complex answers might be to hard for me to understand.
Edit:
Adding the whole freaking code. Something is seriously wrong. 🤦♀️
index:
<?php
spl_autoload_register(function ($class) {
include $class . '.class.php';
});
$allPosts = new Lista;
if(isset($_REQUEST['addNewPost'])){
$allPosts->addNewPost($_REQUEST['ett'], $_REQUEST['tva'], $_REQUEST['tre']);
}
?>
<?php $page_title = "Att göra lista";
include("includes/header.php");
?>
<?php
include("includes/sidebar.php");
?>
<h2>Min att göra lista</h2>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
Uppgift: <input type="text" name="ett"/><br/>
Utfarare: <input type="text" name="tva"/><br/>
Senast: <input type="text" name="tre"/><br/>
<input type="submit" name="addNewPost" value="Lägg till post"/>
</form>
<?php
//Loopa igenom array
foreach ($allPosts->getTheList() as $key=>$val) {
echo "<section id='postPart'>" . $val->getEtt() . "<br/>" . $val->getTva(). " " . $val->getTre(). "</section><section id='buttonPart'><button type='button' name='klar'>Avklarad!</button> <button type='button' name='deletePost'>Ta bort</button>\n";
}
//echo "<section id='postPart'>" . $_REQUEST['one'] . "<br/>" . $_REQUEST['two'] . " " . $_REQUEST['three'] . "</section><section id='buttonPart'><button type='button' name='klar'>Avklarad!</button> <button type='button' name='deletePost'>Ta bort</button>\n";
var_dump($allPosts);
?>
</body>
</html>
Class: Lista:
<?php
class Lista{
public $theList=[];
function __construct(){
if(file_exists("text.json")>0)
$this->theList = json_decode(file_get_contents('text.json'), true);
}
function addNewPost($ett, $tva, $tre){
$posten = new Post ($ett, $tva, $tre);
array_push ($this->theList, $posten);
$jsonStr = json_encode($this->theList);
file_put_contents("text.json", $jsonStr);
}
function getTheList( ){
return $this->theList;
}
}
Class Post:
<?php
class Post{
public $ett;
public $tva;
public $tre;
function __construct ($ett, $tva, $tre){
$this->ett = $ett;
$this->tva = $tva;
$this->tre = $tre;
}
function getEtt():string{
return $this->ett;
}
function getTva(){
return $this->tva;
}
function getTre(){
return $this->tre;
}
}
Besides the typo, to json_encode an array of objects your need to make an exporter method which returns an array of each property or implement JsonSerializable
<?php
class Post implements JsonSerializable {
protected $whatIs = ' ';
protected $whoIs = ' ';
protected $whenIs = ' ';
function __construct($what,$who,$when){
$this->whatIs=$what;
$this->whoIs=$who;
$this->whenIs=$when;
}
public function jsonSerialize()
{
return get_object_vars($this);
}
}
$arr = [];
$arr[] = new Post(1,2,3);
echo json_encode($arr);
Result:
[{"whatIs":1,"whoIs":2,"whenIs":3}]
I think your problem is on this line:
$jsonStr = json_encode($this->$thePost, JSON_PRETTY_PRINT);
You might be trying to do this :
$jsonStr = json_encode($thePost, JSON_PRETTY_PRINT);
Since $thePost is an object, and not a property of your class. It could work if $thePost is a string that match a property name.
I am making a tool to convert steam profile urls to the different steam ids, whatever.
I have the different functions, triggered when submitting the URL of the profile with a form.
One of the function are, that it gets the avatar of the regarding steam profile.
Actually it gets the link of the image. What I can do is, echo an img element with the link, this wont give me any flexibility since I wont be really able to style etc that afterwards.
Now, the function of getting the avatar, is in the function of the submit form.
I tried just inserting the image URL into an img element.
<img src"<?php echo $avatar ?>">
Well, then I get a error message, saying "$avatar" is undefined, even though I defined it in my main php tags. I think that is due to the fact that it is done inside the form function, could be wrong though.
My main question now is, what could be a different approach to this? I need that in the form function because it should only be called then.
Maybe I just have to use the inconvenient way of echoing an img element every time.
Here is the actual code.
<form method="post">
<input type="text" name="profile_url">
<input type="submit" value="click" name="submit">
</form>
<div id="avatar-div" style="height:100px; width:100px;">
<img src="<?php echo $avatar; ?>">
</div>
the main php part
if(isset($_POST['submit']))
{
display();
}
function display() {
require_once 'steamid.class.php';
$input = $_POST["profile_url"];
$api_key = "xxxxxxxxxxxxxxx";
$id = new SteamID($input,$api_key);
if(substr_count($input, ' ') === strlen($input)) {
echo "Enter URL";
} else {
if ($id->resolveVanity()) {
$avatar = $id->toAvatar();
$communityid = $id->toCommunityID();
echo $communityid . ", " . " ";
$steamid = $id->toSteamID();
echo $steamid . ", " . " ";
$userid = '[U:1:'.$id->toUserID().']';
echo $userid . ", " . " ";
} else {
echo "Profile wasnt found!";
}
}
}
I'm refactoring my answer based on the conversation we had. Here is the recommended PHP code.
function urlCheck() {
$input = $_POST["profile_url"];
if(empty($input)) {
echo "Enter URL";
return false;
} else {
return true;
}
}
function display() {
require_once 'steamid.class.php';
$api_key = "xxxxxxxxxxxxxxx";
$id = new SteamID($input,$api_key);
if (urlCheck()) {
if ($id->resolveVanity()) {
$communityid = $id->toCommunityID();
echo $communityid . ", " . " ";
$steamid = $id->toSteamID();
echo $steamid . ", " . " ";
$userid = '[U:1:'.$id->toUserID().']';
echo $userid . ", " . " ";
return $id->toAvatar();
} else {
echo "Profile wasn't found!";
}
}
}
You haven't mentioned where you're running display(), or where you're expecting the output (echo) to display. I can only assume you want it at the top of the page. Let me explain how to use this.
<head>
$avatar = display();
</head>
<body>
<div id="avatar-div" style="height:100px; width:100px;">
<img src="<?= $avatar ?>">
</div>
</body>
Basically the way this works, is that wherever you run display(), is where the echoes will output (in this case, before the body). Wherever you echo $avatar is where the id will be displayed. I hope this works for you.
Take a look at PHP's Variable Scope
Any variable used inside a function is by default limited to the local function scope.
To fix this problem, use the global keyword. This way you will explicitly set $avatar; as a global variable so it can be used outside of your display() function.
Here is how it would work for your example:
function display() {
global $avatar;
// Rest of your display() function
// Set $avatar somewhere in here
}
display(); // Actually call display so $avatar is set
<div id="avatar-div" style="height:100px; width:100px;">
<img src="<?=$avatar;?>">
</div>
I tried to generate radio buttons dynamically from my database, but I am stuck where I need to limit (check if the user selected at least 5 groups(5 different games) of the generated button before submission into the database.
<?php while($row = mysql_fetch_array($query)) : ?>
<?php
$home_team = $row\['home_team'\];
$away_team = $row\['away_team'\];
$game_id = $row\['game_id'\];
$team_joined = $home_team.' VS '.$away_team;
$teams = $home_team.'vs'.$away_team;
$match_day = #$row\['match_day'\];
$match_time = #$row\['match_time'\];
date_default_timezone_set('Africa/Lagos');
$time = date('l, jS F h:iA');
?>
<?php
if (isset($_POST\['submit'\])) {
$amount = mysql_real_escape_string($_POST\['amount'\]);
$games = #$_POST\[''.$game_id.''\];
$countGames = count($games);
echo $countGames;
/* if ($countGames < 3) {
$errorfill = "please selecet 3 games";
} else { */
if ($amount) {
foreach ($games as $game) {
$gameValue = $game;
if ($amount < $bank_verify) {
$money_left = $bank_verify - $amount;
$deduct_query = mysql_query("UPDATE bank SET money_unit='$money_left' WHERE username='$username' ");
$query_start_game = mysql_query("INSERT INTO bet10_players VALUES('', '$username', '$amount',
'$gameValue', '$team_joined', '$game_id','$time', '$pin', '$match_day', '$match_time')") or die(mysql_error());
header("Location: print.php?pin=$pin&time=$time");
} else {
$errorbank = "SORRY!!! You do not have enough units to stake this bet";
}
}
} else {
$errorfill = "You have not entered any amount";
}
//}
}
?>
<form role="form" action="#" method="post">
<h5><?php echo $team_joined; ?></h5>
<h5><?php echo '<span style="color:#f0ad4e;">' . $match_day . ', ' . $match_time . '</span>'; ?></h5>
<label><input type="radio" name="<?php echo '' . $game_id . '\[' . $game_id . '\]'; ?>" value="<?php echo $home_team; ?>">Home</label>
<label><input type="radio" name="<?php echo '' . $game_id . '\[' . $game_id . '\]'; ?>" value="Draw ">Draw</label>
<label><input type="radio" name="<?php echo '' . $game_id . '\[' . $game_id . '\]'; ?>" value="<?php echo $away_team; ?>">Away</label>
<hr>
<?php endwhile; ?>
<div class="form-group">
<input type="text" name="amount" class="form-control" placeholder="Enter your amount here">
<input type="submit" name="submit" value="submit" class="btn btn-danger" style="margin-bottom: 10px;">
This is the link to the image of what I intend to achieve with these code https://i.stack.imgur.com/Xif8M.png
Because there are a lot of issues just with what you have, I can not actually "fix" what you have in good conscience. The mysql_* library is deprecated (removed in >= PHP7) and you are escaping a bunch of things you don't need to, as I noted. Also, as noted, using # to silence warnings is not a good idea, you will want to just fix them. If I were to do this, I would have a series of classes that I would create. I would also do an .htaccess or web.config (Windows) to force everything through the index page, but I suspect from your script you have individual pages, so I will go on that notion:
First off, I would probably create a base app that had some simple, helpful features.
/vendors/App.php
<?php
class App
{
# Easily return post values even if they don't exist without drawing errors
public function getPost($key=false)
{
if(!empty($key))
return (isset($_POST[$key]))? $_POST[$key] : false;
return $_POST;
}
# Easily return session values even if they don't exist without drawing errors
public function getSession($key=false)
{
if(!empty($key))
return (isset($_SESSION[$key]))? $_SESSION[$key] : false;
return $_SESSION;
}
# Used to render pages
public function render($file)
{
ob_start();
include($file);
$data = ob_get_contents();
ob_end_clean();
return $data;
}
}
/vendors/Game.php
If you create a base Game class, you will better be able to control Game-related base features
<?php
class Game extends App
{
protected $games = array();
protected $errors = array();
protected $con;
# Inject the database
public function __construct(\PDO $con)
{
$this->con = $con;
}
# Fetch a list (or just one) game
public function gameList($game_id = false)
{
$where = (!empty($game_id))? " WHERE game_id = '{$game_id}'" : "";
$this->games = array();
$query = $this->con->query("SELECT * FROM games{$where}");
while($result = $query->fetch(PDO::FETCH_ASSOC)) {
$this->games[] = $result;
}
return $this;
}
# Send back the games if stored
public function getGames($first = false)
{
# If you you only need one row returned
if($first)
return (isset($this->games[0]))? $this->games[0] : false;
# Return entire list
return $this->games;
}
# Count how many are currently stored
public function getCount()
{
return count($this->games);
}
}
/vendors/Game/Observer.php
If you create a base Game Observer class, you will better be able to control listeners and processing of requests.
<?php
namespace Game;
class Observer extends \Game
{
protected $time;
# This is a general listener method, listens for the post
# It needs work, I don't know where you are getting some of these
# variables from...I am injecting for example-sake
public function listen($bank_verify,$pin,$min=5)
{
# Listen for the submission
if(empty($this->getPost('submit')))
return $this;
elseif(empty($this->getSession('username')))
return $this;
# Fetch the post values, fitler empty
$REQUEST = array_filter($this->getPost('game'));
# See if there are at least 5 submitted
if(count($REQUEST) < $min) {
$this->errors[] = 'You must have at least '.$min.' selected';
return $this;
}
foreach($REQUEST as $id => $value) {
$this->games[$id] = $value;
}
$username = $this->getSession('username');
$amount = $this->getPost('amount');
if($amount < $bank_verify) {
$money_left = $bank_verify - $amount;
$this->updateAccount($money_left,$username);
foreach($this->games as $id => $value) {
$query_start_game = $this->con->prepare("INSERT INTO bet10_players VALUES('',?,?,?,?,?,?,?,?,?)");
$query_start_game->execute(array(
$username,
$amount,
$gameValue,
$team_joined,
$game_id,
$time,
$pin,
$match_day,
$match_time
));
}
}
else {
$this->errors[] = 'Not enough money.';
return $this;
}
header("Location: print.php?pin=$pin&time=$time");
exit;
}
# This sets the timezone (just once)
public function setTime($tz = 'Africa/Lagos')
{
date_default_timezone_set($tz);
$this->time = date('l, jS F h:iA');
return $this;
}
# This will update the account safely
public function updateAccount($money_left,$username)
{
$sql = "UPDATE bank SET money_unit = ? WHERE username = ?";
$query = $this->con->prepare($sql);
$query->execute(array($money_left,$username));
return $query;
}
# This probably needs work, but you should insert using this method
public function addBets($array,$table='bet10_players')
{
$fill = "'', ".implode(', ',array_fill(0,count($array),'?'));
$sql = "INSERT INTO `{$table}` VALUES({$fill})";
$query = $this->con->prepare($sql);
$query->execute($array);
return $query;
}
# Returns the time if need be...
public function getTime()
{
return $this->time;
}
}
/config.php
I would create this page to be included on all pages at the top. It can be expanded and is good to keep everything consistent like your root path and such.
<?php
# start the session
session_start();
# Create some useful defines
define('DS',DIRECTORY_SEPARATOR);
define('ROOT_DIR',__DIR__);
define('CLASSES',ROOT_DIR.DS.'vendors');
define('DB_HOST','localhost');
define('DB_NAME','databasename');
define('DB_USER','root');
define('DB_PASS','');
# Create a class autoloader which turns a \Namespace\Class into a directory
# like /var/html/domain/mydomain/vendor/Namespace/Class.php
spl_autoload_register(function($class) {
$path = str_replace(DS.DS,DS,CLASSES.DS.str_replace('\\',DS,$class).'.php');
if(is_file($path))
include_once($path);
});
/index.php
<?php
# Check if we are inside the class, if not, do so
if(!isset($this)) {
# Include the config file
require_once(__DIR__.DIRECTORY_SEPARATOR.'config.php');
# Create your connection (you should expand on this...)
$con = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME,DB_USER,DB_PASS);
# Create a Game object
echo (new \Game\Observer($con))->render(__FILE__);
# Stop further execution
exit;
}
# Now we are inside the \Game\Observer class, so you can now use $this
# Set the time and add a listener for post
$this->setTime();
# Since there is no indication of where some of these variables come from,
# this listen method will need attention...actually all the elements from the
# \Game and \Game\Observer need review, but they should be close enough to figure out
$this->listen($bank_verify,$pin);
?>
<form role="form" action="" method="post">
<?php
# $this->gameList()->getGames() should just return an array from your database
foreach($this->gameList()->getGames() as $row) {
$team_joined = $row['home_team'].' VS '.$row['away_team'];
$teams = $row['home_team'].'vs'.$row['away_team'];
?>
<h5><?php echo $team_joined; ?></h5>
<h5><span style="color:#f0ad4e;"><?php echo $row['match_day'].', '.$row['match_time'] ?></span></h5>
<input type="hidden" name="game[<?php echo $row['game_id'] ?>]" value="" />
<label><input type="radio" name="game[<?php echo $row['game_id'] ?>]" value="<?php echo $row['home_team']; ?>" />Home</label>
<label><input type="radio" name="game[<?php echo $row['game_id'] ?>]" value="draw" />Draw</label>
<label><input type="radio" name="game[<?php echo $row['game_id'] ?>]" value="<?php echo $row['away_team']; ?>" />Away</label>
<hr>
<?php
}
?>
<div class="form-group">
<input type="text" name="amount" class="form-control" placeholder="Enter your amount here" />
<input type="submit" name="submit" value="submit" class="btn btn-danger" style="margin-bottom: 10px;" />
</div>
</form>
When you process the post, you will retrieve data from the database based on the game id, so you should get all the variables you need except for ones that have no indication of origin in your script. Anyway, this is what I would do if I were you. One final note, I have not tested any of this, some of the methods are based off a framework I use, but I think it's a safer version of your script where sql injection is concerned, though you will have to research what some of this is doing...
So, I'm trying to create a very basic form using HTML/PHP. Yes, I am a beginner.
I'm going for something along the lines of this.
But instead, I'm getting this.
The form has text input for a few fields such as "Name", "Username", "Email", and then a drop down list to select a browser of your choice. Very basic stuff. I'm trying to return the user input to the screen. The only problem is that when the page loads, I have an empty drop-down box with no browsers to choose from.
I created a PHP class called "Select" that is very simple. It has a few basic functions. I also created two other files, postInfo.php (used to return user info) and userForm.php (the file to create the form itself).
I've tried debugging and testing and I'm almost certain there is nothing wrong the Select class, and the two other files have been run through code validators and nothing comes up. Everything should be fine, but this is starting to give me a headache.
Here's my Select class:
<?php
$browsers = array ("Firefox", "Chrome", "Internet Explorer", "Safari", "Opera", "Konqurer", "Other");
class Select {
private $name;
private $value;
#Getter & Setter methods
public function setName($name) {
$this -> name = $name;
}
public function getName() {
return $this -> name;
}
public function setValue($value){
if (!is_array($value)){
echo ("No array values found.");
}
$this->value = $value;
}
public function getValue() {
return $this -> value;
}
#Method to implement browsers
private function createBrowserList($value){
foreach($value as $val){
echo "<option value=\"$val\">" . $val . "</option>\n";
}
}
#Method to create the selection field
public function createSelections(){
echo "<select name=\"" . $this->getName() . "\">\n";
$this -> makeOptions ($this->getValue());
echo "</select>" ;
}
}
?>
My postInfo.php file:
<?php
$name = $_POST["name"];
$username = $_POST["username"];
$email = $_POST["email"];
$browser = $_POST["browser"];
echo "$name <br>";
echo "$username <br>";
echo "$email <br>";
echo "$browser <br>";
?>
And my userForm.php file (used to create the actual form)
<html>
<body>
<form action ="postInfo.php" method="post" id="form">
Name:<input type ="text" name="name"> <br>
Username:<input type ="text" name="username"> <br>
Email:<input type ="email" name="email"> <br>
<?php
include "selectClass.php";
$selection = new Select();
$selection -> setName("Select Browser");
$selection -> setValue($browsers);
$selection -> createSelections();
?>
<input type = "submit" name = "submit" value = "Go!">
</form>
</body>
</html>
public function createSelections(){
echo "<select name=\"" . $this->getName() . "\">\n";
$this -> createBrowserList ($this->getValue());
echo "</select>" ;
}
You could use something like this:
<?php
$browservalue=array();
$browsers = array ("Firefox", "Chrome", "Internet Explorer", "Safari",
"Opera", "Konqurer", "Other");
foreach ($browsers as $x){
$browservalue[]=strtolower($x);
}
$browsersqnty=sizeof($browsers);
?>
and then inside the html where you want to echo browsers you can do this:
Browsers:<select name='browsers'><?php
for($i=0;$i<$browsersqnty;$i++){
echo "<option value='$browservalue[$i]'>$browser[$i]</option>";
}
?></select>
I have referred to similar questions like this and have done exactly the same way as it should have been but no success. Hence I would appreciate if some one can help me with this
I have a file called view.php which calls a function from a class based on a switch case condition. This function displays the output on the page with few links. When clicked on the link it calls another function which sits in my first function. But obviously when I click my link, nothing happens. That's my code.
view.php
require_once(..'/functions.php');
$functions = new myfile_functions();
<form method="post" action="view.php"><div>
<p><select name="potentialareas" id="potentialareas">
<option style="font-weight:bold;" value="-1">Select an area to view </option>
<?php
foreach($accessareas as $accessarea){
echo "<option value='".$accessarea->id."'>".$accessarea->name. " - " . $accessarea->reporttype. "</option>";
}
?>
</select>
</p>
<p><input name="view" id="view" type="submit" value="View" title="view" /><br /></p>
</div></form>
<div style="border-top:1px dotted #ccc;"></div>
<?php
if(isset($_POST['view']))
{
$hierarchyid = $_POST['potentialareas'];
$reporttype = $DB->get_record_sql("some query");
switch($reporttype->reporttype)
{
case "D Report":
$functions->getDepartmentReport($hierarchyid);
break;
case "S Report":
$functions->getSectionReport($hierarchyid);
break;
case "A Report":
$functions->getAreaReport($hierarchyid);
break;
}
}
functions.php
class myfile_functions(){
function getDepartmentReport($departmentid)
{
global $USER, $CFG, $DB;
$dname = $DB->get_record_sql("some query");
$output = "<div id='actualreport'><p><b>" . $dname->name. " Department Report</b></p>";
$output .= "<p>Activities started: </p>";
$output .= "<p>Activities Completed: </p></div>";
$output .= "<div id='separator' style='border-top:1px dotted #ccc;'></div>";
$output .= "<div id='listofsections'><p><b><i>Select the following for a more detailed report.</i></b></p>";
$snames = $DB->get_records_sql('some query');
foreach($snames as $sname)
{$output .= "<p>" .$sname->name. " <a href='view.php?section=" .$sname->id. "' name='section'><i>view report</i></a></p>";
}
$output .= "</div>";
if(isset($_GET['section']))
{
$this->getSectionReport($_GET['section']);
}
echo $output;
}
function getSectionReport($sectionid)
{
global $USER, $CFG, $DB;
$sname = $DB->get_record_sql("some query");
$output = "<div id='actualreport'><p><b>" . $sname->name. " Report</b></p>";
$output .= "<p>Num Users: </p>";
$output .= "<p>Activities Completed: </p></div>";
$output .= "<div id='separator' style='border-top:1px dotted #ccc;'></div>";
$output .= "<div id='listofareas'><p><b><i>Select the following for a more detailed report.</i></b></p>";
$anames = $DB->get_records_sql('some query');
foreach($anames as $aname)
{$output .= "<p>" .$aname->name. " <a href='view.php?area=" .$aname->id. "' name='view' id='view'><i>view report</i></a></p>";
}
$output .= "</div>";
if(isset($_GET['area']))
{
$areaid = $_GET['area'];
$this->getAreaReport($areaid);
}
echo $output;
}
Similarly another function calling the above function, n so on.
function getAreaReport($id)
{ .. same content but calling another function...}
So when ever I click my view report link, I get the id appended id in my querystring, something like
http://mydomain.com/view.php?section=5
Ideally the contents of getSectionReport() should get printed but its not. Please point out what is it that I am doing wrong.
Thanks in advance.
What's your main method for displaying everything? At the moment you have three functions, all of which link to eachother in various ways, but it doesn't look as if you're instantiating anything first. The PHP is being fed a parameter in your URL, sure, but if a class isn't instantiated and a method declared, how does it know what you want it to do?
For myfile.php, maybe you should do something like:
class MyFile
{
public function other_function()
{
// Various stuff
return 'stuff';
}
public function other_other_function()
{
// Various other stuff
return 'other stuff';
}
public function page_view($file_id)
{
$var = $this->other_function($file_id);
return $this->other_other_function($var);
}
}
$class = new MyFile;
echo $class->page_view($_GET['id']);
If the two functions are part of a class (as your comment above hints), then the call should be written as
$this->getUserReport($id);
If you're accessing a sibling function inside the same class, use:
class ClassName
{
public function sibling_function()
{
return 'Hey bro!';
}
public function my_function()
{
return $this->sibling_function();
}
}
If not, use the standard:
public function my_function()
{
return sibling_function();
}
If you're still having trouble, make sure your class is properly instantiated. There's no point calling another function if you're not even instantiating the class first:
$obj = new ClassName;
echo $obj->my_function();