Class variables NULL? - php

I am working on a web back-end that will pull information into a form, and then when updated, will update the database with the new information. However, when I try to pull information previously stored in a class private variable, it throws me an error stating that the information is NULL. What am I doing wrong here?
<?php
class modify_racer
{
private $mysqli, $racer_id, $firstname,
$lastname, $banner, $bio;
public function error($code)
{
switch($code)
{
case 1:
echo '<p id="error"><b>Error:</b> Please fill out all fields!</p>';
modify_racer::send_form($this->firstname, $this->lastname, $this->banner, $this->bio);
break;
case 2:
echo '<p id="error"><b>Error:</b> Racer already exists!</p>';
break;
case 3:
echo '<p id="error"><b>Error:</b> Could not connect to MySQLi: ' . mysqli_error();
break;
}
}
public function send_form($modify = 1)
{
?>
<div id="form">
<h3>Edit Racer:</h3>
<form method="post" action="">
<label for="firstname">First Name: </label>
<input type="text" id="firstname" name="firstname"
placeholder="Racer's First Name"
value="<?php echo $this->firstname;?>" />
<br />
<label for="lastname">Last Name: </label>
<input type="text" id="lastname" name="lastname"
placeholder="Racer's Last Name"
value="<?php echo $this->lastname;?>" />
<br />
<label for="banner">Banner Location: </label>
<input type="text" id="banner" name="banner"
placeholder="Racer's Banner Image Location:"
value="<?php echo $this->banner;?>" />
<br />
<label for="bio">Racer's Bio Info: </label>
<textarea rows="5" cols="50" id="bio" name="bio"
placeholder="Racer Statistics / Biography"
value=""><?php echo $this->bio;?></textarea>
<input type="submit" id="submit" name="modify" value="submit" />
</form>
</div>
<?php
}
public function get_racer($racerID)
{
$this->racer_id = $racerID;
$this->mysqli = new mysqli(MYSQLI_HOST,MYSQLI_USER,MYSQLI_PASS,MYSQLI_DATABASE)
or die(error(3));
$racer_info = "SELECT * FROM ArtecRacers WHERE RacerID=?";
$load_racer = $this->mysqli->prepare($racer_info);
$load_racer->bind_param('s', $racerID);
$load_racer->execute();
$load_racer->bind_result($this->racerID, $this->firstname, $this->lastname, $this->banner, $this->bio);
$load_racer->fetch();
modify_racer::send_form();
}
public function list_racers()
{
?>
<div id="form">
<h3>Select Racer:</h3>
<form method="post" action="">
<?php
$this->mysqli = new mysqli(MYSQLI_HOST,MYSQLI_USER,MYSQLI_PASS,MYSQLI_DATABASE)
or die(error(3));
$racer_list = "SELECT * FROM ArtecRacers";
$get_racers = $this->mysqli->query($racer_list);
while($list = $get_racers->fetch_array(MYSQLI_NUM))
{
echo '<input id="part" type="radio" name="editRacer" value="' . $list[0] . '"/>';
echo '<label for="part">' . $list[1] . ' ' . $list[2] . '</label><br />';
}
?>
<input type="submit" name="selectRacer" id="submit" value="Select Racer" />
</form>
</div>
<?php
}
function test2()
{
echo $this->firstname;
echo $this->lastname;
echo $this->racer_id;
}
}
$start = new modify_racer();
if(!isset($_POST['selectRacer']))
$start->list_racers();
if(isset($_POST['selectRacer']))
$start->get_racer($_POST['editRacer']);
$start->test2();
?>
Everything in the code works except at $start->test2(); all of the information pulled from the function test2() is blank, and I am not sure why... Any insights?
EDIT:
I changed the code to reflect the following on the bottom, and test2() still outputs the variables as NULL:
if(!isset($_POST['editRacer']))
$start->list_racers();
else
$start->get_racers($_POST['editRacer']);
$start->test2();

If you leave your code alone, you're going to have to pass both selectRacer and editRacer parameters into the page. My guess is that you might only want to pass the one, though. In which case, you'll want to change
if(isset($_POST['selectRacer']))
$start->get_racer($_POST['editRacer']);
into
if(isset($_POST['editRacer']))
$start->get_racer($_POST['editRacer']);
Also, if you want to pass these values in through the URL bar, you need to check $_GET, not $_POST.
And finally, everywhere that you are making method calls by executing modify_racer::my_method_here(), you should change that to $this->my_method_here(). The former is a static method call, meaning it's not actually associated with your object, meaning it can't touch those variables. For it to be able to access and change the variables, you'll need to call it through $this.

