HTML form not appearing properly - Gives odd results - php

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>

Related

Error code "Invalid argument supplied for foreach()" when using json_encode (oop, php)

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.

Other way of displaying image, when only having the link from php

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>

Modify form using a dropdown (select) menu

So I'm trying to get records from database by using this code, but I'm only getting else alert message. Can somebody say what I am doing wrong or where is an error in the code? It populates the dropdown, but like I said I don't get the result only the alert message:
<form method='post' action='grafikastest.php'>
<select id="name">
<?php
include_once ('inc\connect.php');
echo "Pasirinkite datÄ…: &nbsp";
$date = strtotime("+0 day");
$dtt=date('Y-m-d', $date);
echo "<option value=$dtt>$dtt</option>";
$date = strtotime("+1 day");
$dtt=date('Y-m-d', $date);
echo"<option value=$dtt>$dtt</option>";
$date = strtotime("+2 day");
$dtt=date('Y-m-d', $date);
echo "<option value=$dtt>$dtt</option>";
$date = strtotime("+3 day");
$dtt=date('Y-m-d', $date);
echo "<option value=$dtt>$dtt</option>";
$date = strtotime("+4 day");
$dtt=date('Y-m-d', $date);
echo "<option value=$dtt>$dtt</option>";
$date = strtotime("+5 day");
$dtt=date('Y-m-d', $date);
echo "<option value=$dtt>$dtt</option>";
$date = strtotime("+6 day");
$dtt=date('Y-m-d', $date);
echo "<option value=$dtt>$dtt</option>";
$sql = "SELECT ID, data, laikas, laikas2 FROM vizitai4 WHERE darb_stat NOT LIKE 'Atlikta' and data LIKE '%" . $dtt . "%' OR
darb_stat IS NULL and data LIKE '%" . $dtt . "%' GROUP BY laikas";
$result = mysql_query($sql);
//rodymas lenteleje
echo $dtt;
echo "<table id=t01>
<tr>
<th>Data</th>
<th>Remonto pradĹľia</th>
<th>Remonto pabaiga</th>
</tr>";
if(mysql_num_rows($result) > 0) {
while( $row=mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['data'] . "</td>";
echo "<td>Remontas prasideda nuo " . $row['laikas'] . " </td>";
echo "<td>Numatomas remonto baigimo laikas " . $row['laikas2'] . " </td>";
echo "<td style='display: none;'><form method=post>
<input name=id type=hidden value='".$row['id']."';>
</form></td>";
echo "</tr>";
}
}else{
echo "<script>alert('Šios dienos įrašų nėra');</script>";
}
echo "</table>";
?>
</select>
<input type="submit" name="submit" value="Ieskoti">
</form>
</body>
</html>
From our exchange, the core of the issue is that you want interaction with the form to change the form itself and that you are trying to accomplish this with only PHP. Since PHP runs once to generate the page, you can not interact with the form elements after and have PHP react to those changes. You need a triggering effect that will re-query PHP. This is a job for a client-side language such as JavaScript.
Since you asked for an example here is a basic one. It is no easy task and has a bunch of moving parts, so I have a feeling that if you "barely know these things..." with what you have now, you will really be in the dark with this answer.
Follow the instruction and it should work for you. I have tested most of this (or have copied snippets from scripts I use) so pay attention to what things are called and where they are placed and read the notation. I suggest you create this directory/file structure as I have it, then test it out there before you attempt to do any modification to your working document(s). Once you do this stuff, if you don't know what you are doing it's near impossible to troubleshoot. Also take note I can not, in good conscience, answer this question without removing the reference to mysql_, those functions are deprecated or removed completely (php7):
/config.php
<?php
// This page goes on every main page of your site
// Comment out the error lines when live,
// you don't want errors showing on your page except in test
session_start();
ini_set("display_errors",1);
error_reporting(E_ALL);
define('DB_HOST','yourdbhost');
define('DB_USERNAME','yourdbusername');
define('DB_PASSWORD','yourdbpass');
define('DB_NAME','yourdbname');
define('SITE_ROOT',__DIR__);
define('DS', DIRECTORY_SEPARATOR);
define('CLASS_DIR', SITE_ROOT.DS.'core'.DS.'classes');
define('FUNCTION_DIR', SITE_ROOT.DS.'core'.DS.'functions');
require_once(FUNCTION_DIR.DS.'autoloader.php');
// This will help to autoload your classes
// **RESOURCE:** http://php.net/manual/en/function.spl-autoload-register.php
spl_autoload_register('autoloader');
// put whatever else you want on this page to make available to your site.
// You don't need the database connection however
/core/functions/makeOptions.php
<?php
/*
** #description This function uses a for loop to make your options
** You need to think how to use php to make your script(s)
** for you
** **RESOURCE:** http://php.net/manual/en/control-structures.for.php
** #param $max [int] This is how many options the function will make
*/
function makeOptions($max = 6)
{
for($i = 0; $i <= $max; $i++) {
$date = strtotime("+".$i." day");
$dtt = date('Y-m-d', $date);
echo '<option value="'.$dtt.'">'.$dtt.'</option>'.PHP_EOL;
}
}
/core/functions/autoloader.php
<?php
/*
** #description This function is used to autoload classes
** #param $class [string] This is automated and is populated by spl_autoload_register()
** **RESOURCE:** http://php.net/manual/en/function.spl-autoload-register.php
*/
function autoloader($class)
{
if(class_exists($class))
return true;
if(is_file($inc = CLASS_DIR.DS.$class.".php"))
include_once($inc);
}
/page1.php
<?php
// Include our config file
require_once(__DIR__.DIRECTORY_SEPARATOR.'config.php');
// Include the function to create our options
include_once(FUNCTION_DIR.DS.'makeOptions.php');
?><!DOCTYPE html>
<html>
<head>
<!-- include in head with anything else you need -->
<!-- **RESOURCE:** http://www.jquery.com/ -->
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script>
$(document).ready(function(){
// Observe any change made to select with name=name
$(this).on('change','select[name=name]',function() {
// get the value of that selection
var thisVal = $(this).val();
// Use ajax to query page2.php
// **RESOURCE:** http://api.jquery.com/jquery.ajax/
$.ajax({
// This is the link that will load the contents of the form
url: '/page2.php',
data: {
// This is equivalent to $_POST['name']
"name":thisVal
},
type: 'POST',
success: function(response) {
// On success of the ajax, this will post the contents of
// page2.php into the div with id=loadspot
$("#loadspot").html(response);
}
});
});
});
</script>
</head>
<body>
<form method='post' action='grafikastest.php'>
<!--
I am not sure the placement of this text, but it can not be
in the middle of a drop down
-->
Pasirinkite datÄ…: &nbsp
<select id="name" name="name">
<option value="">Select</option>
<!-- Apply the options function -->
<?php makeOptions(); ?>
</select>
<!-- This is where you will load the contents of the dropdown via ajax -->
<div id="loadspot"></div>
<input type="submit" name="submit" value="Ieskoti">
</form>
</body>
</html>
/core/classes/Database.php
<?php
/*
** #description This class is your new database which replaces your `mysql_`
** **RESOURCE:** http://php.net/manual/en/pdo.connections.php
*/
class Database
{
// static elements are kind of like a global
private static $singleton;
private static $con;
// This will save the class for reuse
public function __construct()
{
if(self::$singleton instanceof Database)
return self::$singleton;
self::$singleton = $this;
}
// This is the connection to the database
public function connect()
{
if(self::$con instanceof PDO)
return self::$con;
// Review the PDO class for instruction how to make this
// connection better using some PDO presets (Emulation of prepares, etc)
// **RESOURCE** http://php.net/manual/en/pdo.constants.php
self::$con = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME,DB_USERNAME,DB_PASSWORD);
return self::$con;
}
}
/core/classes/qEngine.php
<?php
/*
** #description This class is what you use to safely query your database
** **RESOURCE:** http://php.net/manual/en/pdo.prepare.php
** **RESOURCE:** http://php.net/manual/en/pdo.query.php
** **RESOURCE:** http://php.net/manual/en/pdostatement.fetch.php
**
*/
class qEngine
{
private static $con;
private $query;
public function query($sql = false,$bind = false)
{
// This checks if the connection is already saved
// You can also use "dependency injection" to pass your
// database connection to this class. I prefer to use
// a static connection but here is how that dependency works:
// **RESOURCE** http://code.tutsplus.com/tutorials/dependency-injection-in-php--net-28146
// **RESOURCE** https://en.wikipedia.org/wiki/Dependency_injection
if(!(self::$con instanceof PDO)) {
// Makes connection
$dbEngine = new \Database();
self::$con = $dbEngine->connect();
}
// Creates a bind array
// **RESOURCE** http://php.net/manual/en/pdostatement.bindvalue.php
// **RESOURCE** http://php.net/manual/en/pdostatement.execute.php (Example #2)
// **RESOURCE** http://php.net/manual/en/pdostatement.bindparam.php
if(!empty($bind)) {
$bArray = false;
foreach($bind as $key => $value) {
$bKey = ":{$key}";
$bArray[$bKey] = $value;
}
}
// If there is a bind array, it will run a prepare
if(!empty($bArray)) {
$this->query = self::$con->prepare($sql);
$this->query->execute($bArray);
}
// If no bind, it will run a straight query
else {
$this->query = self::$con->query($sql);
}
// This returns the object for method chaining
// **RESOURCE** http://stackoverflow.com/questions/3724112/php-method-chaining
return $this;
}
public function getResults()
{
// This will check that a query has been made
if(empty($this->query))
return 0;
// This will loop through the results and save to 1D array
while($result = $this->query->fetch(PDO::FETCH_ASSOC))
$row[] = $result;
// This will return either the array or a "0"
return (!empty($row))? $row : 0;
}
}
/core/functions/getListByDate.php
<?php
/*
** #description This function will query your database safely
** #param $date [string] Receives a date by string
*/
function getListByDate($date)
{
$bind = array('%'.$date.'%','%'.$date.'%');
return (new \qEngine()) ->query("SELECT `ID`,`data`,`laikas`,`laikas2`
FROM `vizitai4`
WHERE `darb_stat`
NOT LIKE 'Atlikta'
AND `data`
LIKE :0
OR `darb_stat`
IS NULL AND `data`
LIKE :1
GROUP BY `laikas`",$bind)
->getResults();
}
/page2.php
<?php
// Include our config file
require_once(__DIR__.DIRECTORY_SEPARATOR.'config.php');
// Include the function to query the database
include_once(FUNCTION_DIR.DS.'getListByDate.php');
// This is the page that the AJAX queries from page1.php
// See if the post has been made
if(!empty($_POST['name'])) {
// Fetch data from database
$vizitai4 = getListByDate($_POST['name']);
?>
<table id="t01">
<tr>
<th>Data</th>
<th>Remonto pradĹľia</th>
<th>Remonto pabaiga</th>
</tr>
<?php
if($vizitai4 != 0) {
foreach($vizitia4 as $row) {
?> <tr>
<td><?php echo $row['data']; ?></td>
<td>Remontas prasideda nuo <?php echo $row['laikas']; ?></td>
<td>Numatomas remonto baigimo laikas <?php echo $row['laikas2']; ?> </td>
<td style="display: none;"><input name="id[]" type="hidden" value="<?php echo $row['id']; ?>" /></td>
</tr>
<?php
}
}
else {
?>
<script>
alert('Šios dienos įrašų nėra');
</script>
<?php
}
?>
</table>
<?php
}
Here is the basic construct of what is happening:

Class could not be converted to string

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.

(EDITED QUES) PHP - Call function within another function

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();

Categories