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
Related
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;
}
I am making a login for my website, but when i enter the name & pass in the form it gives a bool(false) back. Can't find out why it's happening. I've used the same code for another website with some adjustments and its just working fine there.
//classDatabase.php
class Database
{
public $pdo = null;
public function __construct()
{
$db_user = '******';
$db_pass = '*******';
$this->pdo = new PDO( 'mysql:host=localhost;dbname=showcase_nl', $db_user, $db_pass );
}
public function getDb()
{
return $this->pdo;
}
public function getLogin($name, $pass)
{
$sql = "SELECT id, name, pass FROM users WHERE name=:name AND pass=:pass";
$query = $this->getDb()->prepare($sql);
$query->execute(array(':name'=>$name, ':pass'=>$pass ));
$result = $query->fetch();
return $result;
}
}
?>
Login.php
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$name = isset($_POST[ 'name' ]) ? $_POST[ 'name' ] : '';
$pass = isset($_POST[ 'pass' ]) ? $_POST[ 'pass' ] : '';
if ($name != '' && $pass != '')
{
$result = $db->getLogin($name, $pass);
if (count($result) > 0)
{
$_SESSION['login'] = $result;
var_dump($_SESSION);
if ($_SESSION['login'])
{
header('Location: ?page=beheer.php');
}
else
{
echo 'Gegevens zijn onjuist';
}
}
else
{
echo 'Onbekende gebruiker';
}
}
else
{
echo 'Je hebt niet alle velden ingevuld';
}
}
else
{
echo '
<div class="col-md-8 col-md-offset-2">
<div class="panel-blog panel-default">
<div class="panel-body">
<form method="post">
<div class="form-group">
<label for="name">Naam:</label>
<input type="name" class="form-control" name="name" id="name" placeholder="Naam">
</div>
<div class="form-group">
<label for="pass">Wachtwoord:</label>
<input type="password" class="form-control" name="pass" id="pass" placeholder="Wachtwoord">
</div>
<button type="submit" class="btn btn-default">Log in</button>
</form>
</div>
</div>
</div>';
}
Also tried it with PDOStatement::bindParam, but still doesn't work.
public function getLogin($name, $pass)
{
$sql = "SELECT * FROM users WHERE name=:name AND pass=:pass";
$query = $this->getDb()->prepare($sql);
$query->bindParam(':name', $name);
$query->bindParam(':pass', $pass);
$query->execute();
$result = $query->fetch(PDO::FETCH_ASSOC);
return $result;
}
I have been practicing with PHP and mongodb. I am developing a simple web application but using OOP.
I created a class called user which has my methods to do with user like addUser, deleteUser etc. For add user, I would like for the form to carry out some simple validation tasks, but i am not sure how. Here is the class to add a new user:
function createUser($username, $name, $email, $password){
$user = array(
'username' => $username,
'name' => $name,
'email' => $email,
'password' => $password
);
if ($this->db->count(array('username' => $username)) == 0) {
$this->db->insert($user);
return true;
} else {
echo 'username taken';
}
}
And the html:
<?php
session_start();
include_once 'user.php';
include './templates/header.php';
if (isset($_POST['register']) && ($_POST['register']) == ($_POST["register"])) {
$user = new User();
$return = $user->createUser(
$_POST['username'],
$_POST['name'],
$_POST['email'],
$_POST['password'],
$_POST['password2']);
}
if ($return == true) {
echo 'you have successfully registered';
} else {
echo '</br>' . 'sorry, try again';
}
?>
<div class="container">
<div class="jumbotron">
<form method="post" action="">
<label>Username: </label><br>
<input name="username" type="text" ><br><br>
<label>Name: </label><br>
<input name="name" type="text"><br><br>
<label>Email: </label><br>
<input name="email" type="email" ><br><br>
<label>Password: </label><br>
<input name="password" type="password" ><br><br><br>
<label>Repeat Password: </label><br>
<input name="password2" type="password" ><br><br><br>
<input name="register" class="btn btn-primary btn-lg" type="submit" value="Register"><br>
</form>
</div>
</div>
Please feel free to correct me on other mistakes you may notice. I know there is bound to be some.
i wrote a simple example for you its simple and useful
class validation {
public $currentValue;
public $values = array();
public $errors = array();
public function __construct() {
parent::__construct();
// echo "burasi model sayfasi ";
}
public function post($key){
if(isset($_POST[$key])){
$this->values[$key] = $_POST[$key];
$this->currentValue = $key;
return $this;
}else{ die("hi boo boo ! your form values are empty");}
}
public function isEmpty(){
if(empty($this->values[$this->currentValue])){
$message='the form is emppty';
$this->errors[$this->currentValue]['empty'] =''.$message.'';
}
return $this;
}
public function submit(){
if(empty($this->errors)){
return true;
}else{
return false;
}
}
}
this is an example so how can you use it ?
firstly you need yo call the class
$form = new validation ();
$form->post("all you need just write post name here ")
->isEmpty();
if($form->submit()){
//everyting is ok !
you cann add delet or update data
}else{
$data["error"] = $form->errors; // and we sett the errorr mesages to the array now you can show the user the errormesages ! well done
}
}
I have problem in php i'm using WAMP(php 5.3.13 and mysql 5.5.24). And my problem is when I am testing the register form:
include "config.php";
if(isset($_GET['confirm_registration'])){
User::ConfirmRegistration($_GET['confirm_registration']);
}
if(isset($_POST['confirm_registration'])){
$username= $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
if(!Validator::Email($email)){
echo "Invalid email address";
} else {
User::BeginRegistration($username,$email,$password);
}
}
?>
<div id="contentWrapper">
<div id="form">
<form id="signup" method="POST" action="">
<div class="signup_form"><strong>Sign up</strong></div>
<div class="signup_form">
<label>Username</label>
<input type="text" id="username" name="username" size="30">
</div>
<div class="signup_form">
<label>E-Mail</label>
<input type='text' id='email' name='email' size="30">
</div>
<div class="signup_form">
<label>Password</label>
<input type='password' id='password' name='password' size="30">
</div>
<div class="signup_form">
<label></label>
<input type='submit' name="confirm_registration" value='Submit'>
</div>
</form>
</div>
</html>
This is the error :Call to a member function query() on a non-object in C:\wamp\www\zavrsni_rad\classes\DataBase.class.php on line 11
and here is the DataBase class:
class DataBase
{
public static $connection;
public static function Connect(){
self::$connection = new mysqli("localhost","root","","zavrsni_rad");
self::$connection->set_charset("utf8");
}
public static function Execute($query){
self::$connection->query($query);
}
public static function GetString($query){
$r = self::$connection->query($query);
$res_arr = $r->fetch_row();
return $res_arr[0];
}
public static function GetRow($query){
$r = self::$connection->query($query);
return $r->fetch_row();
}
public static function GetTable($query){
$r = self::$connection->query($query);
$res = array();
while($rw = $r->fetch_row()){
$res[] = $rw;
}
return $res;
}
public static function Disconnect(){
self::$connection->close();
}
}
Clearly self::$connection is not yet instantiated when you call Execute() - you should run Connect() before.
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