Related

How to fix the Add function?

I'm doing a php based project.And I want to add data to the database.I did it using php, PDO. And I created the code with OOC. But There's a if else part in main HTML page. In that part the else part is running. But I didn't even click the insert button. When the page is loading the else part is running. I watched a video and this code is working perfectly fine. Here's the code..
Insert.php - Getters, Setters, SQL query and etc.
class Stock
{
protected $ItemNo;
protected $ItemName;
protected $brand;
protected $qty;
protected $Description;
protected $ItemDate;
protected $SupplierName;
protected $SupplierMail;
private $tableName = 'StockDetails';
private $dbconn;
function setItemNo($ItemNo) { $this->ItemNo = $ItemNo; }
function getItemNo() { return $this->ItemNo; }
function setItemName($ItemName) { $this->ItemName = $ItemName; }
function getItemName() { return $this->ItemName; }
function setBrand($brand) { $this->brand = $brand; }
function getBrand() { return $this->brand; }
function setQty($qty) { $this->qty = $qty; }
function getQty() { return $this->qty; }
function setDescription($Description) { $this->Description = $Description; }
function getDescription() { return $this->Description; }
function setItemDate($ItemDate) { $this->ItemDate = $ItemDate; }
function getItemDate() { return $this->ItemDate; }
function setSupplierName($SupplierName) { $this->SupplierName = $SupplierName; }
function getSupplierName() { return $this->SupplierName; }
function setSupplierMail($SupplierMail) { $this->SupplierMail = $SupplierMail; }
function getSupplierMail() { return $this->SupplierMail; }
public function __construct()
{
require_once ('Database.php');
$db = new Database();
$this->dbconn = $db->connect();
}
public function insert(){
$sql = "INSERT INTO $this->tableName VALUES (:ItemNo, :ItemName, :brand, :qty, :Description, :ItemDate, :SupplierName, :SupplierMail)";
$stmt = $this->dbconn->prepare($sql);
$stmt->bindParam(':ItemNo', $this->ItemNo);
$stmt->bindParam(':ItemName', $this->ItemName);
$stmt->bindParam(':brand', $this->brand);
$stmt->bindParam(':qty', $this->qty);
$stmt->bindParam(':Description', $this->Description);
$stmt->bindParam(':ItemDate', $this->ItemDate);
$stmt->bindParam(':SupplierName', $this->SupplierName);
$stmt->bindParam(':SupplierMail', $this->SupplierMail);
if($stmt->execute()){
return true;
}else{
return false;
}}}
?>
Action.php - Form action on AddItem.php
require_once ('Insert.php');
class action{
function __construct(){
switch ($_POST['submit']) {
case 'insert':
$obInsert = new Stock;
$obInsert->setItemNo($_POST['ItemNo']);
$obInsert->setItemName($_POST['ItemName']);
$obInsert->setBrand($_POST['brand']);
$obInsert->setQty($_POST['qty']);
$obInsert->setDescription($_POST['Description']);
$obInsert->setItemDate(date('Y-m-d H:i:s'));
$obInsert->setSupplierName($_POST['SupplierName']);
$obInsert->setSupplierMail($_POST['SupplierMail']);
if($obInsert->insert()) {
header('location: AddItem.php?insert=1');
} else{
header('location: AddItem.php?insert=0');
}
break;
default:
header('location: AddItem.php');
break;
}
}
}
if(isset($_POST['submit'])){
$object = new action;
}
AddItem.php
To get the brand and ItemName from the Database. The brand changes according to ItemName.
<?php
require_once ('GetBrand.php');
$ItemName = LoadItemName();
?>
$(document).ready(function(){
$("#ItemName").change(function(){
var aid = $("#ItemName").val();
$.ajax({
url: 'GetBrand.php',
method: 'post',
data: 'aid=' + aid
}).done(function(brand){
console.log(brand);
brand = JSON.parse(brand);
$('#brand').empty();
brand.forEach(function(bnamee){
$('#brand').append('<option>' + bnamee.brand + '</option>')
})
})
})
})
The Form
<form name="form0" method="post" action="Action.php">
<div class="form-group">
<label for="text">Item No</label>
<input type="text" name="ItemNo" id="ItemNo" placeholder="Item No" required>
</div>
<form name="form1" action="AddItem.php" method="post">
<div class="form-group">
<label for="text">Item Name</label>
<table>
<tr>
<td><select name="ItemName" id="ItemName" required>
<option value="" disabled="" selected>Select Name</option>
<?php foreach($ItemName as $iname)
echo "<option id='".$iname['ItemNo']."' value='".$iname['ItemNo']."'>".$iname['ItemName']."</option>";
?>
</select></td>
<td><label for="text">Add Item Name : </label></td>
<td><input type="text" name="name" id="name"> </td>
<td><button>Add</button></td>
</tr>
</table>
</div>
<div class="form-group">
<label for="text">Brand Name</label>
<table>
<tr>
<td><select name="brand" id="brand" required>
<option value="">Select Brand</option>
</select></td>
<td<label for="text">Add Brand : </label></td>
<td><input type="text" name="Bname" id="Bname" class="form-control" > </td>
<td><button>Add</button></td>
</tr>
</table>
</div>
</form>
<div class="form-group">
<label for="text">Quantity</label>
<input type="text" name="qty" id="qty" placeholder="Quantity" required>
</div>
<div class="form-group">
<label for="text">Item Description</label>
<input type="text" name="Description" id="Description" placeholder="Description" required>
</div>
<div class="form-group">
<label for="text">Date</label>
<input type="date" name="ItemDate" id="ItemDate" required>
</div>
<div class="form-group">
<label for="text">Supplier Name</label>
<input type="text" name="SupplierName" id="SupplierName" placeholder="Supplier Name" required>
</div>
<div class="form-group">
<label for="text">Supplier Mail</label>
<input type="text" name="SupplierMail" id="SupplierMail" placeholder="Supplier Mail" required>
</div><br/>
<div class="form-group">
<button id="submit" name="submit" value="insert">Insert</button>
<?php
if(isset($_GET['insert']) && ($_GET['insert'] == 1)){
echo "Inserted Successfully ";
}else // This else part is running when the page is loading
echo "Ooops..! Something went wrong.";
}
?>
</div>
</form>
<?php
if(isset($_GET['insert']) && ($_GET['insert'] == 1)){
echo "Inserted Successfully ";
}else // This else part is running when the page is loading
echo "Ooops..! Something went wrong.";
}
?>
you are surprised that this runs?
What you have said here is, if there is a $_GET parameter called insert and it's equal to 1 then echo "inserted..." in any other situation that may exist echo 'oops...'
Php cannot naturally discern whether this is the initial page load, a redirect, a button has been pressed or what you are thinking. If you only want this to run if a button has been been clicked you'd need to add in some extra checks around the whole thing, for example
if(isset($_POST['submit'])) {
///add in your checks to
}
or possibly more suitable for you would be
if(isset($_GET['insert']) {
if($_GET['insert'] == 1)){
echo "Inserted Successfully ";
} else {// you're missing a brace here
echo "Ooops..! Something went wrong.";
}
}
the point is, your code will always run regardless at the moment because it is an if/else i.e. do this or do that - but what you want to say is if a - do b or c, else do nothing. I think you need to try and understand exactly how conditionals work

