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();
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;
}
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();
?>
I am building an OOP/PDO login system for my website but, I don't know how I can correctly display error messages within my login class when the user login attempt fails. Also, I would like to know if my OOP approach is right. This is my first project working with OOP and PDO. If you have any suggestions for my code I would like to hear them.
login.class.php
<?php
class Login {
private $dbConnection;
private $studentNumber;
private $studentClass;
private $errorMessage = false;
public function __construct($dbConnection) {
$this->dbConnection = $dbConnection->dbConnection;
}
public function showErrorMessage() {
return $this->errorMessage;
}
public function studentLogin($studentNumber, $studentClass) {
$this->studentNumber = $studentNumber;
$this->studentClass = $studentClass;
$selectStudent = $this->dbConnection->prepare("SELECT * FROM tbl_students WHERE studentNumber = :studentNumber AND studentClass = :studentClass LIMIT 1");
$selectStudent->bindParam(':studentNumber', $this->studentNumber);
$selectStudent->bindParam(':studentClass', $this->studentClass);
$selectStudent->execute();
$selectStudentCheck = $selectStudent->fetch(PDO::FETCH_ASSOC);
if(!empty($selectStudentCheck)) {
return true;
}
else {
$this->errorMessage = "Studentnumber or class is not correct";
}
}
}
?>
dbconnection.class.php
<?php
class DatabaseConnection {
private $DatabaseHost = "localhost";
private $DatabaseName = "plansysteem_keuzetrainingen";
private $userName = "root";
private $passWord = "root";
public $dbConnection;
public function __construct() {
$this->databaseConnect();
}
public function databaseConnect() {
try{
$this->dbConnection = new PDO("mysql:host=$this->DatabaseHost;dbname=$this->DatabaseName", $this->userName, $this->passWord);
$this->dbConnection->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e){
print("Sorry er kan geen verbinding worden gemaakt met de database");
file_put_contents("../errors/database.connection.errors.txt", $e->getMessage().PHP_EOL,FILE_APPEND);
die();
}
}
}
?>
login form
<?php
session_start();
include ("../classes/dbconnection.class.php");
include ("../classes/login.class.php");
if(isset($_POST["submitLogin"])) {
$studentNumber = $_POST["studentNumber"];
$studentClass = $_POST["studentClass"];
$dbConnection = new DatabaseConnection();
$login = new Login($dbConnection);
if($login->studentLogin($studentNumber, $studentClass)) {
echo "Succes";
}
else {
echo "Student not found!";
}
}
?>
<!DOCTYPE html>
<html class="no-js" lang="nl">
<head>
<meta charset="UTF-8" />
<meta name="description" content="" />
<meta name="keywords" content="" />
<meta name="author" content="Communication Centre" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Login Plansysteem Keuzetrainingen</title>
<link rel="icon" type="image/png" href="../img/favicon.png" sizes="16x16 32x32" />
<link rel="stylesheet" type="text/css" href="../css/foundation.css" />
<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Advent+Pro" />
<link rel="stylesheet" type="text/css" href="../css/main.css" />
<script type="text/javascript" src="../js/vendor/modernizr.js"></script>
</head>
<body>
<div class="row">
<div class="small-12 medium-8 medium-offset-2 large-6 large-offset-3 columns">
<h1 class="mainTitle">inloggen</h1>
</div>
</div>
<form method="post">
<div class="row">
<div class="small-12 medium-8 medium-offset-2 large-6 large-offset-3 columns">
<small class="error"></small>
</div>
</div>
<div class="row">
<div class="small-12 medium-8 medium-offset-2 large-6 large-offset-3 columns">
<div class="row collapse">
<div class="small-2 medium-1 large-1 columns">
<span class="prefix">
<img src="../img/cursor_icon.png" alt="Cursor Icon" />
</span>
</div>
<div class="small-10 medium-11 large-11 columns">
<input type="text" name="studentNumber" placeholder="Studentnummer" class="placeholderBlack" />
</div>
</div>
</div>
</div>
<div class="row">
<div class="small-12 medium-8 medium-offset-2 large-6 large-offset-3 columns">
<div class="row collapse">
<div class="small-2 medium-1 large-1 columns">
<span class="prefix">
<img src="../img/person_icon.png" alt="Person Icon" />
</span>
</div>
<div class="small-10 medium-11 large-11 columns">
<select name="studentClass">
<option value="">Selecteer Klas</option>
<option value="1DVTM-REG-01.P1">1DVTM-REG-01.P1</option>
<option value="1DVTM-REG-02.P1">1DVTM-REG-02.P1</option>
<option value="1DVTM-REG-03.P1">1DVTM-REG-03.P1</option>
</select>
</div>
</div>
</div>
</div>
<div class="row">
<div class="small-12 medium-8 medium-offset-2 large-6 large-offset-3 columns">
<input type="submit" name="submitLogin" value="Login" class="button expand buttonBlack" />
</div>
</div>
</form>
<script type="text/javascript" src="../js/vendor/jquery.js"></script>
<script type="text/javascript" src="../js/foundation.min.js"></script>
<script type="text/javascript">
$(document).foundation();
</script>
</body>
</html>
This looks quite a bit like the login system that I have built for my projects, as far as returning error messages, you can assign the error to a variable and use it with return to pass it along. Another thing that may be easier to do is to use an ajax call for the login instead of having the php directly on the page. This would also allow for you to dynamically assign error/success messages.
But as far as returning the error messages you could change the catch to something like this
$status = [];
if(!empty($selectStudentCheck)) {
status['status'] = true;
return status;
}
else {
$status['status'] = false;
$status['msg'] = "Studentnumber or class is not correct";
return $status;
}
this would also remove the need for the showErrorMessage() function. You would then to need to just check ['status'] and then display ['msg'] if you want to display the error. The above would also work well with an ajax call.
One other thing that I noticed that you may want to do is to move your database info into a separate file to be included so that you can set permission on it so that the info is more secure. Something I have done with mine is the following
db_info.inc
<?php
# Defining Database Values to avoid hardcoding in each file.
define ('DB_USER', 'user');
define ('DB_PASS', 'supersecret password');
define ('DB_HOST_WRITE', 'host1'); # Master DB
define ('DB_HOST_READ', 'host2'); # Slave DB
define ('DB_ONE', 'database1');
define ('DB_TWO', 'database2');
Then just include the the file and assign them to the variables you need and inset them where they need to be. such as below.
class User {
# Set class wide variables
private $db;
public $dbuser = DB_USER;
public $dbhost = DB_HOST_WRITE;
public $dbname = DB_ONE;
public $dbpass = DB_PASS;
Also you can construct the actual database connection inside the construct. of the actual login class so that you don't have to pass it into the login functions. This can also allow you to more easily assign database rights to users for special functions.
public function __construct() {
try {
$this->db = new PDO("mysql:host=" . $this->dbhost . ";dbname=" . $this->dbname, $this->dbuser, $this->dbpass);
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Exception $ex) {
file_put_contents($this->pdolog, $ex->getMessage(), FILE_APPEND);
}
}
Hope this helps
==========
For the ajax call the blow is snippets from my own implementatation
the login form
<form id="formLogin">
<input class="form-control center-block text-center" name="username" id="username" placeholder="Username" type="text" required>
<input class="form-control center-block text-center" name="password" id="password" placeholder="Password" type="password" required>
<input type="button" value="Login" id="login" class="btn btn-block btn-primary center-block" onclick="userlogin(event, '#formLogin')">
</form>
The onlick option is the magic part. It calls the following jquery script.
function userlogin(event, loginform) {
event.preventDefault();
$('#login').fadeOut();
$.ajax({
type: 'POST',
url: '/inc/login.php',
data: $(loginform).serializeArray(),
dataType: 'json',
success: function(data) {
if (data.status == 'error') {
alert(data.statusmsg);
$('#login').fadeIn();
}
if (data.status == 'success') {
window.location = '/account/';
}
},
error: LogonError
});
}
function LogonError() {
alert('Error: The system could not log you in.' +
'\n\nIf you believe this is an error please email the' +
'\nAdministrator at admin#blacklistlogistics.com');
}
This takes the values from the form with jquery doing all the extra magix so I dont have to and passes it to the php page login.php
login.php
$user = #$_POST['username'];
$pass = #$_POST['password'];
$response = array();
if($user == null) {
$errors = 1;
$response['statusmsg'] .= "Please enter your username.\n";
}
if($pass == null) {
$errors = 1;
$response['statusmsg'] .= "Please enter your password.\n";
}
if($errors === 1) {
$response['status'] = 'error';
echo json_encode($response);
return;
} else {
$login = new User;
$loginstatus = $login->login($user, $pass);
if($loginstatus === 0) {
$response['status'] = 'error';
$response['statusmsg'] = "The system was unable to log you in. Please try again later.\nIf this error presists please inform the site administrator.";
echo json_encode($response);
return;
}
if($loginstatus === 2) {
$response['status'] = 'error';
$response['statusmsg'] = "There was an error. Please try again later.\nIf this error presists please inform the site administrator.";
echo json_encode($response);
return;
}
if($loginstatus === 1) {
$response['status'] = 'success';
echo json_encode($response);
return;
}
}
This grabs the info that jquery passed us out of the post and then passes it to the login function and then checks the return values and passes the info needed back to jquery to display errors etc.
the login function
public function login($username, $password) {
# Set login time
$logintime = date('Y-m-d H:i:s');
$ip = filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP);
# setting db connection inside try for exception handling
try {
$conn = $this->db;
$stmt = $conn->prepare('SELECT * FROM Members WHERE UserName = :username');
$stmt->execute(array(':username' => $username));
$results = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt = NULL;
} catch (PDOException $ex) {
$conn = NULL;
file_put_contents($this->pdolog, $ex->getMessage(), FILE_APPEND);
return 2;
}
if ($results === FALSE || $results['AccountActive'] === 0) {
$conn = NULL;
return 0;
} else {
if (password_verify($password, $results['UserPass'])) {
try {
$stmt = $conn->prepare('UPDATE Members SET LastDate = :lastdate, LastIP = :lastip, FailCount = :failcount WHERE MemberID = :memberid');
$stmt->execute(array(':lastdate' => $logintime, ':lastip' => $ip, ':failcount' => 0, ':memberid' => $results['MemberID']));
} catch (PDOException $ex) {
$conn = NULL;
file_put_contents($this->pdolog, $ex->getMessage(), FILE_APPEND);
return 2;
}
$conn = NULL;
$_SESSION['login'] = 1;
$_SESSION['MemberID'] = $results['MemberID'];
$_SESSION['UserName'] = $results['UserName'];
return 1;
} else {
$conn = NULL;
return 0;
}
}
}
after the function has run and data has been passed back to the jquery call, jquery then process the data in the success or error portions.
Hope this helps as well, also sorry for the long copy/paste code. also I kept the majority of the extra peices of my code intact just incase you would like to pull ideas from it.
I am stuck with writing View for my code igniter search form which need to use get..
I currently have this
Controller
<?php
class Search extends CI_Controller {
function __construct(){
parent::__construct();
}
public function index(){
$this->load->view('Search');
}
public function doSearch()
{
$this->load->model("Messages_model");
if ($this->input->get('search') !== FALSE) {
$data ['results'] = $this->Messages_model->searchMessages($this->input->get('search'));
} else {
$data['results'] = array();
}
$this->load->view("Search", $data);
}
Model
class Messages_model extends CI_Model{
function searchMessages($string){
$this->load->database();
$query = $this->db->query("SELECT * FROM messages WHERE text LIKE '%$string%'");
return $query->result();
}
View
<!DOCTYPE html>
<html>
<style>
</style>
<head>
<title></title>
</head>
<body>
<form action="<?php echo site_url('Search/doSearch');?>" method = "get">
<input type="text" name = "keyword"/>
<input type="submit" value = "Search" />
</form>
</div>
</body>
</html>
Can anyone help me out in getting search string displayed
Firstly, go to application/config/config.php and find $config['allow_get_array'] and make sure it's set to TRUE.
Then in your controller you would have something like this:
public function search()
{
$this->load->model("Messages_model");
if ($this->input->get('search') !== FALSE) {
$data ['results'] = $this->Messages_model->searchMessages($this->input->get('search'));
} else {
$data['results'] = array();
}
$this->load->view("Search", $data);
}
Please note that there isn't any validation happening on the string here so you will need to add your own.
Hope this helps!
EDIT
View file:
<!DOCTYPE html>
<html>
<style>
</style>
<head>
<title></title>
</head>
<body>
<form action="<?php echo site_url('search/doSearch'); ?>" method = "get">
<input type="text" name="keyword" value="<?php echo isset($search_value) ? $search_value : ''?>"/>
<input type="submit" value="Search" />
</form>
<?php
if ($search_passed && !empty($results)) {
foreach ($results as $result) {
//Code for displaying results
}
} elseif ($search_passed && empty($results)) {
echo 'No results found!';
}
?>
</div>
</body>
</html>
Controller Method:
public function doSearch()
{
$this->load->model("Messages_model");
if ($this->input->get('keyword') !== FALSE) {
$data ['results'] = $this->Messages_model->searchMessages($this->input->get('keyword'));
//Uncomment the line below to test
// echo '<pre>'; print_r($data['results']);die('</pre>');
$data['search_passed'] = TRUE;
$data['search_value'] = $this->input->get('keyword');
} else {
$data['search_passed'] = FALSE;
$data['results'] = array();
}
$this->load->view("Search", $data);
}
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