How To Use Getters And Setters In PHP With User Input - php

I have created a registration form and now I want to insert data by using Getters and Setters. I have created intAll.php file which has HTML structure and PHP function, then I have created Encap.php file which has Database Connection, My SQL Queries and Getters/Setters. Now I want to pass my Input Data to Encap.php file and I want to catch them in Encap.php file and insert into My SQL DB, but my codes don't work.
So, How to Fix this?
intAll.php File
<?php
include 'Encap.php';
$InsertData = new Databases;
$success_message = '';
if(isset($_POST["submit"]))
{
$InsertData->setName($_POST['name']);
$InsertData->setUsername($_POST['username']);
$InsertData->setPassword($_POST['password']);
//$name=$_POST['name'];
//$username=$_POST['username'];
//$password=$_POST['password'];
if($InsertData->insertsingle())
{
$success_message = 'Post Inserted';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Insert data into Table using OOPS in PHP</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
<br /><br />
<div class="container" style="width:700px;">
<form method="post">
<label>Name</label>
<input type="text" name="name" class="form-control" />
<br />
<label>Username</label>
<input type="text" name="username" class="form-control" />
<br />
<label>Password</label>
<input type="text" name="password" class="form-control" />
<br />
<input type="submit" name="submit" class="btn btn-info" value="Submit" />
<span class="text-success">
<?php
if(isset($success_message))
{
echo $success_message;
}
?>
</span>
</form>
</div>
</body>
</html>
Encap.php File
<?php
class Databases{
public $con;
private $id;
private $name;
private $username;
private $password;
function setId($id) {
$this->id = $id;
}
function getId() {
return $this->id;
}
function setName($name) {
$this->name = $name;
}
function getName() {
return $this->name;
}
function setUsername($username) {
$this->username = $username;
}
function getUsername() {
return $this->username;
}
function setPassword($password) {
$this->password = $password;
}
function getPassword() {
return $this->password;
}
public function __construct()
{
$this->con = mysqli_connect("localhost", "root", "", "portal");
if(!$this->con)
{
echo 'Database Connection Error ' . mysqli_connect_error($this->con);
}
}
public function insertsingle()
{
$string = "INSERT INTO academic (name,username,pw) VALUES ('getName()','getUserName()','getPassword()')";
$rsint=mysqli_query($this->con, $string);
return $rsint;
}
}
?>

You cannot call a function within in a string. You should interrupt your string to do that:
public function insertsingle()
{
$string = "INSERT INTO academic (name,username,pw) VALUES ('" . $this->getName() . "','" . $this->getUserName() . "','" . $this->getPassword() . "')";
$rsint=mysqli_query($this->con, $string);
return $rsint;
}
However, since you're not sanitizing your user input anywhere, this code is vulnerable to SQL injection attacks and you should be using a prepared statement instead (note: untested code, might need to be tweaked a little):
public function insertsingle()
{
$string = "INSERT INTO academic (name,username,pw) VALUES (?, ?, ?)";
$stmt = mysqli_prepare($this->con, $string);
$stmt->bind_param("sss", $this->getName(), $this->getUserName(), $this->getPassword());
$rsint = $stmt->execute();
return $rsint;
}

Related

Read from textbox into array php

file index.php
<html>
<head>
<title>Guset Book</title>
</head>
<body>
<h3>Guest book</h3>
<a href="/addNew.php">
<p><input type="button" value="Add in book" ></p>
</a>
<a href="/readAll.php">
<p><input type="button" value="Read all"></p>
</a>
</body>
file addNew.php
<html>
<head>
<title>Guset Book</title>
</head>
<body>
<h3>New</h3>
<form name='formAddNew' method='post' action="ControllerAdd.php">
<p>Author: <input type="text" name="nameAuthor"></p>
<p>Comment:</p>
<p><textarea rows="5" cols="40" name="commentAuthor" style="resize: none;"></textarea></p>
<p><input type="submit" name="submitAuthor" value="Submit"></p>
</form>
</body>
file Model.php
<?php
class GuestBook
{
private $author;
private $comment;
function __construct($author, $commment)
{
$this->author = $author;
$this->comment = $commment;
}
public function getAuthor()
{
return $this->author;
}
public function getComment()
{
return $this->comment;
}
}
$guestBookList = new ArrayObject();
$guestBookList[] = new GuestBook("Author", "Comment");
function addInList($author, $comment)
{
$guestBookList[] = new GuestBook($author, $comment);
}
?>
file ControllerAdd.php
<html>
<head>
<title>Add</title>
</head>
<body>
<?php
require_once "Model.php";
addInList($_POST["nameAuthor"], $_POST["commentAuthor"]);
?>
<h3>Succes</h3>
<input type="button" value="On main">
</body>
file readAll.php
<html>
<head>
<title></title>
</head>
<body>
<?php
require_once "Model.php";
foreach($guestBookList as $value)
{
echo("<br>-----------<br>");
echo($value->getAuthor());
echo("<br>");
echo($value->getComment());
}
?>
</body>
The problem is that complier don't throws a mistakes, but don't write the code into array from textboxes. It read in right way the info from textboxes, but don't write into array Plz help.
I suggest in your particular case you need to change behaviour of your Model, something like this:
it's only an example, and must not be used as is
I guess, this code don't crash OP source
<?php
class GuestBook {
private $source;
private $book;
function __construct($filename) {
$this->book = array();
$this->source = $filename;
$this->restore();
}
function getBook() {
return $this->book;
}
function restore() {
if (file_exists($this->source)) {
$records = file($this->source);
if (is_array($records)) {
while (count($records)) {
$line = trim(array_shift($records));
list($author, $comment) = explode(':splitter:',$line);
$this->book[] = new GuestBookRecord($author, $comment);
}
}
}
}
function save() {
$fd = fopen($this->source, 'w');
foreach ($this->book as $record) {
fwrite($fd, $record->getAuthor().':splitter:'.$record->getComment().PHP_EOL);
}
fclose($fd);
}
function addComment($author, $comment) {
$this->book[] = new GuestBookRecord($author, $comment);
$this->save();
}
}
class GuestBookRecord {
private $author;
private $comment;
function __construct($author, $commment) {
$this->author = $author;
$this->comment = $commment;
}
public function getAuthor() {
return $this->author;
}
public function getComment() {
return $this->comment;
}
}
$guestBook = new GuestBook('sample.txt');
// compatibility with OP source
$guestBookList = $guestBook->getBook();
// compatibility with OP source
function addInList($author, $comment) {
global $guestBook;
$guestBook->addComment($author, $comment);
}
But it's not so good. Here is minimum 2 problems, first - the code reads all of the records into memory, second - concurrent accessing. It's just an example.
Session are best way to pass variables in this case
if i understand properly then you want to pass text filds value from two page and use them in 3rd page in array.
Use this as reference
index.php
<?php
session_start();
if(isset($_POST['submit'])){
if(!empty($_POST['tex1'])){
$_SESSION['tex1'] = $_POST['tex1'];
header('location:form.php');
}
}
?>
<form method="POST">
<input type="text" name="tex1">
<input type="submit" name="submit" value="submit">
</form>
form.php
<?php
session_start();
if(isset($_POST['submit'])){
if(!empty($_POST['tex2'])){
$_SESSION['tex2'] = $_POST['tex2'];
header('location:final_page.php');
}
}
?>
<form method="POST">
<input type="text" name="tex2">
<input type="submit" name="submit" value="submit">
</form>
final_page.php
<?php
session_start();
print_r($_SESSION);
$_SESSION is global variable of php.
To read more about session. Please read http://php.net/manual/en/reserved.variables.session.php
file1.php
<form action="file2.php" method="POST">
<textarea rows="4" cols="50" name="data[]"> </textarea>
<input type="submit" value="Submit">
</form>
file2.php
<?php
session_start();
$formData = $_POST['data'];
//echo '<pre>'; print_r($formData); die;
$_SESSION['formData'] = $formData;
echo 'Open File 3 to check submitted data.'
?>
file3.php
<?php
session_start();
if(isset($_SESSION['formData']) && $_SESSION['formData'] != ''){
print_r($_SESSION['formData']);
} else {
echo 'Submit form first.';
}
session_destroy();
?>

Adding records to the database using class function

I'm trying to add records to the database using function like this:
require_once('../config/Database.php');
class Category {
private $conn;
private $id;
private $name;
private $description;
private $created;
public function __construct($db) {
$this->conn = $db;
}
public function addRecord($n, $desc) {
$this->conn->prepare("INSERT INTO categories VALUES('', '$n', '$desc', CURDATE())")->execute();
$this->name = $n;
$this->description = $desc;
}
and to call it with it:
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST'){
if ( isset( $_POST['addRecord'], $_POST['n'], $_POST['desc']) ) {
$cat = new Category($conn);
$n = filter_input ( INPUT_POST , 'n', FILTER_SANITIZE_STRING );
$desc = filter_input ( INPUT_POST , 'desc', FILTER_SANITIZE_STRING );
$cat->addRecord($n, $desc);
}
}
?>
<div style="border: 5px solid black; width: 40%">
<h3>addRecord($n, $desc):</h3>
<form action="" method="post">
<label>Category name :</label>
<input type="text" name="n" id="n" required="required" placeholder="Please Enter Name"/><br /><br />
<label>Category description :</label>
<input type="text" name="desc" id="desc" required="required" placeholder="Please Enter Description"/><br /><br />
<input type="submit" value="addRecord" name="addRecord"/><br />
</form>
</div>
Database connection is here:
<?php
class Database {
public function getConnection() {
$result = false;
try {
$result = new PDO('mysql:host=localhost;dbname=demo', 'root', '');
} catch(PDOException $e) { }
return $result;
}
}
$db = new Database();
$conn = $db->getConnection();
if (!$conn) {
die("Error connecting to the database");
}
?>
I'm not getting any error but it's not working, just nothing happends when I press the "addRecord" button

Object of class Years cannot be converted to string error in Object oriented php

i'm new to OO in php. i was working with this code and there was an error "object of the class years cannot be converted in string". Now i kind of know what the error is saying but i'm not able to figure the solution out. And yeah I've checked every other question regarding this. Somebody please help me. Here is the code:
<?php
if(isset($_POST['sub'])){
$name=$_POST['name'];
$age=$_POST['age'];
$hrs=$_POST['hrs'];
class Years
{
const divid=24;
public function __construct($nme,$ag,$hr)
{
$ans= ($ag * $hr)/self::divid;
return $ans;
}
public function calc()
{
return "ok";
}
}
echo $yrs= new Years($name,$age,$hrs);
}
?>
<html>
<head>
<title>Form</title>
</head>
<body>
<h1>My Unconcious Life</h1>
<form method="post">
Your Name:<br />
<input type="text" name="name" /><br />
Your Age:<br />
<input type="text" name="age" /><br />
Hours slept per night:<br />
<input type="text" name="hrs" /><br />
<input type="submit" name="sub" value="Calculate" />
</form>
</body>
</html>
There are several problems with your class. Let's see:
class Years
{
const divid=24;
public function __construct($nme,$ag,$hr)
{
$ans= ($ag * $hr)/self::divid;
return $ans;
}
public function calc()
{
return "ok";
}
}
echo $yrs= new Years($name,$age,$hrs);
Problem #1: constructors do not return anything.
In order to make your class return something, you should create an attribute and then return it with a getter method:
class Years
{
const divid=24;
private $ans;
public function __construct($nme,$ag,$hr)
{
$this->ans = ($ag * $hr)/self::divid;
}
public function getAns()
{
return $this->ans;
}
public function calc()
{
return "ok";
}
}
Problem #2: Your constructor has unused arguments.
Why are you passing a $nme (notice the typo) argument to the constructor if it is not needed?
class Years
{
const divid=24;
private $ans;
public function __construct($ag,$hr)
{
$this->ans = ($ag * $hr)/self::divid;
}
public function getAns()
{
return $this->ans;
}
public function calc()
{
return "ok";
}
}
Problem #3: in order to convert an object to a string, your class should implement the __toString() method:
class Years
{
const divid=24;
private $ans;
public function __construct($ag,$hr)
{
$this->ans = ($ag * $hr)/self::divid;
}
public function getAns()
{
return $this->ans;
}
public function __toString()
{
return $this->getAns();
}
public function calc()
{
return "ok";
}
}
Despite of that, I'd say that your fundamental issue is that you are creating objects when they are not needed.
If you want just to transform units of time, all you need is a function:
function getYears($ag, $hr) {
return $ag * $hr / 24;
}
This is what it should be. This is not a problem to be solved with object orientation, a simple function call will do it.
Always remember to KISS.
Slightly different than the other answer. a little easier.
class Years
{
const divid=24;
public $ans;
public function __construct($nme,$ag,$hr)
{
$this->ans = ($ag * $hr)/self::divid;
}
public function calc()
{
return "ok";
}
}
$yrs= new Years($name,$age,$hrs);
echo $yrs->ans;
The correct way to code this would be
<?php
class Years
{
private $divid;
// although this is
public function __construct($div)
{
$this->divid = $div;
}
public function calc($ag,$hr)
{
return ($ag * $hr) / $this->divid;
}
}
if( isset($_POST['sub'], $_POST['age'], $_POST['hrs'], $_POST['name']) ){
$name=$_POST['name'];
$age=$_POST['age'];
$hrs=$_POST['hrs'];
$yrs = new Years(24);
$result = $yrs->calc($age,$hrs)
echo "The result is $result";
} else {
?>
<!DOCTYPE html>
<html>
<head>
<title>Form</title>
</head>
<body>
<h1>My Unconcious Life</h1>
<form method="post">
Your Name:<br />
<input type="text" name="name" /><br />
Your Age:<br />
<input type="text" name="age" /><br />
Hours slept per night:<br />
<input type="text" name="hrs" /><br />
<input type="submit" name="sub" value="Calculate" />
</form>
</body>
</html>
<?php
}
?>
?>

PDO Simple User Class Wont Work

i'm trying to create a simple user class but i can't get the data in the database i tried a lot of different code now here is the user class
namespace MonetizeMedia;
class User {
private $uid;
private $fields;
public function __construct() {
$this->uid = null;
$this->fields = array('username' => '',
'password' => '');
}
public function __get($field) {
if($field == 'uid')
{
return $this->uid;
}
else
{
return $this->fields[$field];
}
}
public function __set($field, $value) {
if(array_key_exists($field, $this->fields))
{
$this->fields[$field] = $value;
}
}
public function createUser() {
try {
$db = new \MonetizeMedia\Database;
$bcrypt = new \MonetizeMedia\Bcrypt(15);
$sql = "INSERT INTO users(username, password) VALUES(:username, :password)";
$stmt = $db->prepare($sql);
$stmt->bindParam(":username", $username);
$stmt->bindParam(":password", $bcrypt->hash($password));
$stmt->execute();
return "Registration Successful";
} catch ( PDOException $e ) {
return $e->getMessage();
}
}
and here is the register page
<?php
ob_start();
session_start();
include 'classes/user.class.php';
if(isset($_POST['submitted'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$User->username = $username;
$User->password = $password;
if($User->createUser()) {
echo "DONE!";
}
else
{
echo "An error occured while creating your account. Please try later.";
return;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Register</title>
</head>
<body>
<form method="post" action="">
<ul>
<li>
<label for="usn">Username : </label>
<input type="text" name="username" />
</li>
<li>
<label for="passwd">Password : </label>
<input type="password" name="password" />
</li>
<li class="buttons">
<input type="submit" name="register" value="Register" />
</li>
</ul>
</form>
</body>
</html>
i'm trying to learn php and pdo so i'm not so good at the moment

PHP not displaying data from database

I am trying to display a list of comments from a MySql database in PHP.
The foreach loop works as it displays the necessary html for each comment in the database, but no actual content from the database is being pulled through.
Comment class
class Comment {
protected $_id;
protected $_user;
protected $_commentText;
protected $_dateTimePosted;
public function __construct()
{
$this->_dateTimePosted = new DateTime();
$this->_dateTimePosted->format(DATE_RFC3339);
}
public function get_id()
{
return $this->_id;
}
public function set_id($value)
{
$this->_id = $value;
}
public function get_user()
{
return $this->_user;
}
public function set_user($value)
{
$this->_user = $value;
}
public function get_commentText()
{
return $this->_commentText;
}
public function set_commentText($value)
{
$this->_commentText = $value;
}
public function get_dateTimePosted()
{
return $this->_dateTimePosted;
}
public function set_dateTimePosted($value)
{
$this->_dateTimePosted = $value;
}
}
CommentFunctions.php
include 'dbConnect.php';
class CommentFunctions {
protected $conn;
public function __construct()
{
$this->conn = dbConnect();
}
public function get_comments()
{
$sql = "SELECT * FROM comments";
$stmt = $this->conn->stmt_init();
$stmt->prepare($sql);
$stmt->execute();
$stmt->store_result();
$comments = array();
while ($row = $stmt->fetch())
{
$comment = new Comment();
$comment->set_id($row['id']);
$comment->set_user($row['user']);
$comment->set_commentText($row['comment_text']);
$comment->set_dateTimePosted($row['datetime_posted']);
$comments[] = $comment;
}
return $comments;
}
}
Index.php
<?php
include './includes/Comment.php';
include './includes/CommentFunctions.php';
$comments_func = new CommentFunctions();
$all_comments = $comments_func->get_comments();
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Comments</title>
<link rel="stylesheet" type="text/css" href="./css/Master.css" />
<link rel="stylesheet" type="text/css" href="./css/Site.css" />
</head>
<body>
<div id="Container">
<h2>Comments</h2>
<a class="reload-comments" href="/">Refresh</a>
<div id="Comments">
<?php if (!$all_comments) {
echo 'No comments yet.';
} ?>
<?php foreach ($all_comments as $c) { ?>
<div class="comment">
<input class="id" type="hidden" value="<?php echo $c->get_id(); ?>" />
<div class="author">Posted by <?php echo $c->get_user(); ?></div>
<div class="comment-text">
Posted <?php echo $c->get_dateTimePosted(); ?>
<p><?php echo $c->get_commentText(); ?></p>
</div>
</div>
<?php } ?>
</div>
<div id="AddComment">
<form name="add_comment_form" id="add_comment_form" action="index.php" method="post">
<label for="user">Your Name:</label>
<input name="user" id="user" type="text" /><br />
<label for="comment_text">Comment:</label>
<textarea name="comment_text" id="comment_text" rows="5" cols="10"></textarea><br />
<input name="submit" id="submit" type="submit" value="Submit" />
<input id="reset" type="reset" class="hidden" />
</form>
</div>
<div class="loader"></div>
<div class="response"></div>
</div>
</body>
Comments can be added, the data is stored fine in the database, and the loop runs the correct number of times, but the code such as echo $c->get_commentText(); is not displaying a value.
Appreciate any help.
Looks like you're using mysqli.
You're forgetting a key step: binding your result variables.
See http://www.php.net/manual/en/mysqli-stmt.bind-result.php and the examples there for more info on how to get actual values back.
try a
var_dump($all_comments)
after you fetch it, to prove that there is actually something in the array
next step would be to check that the sql worked. I am not sure what database layer you are using so i'm not sure what the check to do that would be.
i would assume that this method should have a return value you can check
$stmt->execute();

Categories