PHP writing variables and string to text file

I'm trying to write to file like this:
<?php
date_default_timezone_set('Europe/Budapest');
if(isset($_POST['user'])) {
global $user;
$user = $_POST['user'];
} else {
die("Nincs user beállítva!");
}
if(isset($_POST['pass'])) {
global $pass;
$pass = $_POST['pass'];
} else {
die("Nincs pass beállítva!");
}
if(!isset($_POST['msg'])) {
die("Nincs üzenet!");
} else {
global $msg;
$msg = $_POST['msg'];
}
if(!file_exists("logfile.txt")) {
die("Nem létezik a logfile.txt!");
}
$cont = file_get_contents("logfile.txt");
file_put_contents("logfile.txt","{$user}: {$msg}\n{$cont}"); //<-- Tried this one so many ways
?>
And it gives me this in the txt file:
<? global $user; echo $user; ?>: test
No matter what i change in the file_put_contents, it always give something similar to this.
Thanks for the help in advance.
EDIT: I made the edit that #Barmar suggested, but it is still doing the same thing:
<form name="send" action="chat_send.php" method="post">
<input type="text" name="msg" autocomplete="off" value="">
<?php
global $user;
echo '<input type="hidden" name="user" value="' . $user . '">';
...
</form>
There's nothing wrong with how you're writing to the file. The problem is most likely with how you're setting $_POST['user']. It looks to me like the script that created the form did something like:
echo '<input type="hidden" name="user" value="<?php global $user; echo $user; ?>">';
You can't use <?php ... ?> in the middle of a string to execute PHP code;
That's used when you're outputing normal HTML after ?>, to get back into PHP execution mode temporarily. So your form just contains the literal string ?php global $user; echo $user; ?> in the hidden input value.
In a string, you use concatenation, so it should be:
global $user;
echo '<input type="hidden" name="user" value="' . $user . '">';
Or you can return to HTML mode first:
?>
<form name="send" action="chat_send.php" method="post">
<input type="text" name="msg" autocomplete="off" value="">
<input type="hidden" name="user" value="<?php global $user; echo $user; ?>">
...
</form>
<?php

