call isset from function inside class - php

I have not been able to find out how to do this, but I think that it can be done.
I want to receive information about name ($ime) and display drugiDio() after I get that. I am using isset as I also want to not display prviDio() after input of name, but I think that that part I can find alone.
Here is the code I tried:
<?php
class igra {
function prviDio() {
global $lang;
$kreni = $lang['kreni'];
echo "<h1>".$lang['naslov']."</h1><p>".$lang['opis']."</p>";
echo '<form metod="post">'
.$lang['unesite-ime'].
'<input name="ime" type="text" id="ime" size="40" maxlength="40" /><br /><br />
<input type="submit" name="kreni" value="'.$kreni.'" /></form>';
}
function drugiDio() {
global $lang;
$ime=$_GET['ime'];
echo $lang['vase-ime']. $ime;
}
}
$igra = new igra;
echo $igra->prviDio();
if(isset($igra->$_GET['kreni'])) {
echo $igra->drugiDio();
}
?>
What can I do with this for it to work?:
if(isset($igra->$_GET['kreni'])) {
echo $igra->drugiDio();
}
I also tried
if(isset($igra->_GET['kreni'])) {
echo $igra->drugiDio();
}
and many other combinations but none of them don't work...
Text from variables is in language files. This is just the PHP part. On the page everything is visible, and it works fine when I echo name without isset() like echo $igra->drugiDio();.

Do this:
if(isset($_GET['kreni'])) {
echo $igra->drugiDio();
}
Note:
$_GET and $_POST are superglobal variables so you can access them directly, provided that they are set. For more information please read the manual here.

Related

PHP class, html forum, print $_POST Array on page

i am beginner php programmer, iv been trying to create a small program that takes input from a forum and then after submission i want it to be printed on the screen. simple and easy i thought, iv been trying and suspiciously it seems to work fine for 1 text field, when i added the remaining 2 text fields called [fam][user] my code stops returning the content to the screen. also i started to recieve an error of an unindex array, therefore i had to use isset to counter this problem, and also, why does my code call the destructor although i never implicitly set my destructor. i dont know how to ask these questions because the errors arent consistent.
code doesnt print my [name][fam][user]
code prints [name] when everything about [fam][user] are ommited from the code.
-code sometimes called the destructor
-code doesnt clear html previous input(e.g, when working with the one text field, lets say i input the [name] john, and click submit it
displays submit, then,i refresh the page, and the name john is still
displayed, why doesnt the destructor clear the memory of name from my
submission.
<form class="nameform" action="book.php" method="post">
<input type="text" name="Name" value="1">
<input type="text" name="Fam" value="2">
<input type="text" name="User" value="3">
<input type="button" name="submit" value="Submit">
</form>
private $name; private $familyName; private $userName;
function __construct($names,$familyNames,$userNames)
{
$this->name = $names;
$this->familyName = $familyNames;
$this->userName = $userNames;
}
function getName()
{
return $this->name;
}
function getFamilyName()
{
return $this->familyName;
}
function getUserName()
{
return $this->userName;
}
public function __destruct()
{
echo "destroyed again";
$this->name;
$this->familyName;
$this->userName;
}
}
if(!isset( $_POST["Name"])||!isset($_POST["Fam"])||!isset($_POST["User"]))
{
echo "Please fill in the data";
} else {
$p1 = new Person($_POST["Name"],$_POST["Fam"],$_POST["User"]);
print $p1->getName();
print $p1->getFamilyName();
print $p1->getUserName();
print_r($_POST);
}
// $n = $_POST["Name"];
// $f = $_POST["Fam"];
// $u = $_POST["User"];
// $p1 = new Person($_POST["Name"],$_POST["Fam"],$_POST["User"]);
?>
code doesnt print my [name][fam][user]
You never echo them out of the destuctor
public function __destruct()
{
echo "destroyed again";
$this->name; //<---- does nothing
$this->familyName;
$this->userName;
}
So I am not sure what this is supposed to do. You have them down at the bottom
print $p1->getName();
print $p1->getFamilyName();
print $p1->getUserName();
But the only thing you'll get from the destruct method is
"destroyed again"
And you will only see that if everything in the form is set. Which it always is when the form is submitted, because type text is always submitted with its form.
Which brings me to this, you should be checking empty instead of isset there
if ('POST' === $_SERVER['REQUEST_METHOD']) { //check if POST
if(empty($_POST["Name"])||empty($_POST["Fam"])||empty($_POST["User"])){
echo "Please fill in the data";
} else {
$p1 = new Person($_POST["Name"],$_POST["Fam"],$_POST["User"]);
print $p1->getName();
print $p1->getFamilyName();
print $p1->getUserName();
print_r($_POST);
}
}
Note that anything falsy will be empty, false, [], '', 0, '0', null etc.
I don't know if this solves all of you problems, but these things could produce some of the behaviour you are experiencing.
Another more advance way to check these is like this:
if ('POST' === $_SERVER['REQUEST_METHOD']) { //check if POST
$post = array_filter( $_POST, function($item){
return strlen($item); //any thing of a length of 0 is removed
});
if(count($post) != count($_POST)){
foreach(array_diff_key( $_POST, $post) as $missing=>$empty) {
echo "Please fill in $missing\n";
}
}else{
$p1 = new Person($_POST["Name"],$_POST["Fam"],$_POST["User"]);
print $p1->getName();
print $p1->getFamilyName();
print $p1->getUserName();
print_r($_POST);
}
}
Output
Please fill in Name
Please fill in Fam
You can test it online Here
Cheers!