Passing PHP variable data onto another page after validation

While I found something similar to this question on here it didn't answer my question outright.
I have set up this php script to validate the form data, which works, after its validated I want it to then pass the info onto another script page to let the user then verify their input data and then mail the data. Its at this state that I'm having trouble. I've spent the last few days trying to find a solution to this and unfortunately coming up short.
<?php
$name_error = '';
$email_error = '';
$comments_error = '';
$error = false;
if (!empty($_POST['submitted']))
{ //if submitted, the validate.
$name = trim($_POST['name']);
if (empty($name))
{
$name_error='Name is required';
$error = true;
}
$email = trim($_POST['email']);
/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email))
{
$email_error='E-mail address not valid';
$error = true;
}
$comments = trim($_POST['comments']);
if (empty($comments))
{
$comments_error='Comments are required';
$error = true;
}
if ($error == false)
{
$name_send = $name;
$email_send = $email;
$comments_send = $comments;
/* Redirect visitor to the thank you page */
header('Location: /mail.php');
exit();
}
}
The form this is attached to:
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="post">
<label>Your Name</label><br />
<input type="text" name="name" style="width:95%" class="text" value='<?php echo htmlentities($name) ?>' />
<br/>
<span class='error'><?php echo $name_error ?></span>
<br />
<label>Email</label><br />
<input type="email" name="email" style="width:95%" class="text" value='<?php echo htmlentities($email) ?>' />
<br/>
<span class='error'><?php echo $email_error ?></span>
<br />
<label for="comments" style="font-size:16px;">Feedback Comments</label><br />
<textarea name="comments" style="width:95%;" rows="8" value='<?php echo htmlentities($comments) ?>'></textarea>
<br />
<span class='error'><?php echo $comments_error ?></span>
<br />
<input type="checkbox" name="allowCommentPublish" checked="checked" />
<label for="allowCommentPublish" style="font-size:10px;">Allow these comments to be used on our website</label>
<fieldset class="optional">
<h2>[ OPTIONAL ]</h2>
<label>Company Name</label><br />
<input type="text" name="companyName" style="width:95%" class="text" />
<br/>
<label>Phone</label><br />
<input type="text" name="phone" style="width:95%" class="text" /><br/>
<div style="margin:5px 0px;">
<input type="checkbox" name="incmarketing" />
<label style="font-size:10px;"> Yes, you can email me specials and promotions.</label>
<br/>
</div>
</fieldset>
<fieldset>
<input type="submit" name="submitted" value="Send" />
</fieldset>
I will point out im focusing on the main data inputs: Name E-mail and comments.
I need the info from this form to be sent onward but i dont know exactly how to do this and any help will be appreciated greatly.
For passing the values to next page you will have to use either of the three methods.
1. Set cookies with the data.
2. Use global variable session.
3.Pass the data in the url.
For cookies u can set cookies with the values like
setcookie('name',$name);
in ur next page read those cookie data
For sessions:
$_SESSION['name']= $name;
for reading data from cookies & session:
$name = $_COOKIE['name'];
$name = $_SESSION['name'];
For using sessions you must add the line
session_start();
at the start of both the pages that send or receive(use) the data
and for urls
header('Location: /mail.php?name=$name&email=$email&comment=$comments');
Read more on using session
If you need to pass values from one script to another you can use $_SESSION variables. To start a session use: (at the top of the php script)
session_start();
$_SESSION['somename'] = $somevariable;
To access or get that same variable you can use this:
session_start();
$some_other_variable = $_SESSION['somename'];
or you can use hidden input fields.
You can use hidden fields and javascript to submit the form. However as this is the same php page as the original form you will need an if statement
echo '<form name="newForm" action="newpage.php" method="POST">';
echo '<input type="hidden" name="name2" value"' . $name . '">;
echo '<input type="hidden" name="email2" value"' . $email . '">;
echo '<input type="hidden" name="comments2" value"' . $comments . '"></form>;
echo '<script> if (document.getElementById("name2").value != ""){window.onload = function(){ window.document.newForm.submit(); }} </script>';