Strange table update codeigniter $this->db->update

I'm having a problem with an update of one table in the db. I always use the same approach and I have no problem. Although in this case I have an issue...
The code:
the view:
<fieldset>
<legend>Modifica Dati Check-in Cliente</legend>
<?php
$passeggeri='placeholder="Passeggeri"';
$animali='placeholder="Animali"';
$note='placeholder="Note"';
echo form_open('site/esegui_modifica_record_check_in');
echo form_hidden('id',$id[0]->id);
echo form_hidden('rif_parcheggio',$id[0]->rif_parcheggio);
echo form_input('Passeggeri',set_value('passeggeri',$id[0]->passeggeri),$passeggeri);
echo form_input('Animali',set_value('animali',$id[0]->animali),$animali);
echo form_input('Note',set_value('note',$id[0]->note),$note);
?> <br/> <input type="datetime-local" name="data_in_inserita" value="<?php echo strftime('%Y-%m-%dT%H:%M', strtotime($id[0]->data_in));?>" /> <?php
echo form_submit('submit','Modifica');
echo form_close();
?>
</fieldset>
controller:
function esegui_modifica_record_check_in() {
$this->load->model('membership_model');
if($query = $this->membership_model->esegui_modifica_record_check_in())
{
$this->load->view('check_in_auto_succesful');
}
else
{
$this->load->view('admin');
}
}
model:
function esegui_modifica_record_check_in() {
$update_record_check2= array (
'passeggeri' => $this->input->post('passeggeri'),
'animali' => $this->input->post('animali'),
'note' => $this->input->post('note'),
'data_in' => $this->input->post('data_in_inserita')
);
$id=$this->input->post('id');
$this->db->where('id',$id);
$insert = $this->db->update('check2', $update_record_check2);
return $insert;
}
The query is executed but the values are updates as zero (0) character for the modified fields.
It's very strange! this is my first problem with the update function of codeigniter
I don't have a clear idea. Could you please help me?
thanks a lot
by
First thing to debug is to make sure that values are really being passed into your model method. Either debug first on the controller or inside you model:
Controller:
function esegui_modifica_record_check_in()
{
var_dump($this->input->post());
// rest of codes
}
OR
Model:
function esegui_modifica_record_check_in()
{
var_dump($this->input->post());
// rest of codes
}
Then, assuming you haven't fixed it yet. You have a case mismatch on the input name=""
echo form_input('Passeggeri',set_value('passeggeri',$id[0]->passeggeri),$passeggeri);
'passeggeri' => $this->input->post('passeggeri'),
// Passeggeri !== passeggeri
echo form_input('Animali',set_value('animali',$id[0]->animali),$animali);
'animali' => $this->input->post('animali'),
// Animali !== animali
echo form_input('Note',set_value('note',$id[0]->note),$note);
'note' => $this->input->post('note'),
// Animali !== animali
You should take that also into account. You need to follow the same case letters. Make them the same
Either:
echo form_input('Passeggeri',
$this->input->post('Passeggeri')
Or
echo form_input('passeggeri',
$this->input->post('passeggeri')
Sidenote:
As my suggestion above, I would just make it simple and use a normal form.
<form method="POST" action="<?php echo site_url('site/esegui_modifica_record_check_in'); ?>">
<input type="text" name="passeggeri" value="<?php echo $id[0]->passeggeri; ?>" placeholder="Passeggeri" />
<!-- and other text box inputs -->
</form>

Learning OOP in PHP. Is this the correct way to do this?

I've just started learning to do oop and I just wanted to put the most basic set of code together to make sure I'm understanding things correctly. I wanted to capture a form entry in the $_POST variable and pass it to an object to have it output something back to the browser. No SQL, no Security measures, just proof of understanding.
Here is the form:
<html>
<head>
<title>SignUp Form</title>
</head>
<body>
<?php
if(!empty($_POST['name'])) {
include_once "class.php";
} else {
?>
<form method="post" action="signup.php">
<label for="name">Enter name below:</label></br>
<input type="text" name="name" id="name"></br>
<input type="submit" value="Submit">
</form>
<?php
}
echo $name->processName($_POST['name']); ?>
</body>
</html>
And here is the class:
<?php
class Process {
public $entry;
function __construct($entry) {
$this->entry = $entry;
}
public function processName($entry) {
return "You entered " . $this->entry . ".";
}
}
$name = new Process($_POST['name']); ?>
This is working without error right now but it doesn't seem like I should have to enter the $_POST in the echo statement on the form page and in the object on the class page. Is this correct? Should I instead be collecting that in the $entry property. It's working, but I don't think the execution is correct. Thanks in advance!
Your right you don't need to enter the $_POST variable into that function, you could change it to this and it would work without entering the post:
public function processName() {
return "You entered " . $this->entry . ".";
}
Because right now processName function doesn't do anything with the class's public $entry variable, it just echoes out what you put in when you call the function.
What you likely want to do instead is:
Change public $entry; to protected $entry;
Then:
public function getEntry() {
return $this->entry;
}
Then in your html, after constructing the class, you can just put this to get the $entry variable:
echo $name->getEntry();
Coming from Symfony framework background. You could do something right this:
<?php
class Process
{
protected $post_var;
public function __construct($p)
{
$this->post_var = $p;
}
public function getData()
{
//checking if not post request
if(count($this->post_var) == 0) {
return false;
}
$result_arr = [];
//populating $result_arr with $_POST variables
foreach ($this->post_var as $key => $value) {
$result_arr[$key] = $value;
}
return $result_arr;
}
}
$process = new Process($_POST);
$data = $process->getdata();
if($data)
{
echo $data["name"];
}
?>
<form action="" method="post">
<input type="text" name="name"/>
<input type="submit" name="submit"/>
</form>

PHP Session Variable Array

Hi I'm trying to understand session variables, in particular using them with arrays. In the example code below, the user enters a letter and I want to add that submission to a session variable so that the next time the user submits a letter I don't lose the previous entry.
So if the user enters 'e' the array displays 'e', and if the user then picks 's' then the array will now display 'e' and 's'. This is my first experiment with PHP and sessions are proving a little difficult to wrap my head around. Can anyone help me understand how to go about getting the result I want, or where I have gone wrong in the code below? Many thanks in advance.
<?php
session_start();
function example()
{
$_SESSION['lettersGuessed'] = array();
$userLetter = $_GET['input'];
array_push($_SESSION['lettersGuessed'],$userLetter);
print_r($_SESSION['lettersGuessed']);
}
if (strlen($_GET['input'])==1) {
if (ctype_lower($_GET['input']))
{
echo "The user-submitted letter is lowercase.<br>";
example();
}
else
{
echo "Invalid submission<br>";
}
}
?>
<form action="" method="get">
<input name="input" value="Enter a letter!" />
<input type="submit" value="Submit" />
</form>
try it out without array_push in a more simple way
There is a simple change in example function.
Following is complete code
<?php
session_start();
function example() {
$userLetter = $_GET['input'];
$_SESSION['lettersGuessed'][] = $userLetter;
print_r($_SESSION['lettersGuessed']);
}
if (strlen($_GET['input']) == 1) {
if (ctype_lower($_GET['input'])) {
echo "The user-submitted letter is lowercase.<br>";
example();
} else {
echo "Invalid submission<br>";
}
}
?>
<form action="" method="get">
<input name="input" value="Enter a letter!" />
<input type="submit" value="Submit" />
</form>
?>
The problem is that your line in the beginning of example() resets the session variable to a blank array every time the function is called.
Update your example() function as follows:
function example()
{
$_SESSION['lettersGuessed'][] = $_GET['input'];
print_r($_SESSION['lettersGuessed']);
}
Thankfully, PHP is loosely-typed, so you don't have to manually define lettersGuessed as an array. Simply using [] afterwards will cause it to be handled as an array, and then using the = assignment operator will push $_GET['input'] into it.

PHP conditional statment inside a function

I am trying to create function that takes two arguments one for the user input and the other a message for error. I initially have an associative array with the two input fields and the corresponding error.
When the function is submitted without any entry I get two similar output; I thought I would get 'test1' and 'test2'. I am passing different arguments each time but I get the same result. The code is below
$valid = TRUE;
//$errors='';
$errors=array('desc_error'=>'please enter valid description',
'title_error'=>'provide valid title','no_error'=>'',);
function sanitizeText($input,$error){
//$input;
if($input!='')
{
$input= filter_var($input, FILTER_SANITIZE_STRING);
if($input==''){
global $errors;
$errors[$error];
$valid=FALSE;
return $errors[$error];
}
else{
$input;
echo 'test 1';
return $input;
}
}
else if($input=='')
{
if($input==$_POST['desc'])
{
echo 'the description field is required<br/>';
$valid=FALSE;
}
else{
//
}
}
}
if(isset($_POST['submit']))
{
$title=sanitizeText($_POST['title'],'title_error');
$desc=sanitizeText($_POST['desc'],'desc_error');
}
?>
<form method="post" action="">
<p>Book Title:<input type="text" name="title" maxlength="100" value=""/></p>
<p>Desc:<input type="text" name="desc" maxlength="100" value=""/></p>
<p><input type="submit" name="submit" value="Submit"/></p>
</form>
I think you are trying to validate form using php you can also user javascript to validate but to do it using php please refer following links.
http://myphpform.com/required-optional-fields.php
http://coredogs.com/lesson/form-and-php-validation-one-page
http://www.phpf1.com/tutorial/php-form.html?page=3
and
http://www.montanaprogrammer.com/php-web-programming/php-form-validation/
Your code does not make sense logic wise. Firstly, you check if $input is an empty string, or is not, and then within that first check.. you again make the same exact check. Since ifs are evaluated in order, and input is not ever going to be an empty string, the first if will always execute.
Then, your first 'else'; it will only execute if the $input variable is an empty string.. I can sort of see what you're attempting to do, but it won't work as it is right now. In order for it to work, it would have to look something like the below:
function sanitizeText($input,$error) {
global $errors;
global $valid;
$input_val = filter_var($_POST[$input], FILTER_SANITIZE_STRING);
if ($input_val != '') {
$valid = TRUE;
return $input;
}
else if ($input_val == '') {
$valid = FALSE;
echo $errors[$error].'<br />';
}
}
if(isset($_POST['submit']))
{
$title=sanitizeText('title','title_error');
$desc=sanitizeText('desc','desc_error');
}
If the input value is not an empty string, it will return the input value. If it is, it will not return anything and will instead echo the appropriate error.

Categories