PHP - editing data in db issue

I'm going to keep it short and simple. I'm writing a really basic code in php which adds content to mysql db and I've run into an issue with editing. This is my form:
if($idExists)
{
Print '
<form action="editIt.php" method="POST">
<div name="id"> '. $id . '</div>
Enter new detail: <input type="text" name="details"/><br/>
public post? <input type="checkbox" name="public[]" value="yes"/><br/>
<input type="submit" value="Update List"/>
</form>
';
}
And this is my editIt.php
//session start and stuff
if(filter_input(INPUT_SERVER, 'REQUEST_METHOD', FILTER_SANITIZE_STRING) == "POST")
{
echo "<script type='text/javascript'>alert('EDITIT!');</script>";
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("WebSiteDB") or die ("Cannot connect to database");
$id = $_POST['id'];
$details = mysql_real_escape_string($_POST['details']);
$time = strftime("%X");
$date = strftime("%B %d, %Y");
$isPublic = 'no';
foreach($_POST['public'] as $eachCheck)
{
if($eachCheck != NULL)
$isPublic = "yes";
}
mysql_query("UPDATE list SET details='$details', dateEdited='$date', timeEdited= '$time', public='$isPublic' WHERE id='$id'");
header("location: home.php");
}
I can't really find an issue with this code (which is not really strange, I'm a newbie at web stuff) and yet it just goes to home.php and does not change data in DB. Please, help me jump this ledge, so I can go on with my life.
I think, the problem is in this line $id = $_POST['id'];. On form submit, the input field value will only be submitted, not the DIV value.
So, please change from :
if($idExists)
{
Print '
<form action="editIt.php" method="POST">
<div name="id"> '. $id . '</div>
Enter new detail: <input type="text" name="details"/><br/>
public post? <input type="checkbox" name="public[]" value="yes"/><br/>
<input type="submit" value="Update List"/>
</form>
';
}
To :
if($idExists)
{
Print '
<form action="editIt.php" method="POST">
<input type="hidden" name="id" value="' . $id . '">
Enter new detail: <input type="text" name="details"/><br/>
public post? <input type="checkbox" name="public[]" value="yes"/><br/>
<input type="submit" value="Update List"/>
</form>
';
}

Get variable from query string

I was trying to get variable in Query String from URL. But somehow, its just got one variable instead of getting all variables from querystring. I really don't know what goes wrong with my code. Here is the code I want to print out error from the invalidate form:
<?php
displayForm();
function displayForm(){
?>
<form action="./prod_add_action.php" method="post" name="addproductForm">
<fieldset>
<legend>Online Ordering System Setup</legend>
<label for="product_name">Product Name: </label><input type="text" name="product_name" value="" /><?php echo $_GET["name_error"]; ?>
<label for="product_date">Product Date: </label><input type="text" name="product_date" value="" /><?php echo $_GET["date_error"]; ?>
<label for="product_price">Product Price: </label><input type="text" name="product_price" value="" /><?php echo $_GET["price_error"]; ?>
<input name="add_button" type="submit" value="Add" />
<input name="reset_button" type="reset" value="Clear" />
</fieldset>
</form>
<?php
}
?>
And here is the code I created the querystring:
$query_string = "name_error=" .urlencode($name_error) ."&date_error=" .urlencode($date_error) ."&price_error=" .urlencode($price_error);
header("Location: ./prod_add.php?$query_string");
exit();
In the first code, the page only print the first $_GET['name_error'], while it should be include $_GET['date_error'] and $_GET['price_error. ']
This is the address:
http://example.com/prod_add.php?name_error=Product+name+must+be+characters+only&date_error=Product+date+must+be+input+as+this+formate+DD-MM-YYYY&price_error=Product+price+must+be+float+number+only
You should use & instead of &'s ?
$query_string = "name_error=" .urlencode($name_error) ."&date_error=" .urlencode($date_error) ."&price_error=" .urlencode($price_error);
header("Location: ./prod_add.php?$query_string");
exit();
Change & to & as:
$query_string = "name_error=" . urlencode($name_error) . "&date_error=" . urlencode($date_error) . "&price_error=" . urlencode($price_error);
header("Location: ./prod_add.php?$query_string");
exit();

Categories