I try to activate to the registered user's account.
In order to that first create a model
function uyeOnay($registrationCode) {
$query = "SELECT id FROM pasaj_register where activationCode = '" . $registrationCode . "'";
$result = $this->db->query($query, $registrationCode);
if ($result->num_rows() == 1) {
$query = "UPDATE pasaj_register SET activated = 1 WHERE activationCode = ?";
$this->query->query($query, $registrationCode);
return true;
} else {
return false;
}
}
then i called it in my controller
public function kayitEmailOnay() {
$registrationCode = $this->uri->segment(3);
if ($registrationCode == '') {
echo "URLde onay kodu yok";
}
$registrationConfirmed = $this->kayitmodel->uyeOnay($registrationCode);
if ($registrationConfirmed)
echo "successful";
else
echo "unsuccessful";
}
i also called my model in constructor
public function __construct() {
parent::__construct();
$this->load->model('kayitmodel');
}
However, i get this error ,
i think that (in uyeOnay function) :
$this->query->query($query, $registrationCode);
need to be :
$this->db->query($query, $registrationCode);
$this->query->query($query, $registrationCode);
Should be
$this->db->query($query, $registrationCode);
Related
my problem is i whenever i input fname and mname i got an error from the database. i just want to search both of fname and mname in search field.
my search controller function
public function search()
{
$li = $this->session->userdata('logged_in');
$id = $this->session->userdata('idnumber');
if($li == TRUE)
{
$this->load->model('users_model');
$this->load->helper('smiley');
$this->load->library('table');
$image_array = get_clickable_smileys('http://localhost/efg/images/smileys', 'status');
$col_array = $this->table->make_columns($image_array, 8);
$image_array2 = get_clickable_smileys('http://localhost/efg/images/smileys', 'status');
$col_array2 = $this->table->make_columns($image_array2, 8);
$this->data['smiley_table1'] = $this->table->generate($col_array);
$this->data['smiley_tables'] = $this->table->generate($col_array2);
if($this->input->post())
{
$search = $this->input->post('search');
$memb = $this->users_model->search($search);
$usersearch = $this->users_model->search($search);
$grpsearch = $this->users_model->searchgrp($search);
redirect ('home/profile/'.$memb);
}
}
}
My users_model model
public function search($search)
{
$this->db->select('*');
$this->db->from('users');
$this->db->like('username',$search);
$this->db->or_like('fname',$search);
$this->db->or_like('lname',$search);
$this->db->or_like('mname',$search);
$query = $this->db->get();
foreach ($query->result_array() as $row)
{
$memb = $row['idnumber'];
}
$error = 'There is no record for the one you searched. Please go Back.';
$query1 = $this->db->query("SELECT * FROM users WHERE idnumber ='$memb'");
$hehe = $query1->result_array();
if($hehe==NULL)
{
echo $error; exit;
}
else
{
return $memb;
}
}
Always check the varibles using in condition are declared before the condition.
If it doesnt pass the condition what would be the output
public function search($search)
{
$this->db->select('*');
$this->db->from('users');
$this->db->like('username',$search);
$this->db->or_like('fname',$search);
$this->db->or_like('lname',$search);
$this->db->or_like('mname',$search);
$query = $this->db->get();
$memb = null;
foreach ($query->result_array() as $row)
{
$memb = $row['idnumber'];
}
$error = 'There is no record for the one you searched. Please go Back.';
$query1 = $this->db->query("SELECT * FROM users WHERE idnumber =$memb");
$hehe = $query1->result_array();
if($hehe==NULL)
{
return $error;
}
else
{
return $memb;
}
}
Make sure the variables that youll be using in queries are set. Trap before executing queries.
Also, use Query Builder (Active Record) when you can.
public function search($search)
{
$this->db->select('*');
$this->db->from('users');
$this->db->like('username',$search);
$this->db->or_like('fname',$search);
$this->db->or_like('lname',$search);
$this->db->or_like('mname',$search);
$query = $this->db->get();
$memb = '';
if ($query->result_array() > 0) {
foreach ($query->result_array() as $row) {
$memb = $row['idnumber'];
}
if ($memb) {
$this->db->select("*");
$this->db->where("idnumber", $memb);
$query1 = $this->db->get("users");
//$query1 = $this->db->query("SELECT * FROM users WHERE idnumber ='$memb'");
$hehe = $query1->result_array();
return ($hehe) ? $memb : false;
}
return false;
}
$error = 'There is no record for the one you searched. Please go Back.';
return $error;
}
Following code:
function personInfo($person)
{
$zipCode="12345";
if($zipCode!=54321)
{
$zipCode="12345";
$postal="World";
if($zipCode AND $postal < 1)
{
return "Wrong";
}
//Test stops here and do not continue???
}
$person->firstname="Mike";
$person->lastname="Wayne";
$person->address="Universe";
$person->zipCode="12345";
$person->mobile="123456789784512";
$person->password="GogoGO";
$person->socialSecurityNumber="1234567891234567";
return "OK";
}
I am not sure why it stops there since I want to test the code when it fails and when it's OK. I'm still learning so I would be much appreciated for all help!
Rest of the code (database & test) that connects to "function personInfo($person)":
function personInfo($person)
{
$this->db->autocommit(false);
$sql = "Select * from Postal Where ZipCode = '$person->zipCode'";
$result = $this->db->query($sql);
if($this->db->affected_rows!=1)
{
$sql = "Insert Into Postal (ZipCode, Postal) Values ('$person->zipCode','$person->postal')";
$result = $this->db->query($sql);
if($this->db->affected_rows < 1)
{
$this->db->rollback();
return "Wrong";
}
}
$sql .= "Update Person Set Firstname = '$person->firstname', Lastname = '$person->lastname',";
$sql .= " Address = '$person->address', ZipCode = '$person->zipCode',";
$sql .= " Mobile = '$person->mobile', Password ='$person->password'";
$sql .= " Where SocialSecurityNumber = '$person->socialSecurityNumber'";
$result = $this->db->query($sql);
$this->db->commit();
return "OK";
}
class personInfoTest extends PHPUnit_Framework_TestCase {
public function testPersonInfoWrong()
{
//arrange
$zipCode="1234";
$person=$zipCode;
$record=new Record(new DBStub());
// act
$result= $record->personInfo($person);
//assert
$this->assertEquals("Wrong",$result);
}
public function testPersonInfoOK()
{
//arrange
$zipCode="1234";
$person=$zipCode;
$record=new Record(new DBStub());
// act
$result= $record->personInfo($person);
// assert
$this->assertEquals("OK",$result);
$this->assertEquals("1234567891234567",$result->socialSecurityNumber);
$this->assertEquals("Mike",$result->firstname);
$this->assertEquals("Wayne",$result->lastname);
$this->assertEquals("Universe",$result->address);
$this->assertEquals("1234567812345",$result->telefonnr);
$this->assertEquals("GogoGO",$result->password);
$this->assertEquals("12345",$result->zipCode);
$this->assertEquals("World",$result->poststed);
}
}
So I've been stuck on this for quite a while, surprisingly the update and delete functions work just fine, however I cannot make the CREATE function work properly. Please have a look at it and tell me what I'm doing wrong
<-------------- Entire model for admin panel-------------->>>>>>>> Connection to DB is working fine---------->>>>>>>>>>>
<?php
include_once "Model.php";
class ModelPages extends Model {
public function get($key) {
$sql = "SELECT * from pages where page_key = '$key'";
$row = '';
$page = Null;
foreach ($this->pdo->query($sql) as $row) {
$page = $row;
}
// echo "<pre>";
// var_dump($page);
// exit;
return $page;
}
public function getAll() {
$statement = $this->pdo->prepare("SELECT * from pages Where Id > 3");
$result = $statement->execute();
$pages = array();
if($result) {
$pages = $statement->fetchAll(PDO::FETCH_ASSOC);
}
return $pages;
}
public function updatePage($params=array()) {
if (!is_array($params)) {
return 'Params should be an array';
}
if (isset($params['table'])) {
$tableName = $params['table'];
} else {
$tableName = 'pages';
}
$pageId = isset($params['page_key']) ? $params['page_key'] : null;
$pageTitle = isset($params['page_title']) ? $params['page_title'] : null;
$pageBody = isset($params['page_body']) ? $params['page_body'] : null;
if ($pageId == null) {
return 'No page id provided';
}
$sql = "UPDATE " . $tableName . " SET
title = :title,
body = :body
WHERE page_key = :page_key";
$statement = $this->pdo->prepare($sql);
$statement->bindParam(':title', $pageTitle, PDO::PARAM_STR);
$statement->bindParam(':body', $pageBody, PDO::PARAM_STR);
$statement->bindParam(':page_key', $pageId, PDO::PARAM_INT);
$result = $statement->execute();
return $result;
}
public function deletePage($pageId) {
// build sql
$sql = "DELETE FROM pages WHERE id = " . intval($pageId);
$statement = $this->pdo->prepare($sql);
$result = $statement->execute();
return $result;
}
public function createPage($params=array()){
if (!is_array($params)) {
return 'Params should be an array';
}
if (isset($params['table'])) {
$tableName = $params['table'];
} else {
$tableName = 'pages';
}
$page_key = isset($params['page_key']) ? $params['page_key'] : 'page_key';
$pageTitle = isset($params['page_title']) ? $params['page_title'] : 'page_title';
$pageBody = isset($params['page_body']) ? $params['page_body'] : 'page_body';
$sql = "INSERT INTO " . $tablename ." SET page_key=:page_key, title=:title, body=:body ";
// prepare query for execution
$statement = $this->pdo->prepare($sql);
// bind the parameters
$statement->bindParam(':page_key', $_POST['page_key']);
$statement->bindParam(':title', $_POST['title']);
$statement->bindParam(':body', $_POST['body']);
// specify when this record was inserted to the database
// Execute the query
$result = $statement->execute();
return $result;
}
}
<?php
include 'controllers/controller.php';
include 'models/Model.php';
include 'models/ModelPages.php';
<------------------------ADMIN CONTROller----------------------->>>>>>>>>>>>
class Admin extends Controller {
function __construct() {
// create an instance of ModelPages
$ModelPages = new ModelPages();
if(isset($_POST['page_key'])) {
// TODO: update DB
$tableData['page_body'] = $_POST['body'];
$tableData['table'] = 'pages';
$tableData['page_title'] = $_POST['title'];
$tableData['page_key'] = $_POST['page_key'];
$response = $ModelPages->updatePage($tableData);
if ($response == TRUE) {
header("http://188.166.96.184/workspace/marem/AAAAA/index.php?page=admin&success=true");
}
}
if(isset($_GET['page_key'])) {
// by default we assume that the key_page exists in db
$error = false;
$page = $ModelPages->get($_REQUEST['page_key']);
// if page key does not exist set error to true
if($page === null) {
$error = true;
}
// prepare data for the template
$data = $page;
$data["error"] = $error;
// display
echo $this->render2(array(), 'header.php');
echo $this->render2(array(), 'navbar_admin.php');
echo $this->render2($data, 'admin_update_page.php');
echo $this->render2(array(), 'footer.php');
} else {
// case: delete_page
if(isset($_GET['delete_page'])) {
$response = $ModelPages->deletePage($_GET['delete_page']);
if($response == TRUE) {
header("http://188.166.96.184/workspace/marem/AAAAA/index.php?page=admin&deleted=true");
}
}
}
//Get table name and make connection
if(isset($_POST['submit'])) {
$page_key = $_POST['page_key'];
$page_title = $_POST['title'];
$page_body = $_POST['body'];
$response = $ModelPages->createPage();
if($response=TRUE){
header("http://188.166.96.184/workspace/marem/AAAAA/index.php?page=admin&created=true");
}
}
}
// load all pages from DB
$pages = $ModelPages -> getAll();
// display
echo $this->render2(array(), 'header_admin.php');
echo $this->render2(array(), 'navbar_admin.php');
echo $this->render2(array("pages"=> $pages), 'admin_view.php');
echo $this->render2(array(), 'footer.php');
}
}
?>
Since you have if(isset($_POST['page_key']) on the top:
class Admin extends Controller {
function __construct() {
// create an instance of ModelPages
$ModelPages = new ModelPages();
if(isset($_POST['page_key'])) {
...
if ($response == TRUE) {
header("http://188.166.96.184/workspace/marem/AAAAA/index.php?
}
and it is used to call $response = $ModelPages->updatePage($tableData);
your code never reach the part with good values at the bottom:
if(!isset($_POST['page_key'])) {
...
$response = $ModelPages->createPage($tableData);
So my simple but not the best suggestion is use extra parameter when POST like action. so you can check:
if(isset($_POST['action']) && $_POST['action']=='update') {
...
} elseif (isset($_POST['action']) && $_POST['action']=='create') {
...
} etc...
hope this will help you for now :-)
$sql = "INSERT INTO " . $tablename ." SET page_key=:page_key, title=:title, body=:body ";
$tablename is not in scope when the statement above is executed. And you've got no error handling in the code.
I am working on an Item Inventory Web App. I want users should be able to add and assign item to a user. Each user is entitled to one item at a time. If, say, user a already has an item assigned and you want to add more item, the system should lodge an error that will tell you
to withdraw the item be issuing a new one but the errors are not getting lodged in the error[] array even though it shows that the array is not empty. It only echo out the serial number a = 1 and a++ but the text is not there.
class.inc.php
class Summary {
public $result;
public $conn;
public $SQ;
public $q;
public $updateDB;
public $checkDB;
public $returned_result;
public $a;
public $data;
public $col;
public function __construct(){
$this->conn = new PDO('mysql:host=localhost; dbname=dB', 'root', '');
$this->conn->setAttribute(PDO:: ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
public function updateDB($coloumn, $data, $id){
$SQ = "UPDATE mytable SET $coloumn = ? WHERE staffID = ?";
$q = $this->conn->prepare($SQ) or die("ERROR: " . implode(":", $this->conn->errorInfo()));
$q->bindParam(1, $data);
$q->bindParam(2, $id);
if ($q->execute()){
$success = 'Record updated successfully';
};
return $success;
}
public function checkDB($col, $data){
$status = 'Active';
$SQ = "SELECT surname FROM mytable WHERE $col = ? AND status = ?";
$q = $this->conn->prepare($SQ) or die("ERROR: " . implode(":", $this->conn->errorInfo()));
$q->bindParam(1, $data);
$q->bindParam(2, $status);
$q->execute();
if($result = $q->fetch(PDO::FETCH_BOTH)){
$a = $result[0];
if ($a == ''){
$this->returned_result = 'N';
}
else {
$this->returned_result = "This item (". $data . ") is in use by ". $a . ". Please widthraw the item";
}
}
return $this->returned_result;
}
}
index.php:
include('class.inc.php');
$summary = new Summary;
$error = array();
if(isset($_POST['saveRecord']) ) {
$system_name = strtoupper ( $_POST['system_name'] );
$result =$summary->checkDB('systemName', $system_name); //check if the item is in use
if ( $result == 'N' ){
$summary->updateDB('systemName', $system_name, $id);
$update = $summary->updateDB;
}
else $error[] = $result;
$system_serial_number = strtoupper ( $_POST['system_serial_number'] );
$result =$summary->checkDB('CPUSerial', $system_serial_number); //check if the item is in use
if ( $result == 'N' ){
$summary->updateDB('CPUSerial', $system_serial_number, $id);
$update = $summary->updateDB;
}
else $error[] = $result;
}
if(isset($_POST['saveRecord']) && !empty( $error ) ) {
echo "<div class = 'text-error'>";
$a = 1;
foreach ($error as $err){
echo '<p>' . $a . '. ' .$err . '</p>';
$a++;
}
echo "</div>";
}
Any help will be greatly appreciated. And what am I doing wrong with regards to OOP way of programming?
I have created joomla pagination for my own component and its working fine for joomla 2.5 and i have use same for joomla 3.0 the data is displaying and also the pagination is also displaying correctly but the issue is when i click on any pagination no. for going next or prev page its not working form remains on same page.
Here is code i have used for creating pagination.
model.php
defined('_JEXEC') or die('Restricted access');
jimport('joomla.application.component.modellist');
class eventsModelEvents extends JModelLegacy {
var $_total = null;
var $_pagination = null;
function __construct()
{
parent::__construct();
$mainframe = JFactory::getApplication();
// Get pagination request variables
$limit = $mainframe->getUserStateFromRequest('global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int');
$limitstart = JRequest::getVar('limitstart', 0, '', 'int');
// In case limit has been changed, adjust it
$limitstart = ($limit != 0 ? (floor($limitstart / $limit) * $limit) : 0);
$this->setState('limit', $limit);
$this->setState('limitstart', $limitstart);
}
function getPagination()
{
// Load the content if it doesn't already exist
if (empty($this->_pagination)) {
jimport('joomla.html.pagination');
$this->_pagination = new JPagination($this->getTotal(), $this->getState('limitstart'), $this->getState('limit') );
}
return $this->_pagination;
}
function getTotal()
{
// Load the content if it doesn't already exist
if (empty($this->_total)) {
$query = $this->_buildQuery();
$this->_total = $this->_getListCount($query);
}
return $this->_total;
}
function getData()
{
// if data hasn't already been obtained, load it
if (empty($this->_data)) {
$query = $this->_buildQuery();
$this->_data = $this->_getList($query, $this->getState('limitstart'), $this->getState('limit'));
}
return $this->_data;
}
function _buildQuery()
{
// Create a new query object.
$db = JFactory::getDBO();
$query = $db->getQuery(true);
// Select some fields
$query->select('*');
// From the hello table
$query->from('#__events');
$query->order('date DESC');
return $query;
}
function getEvents(){
$db = $this->getDBO();
$db->setQuery('SELECT * from #__events');
$events = $db->loadObjectList();
if ($events === null)
JError::raiseError(500, 'Error reading db');
return $events;
}
function getEvent($id){
$query = ' SELECT * FROM #__events '.
' WHERE id = '.$id;
$db = $this->getDBO();
$db->setQuery($query);
$event = $db->loadObject();
if ($event === null)
JError::raiseError(500, 'Event with ID: '.$id.' not found.');
else
return $event;
}
function saveEvent($event){
$db = $this->getDBO();
$uploaded_path = JPATH_COMPONENT. "/images/";
if($_FILES["event_image"]["tmp_name"]){
if ($_FILES["event_image"]["error"] > 0){
return $_FILES["event_image"]["error"] . "<br>";
} else {
move_uploaded_file($_FILES["event_image"]["tmp_name"],$uploaded_path . $_FILES["event_image"]["name"]);
$event['event_image'] = $_FILES["event_image"]["name"];
}
} else {
$event['event_image'] = $event['event_stored_image'];
}
$event['event_date'] = date('Y-m-d H:i:s', strtotime($event['event_date']));
foreach($event as $key => $value){
$event[$key] = mysql_real_escape_string($value);
}
if(($event['event_name'] != NULL ) && ($event['event_image'] != NULL) && ($event['event_date'] != NULL) && ($event['event_description'] != NULL)){
if(isset($event['event_id'])){
$query = "UPDATE #__events SET name = '".$event['event_name']."',status = '".$event['event_status']."',image = '".$event['event_image']."',date = '".$event['event_date']."',description = '".$event['event_description']."',reservation = '".$event['event_reservation']."' WHERE id =" . $event['event_id'];
} else {
$query = "INSERT INTO #__events (name,status,image,date,description,reservation) VALUES ('".$event['event_name']."','".$event['event_status']."','".$event['event_image']."','".$event['event_date']."','".$event['event_description']."', '".$event['event_reservation']."')";
}
$db->setQuery($query);
if (!$db->query()){
$errorMessage = $this->getDBO()->getErrorMsg();
JError::raiseError(500, 'Error inserting event: '.$errorMessage);
}
} else {
return "Please Fill All fields.";
}
}
function deleteEvents($arrayIDs)
{
$query = "DELETE FROM #__events WHERE id IN (".implode(',', $arrayIDs).")";
$db = $this->getDBO();
$db->setQuery($query);
if (!$db->query()){
$errorMessage = $this->getDBO()->getErrorMsg();
JError::raiseError(500, 'Error deleting events: '.$errorMessage);
}
}
function publishEvents($arrayIDs)
{
$query = "UPDATE #__events SET status = '1' WHERE id IN (".implode(',', $arrayIDs).")";
$db = $this->getDBO();
$db->setQuery($query);
if (!$db->query()){
$errorMessage = $this->getDBO()->getErrorMsg();
JError::raiseError(500, 'Error publishing events: '.$errorMessage);
}
}
function unpublishEvents($arrayIDs)
{
$query = "UPDATE #__events SET status = '0' WHERE id IN (".implode(',', $arrayIDs).")";
$db = $this->getDBO();
$db->setQuery($query);
if (!$db->query()){
$errorMessage = $this->getDBO()->getErrorMsg();
JError::raiseError(500, 'Error publishing events: '.$errorMessage);
}
}
}
view.html.php
jimport( 'joomla.application.component.view');
class eventsViewEvents extends JViewLegacy {
protected $categories;
protected $items;
protected $pagination;
protected $state;
function display($tpl = null)
{
$this->categories = $this->get('CategoryOrders');
$this->state = $this->get('State');
$this->addToolBar();
// Get data from the model
$events = $this->get('Data');
$pagination =$this->get('Pagination');
// push data into the template
$this->events = $events;
$this->assignRef('pagination', $pagination);
parent::display($tpl);
}
function add($tpl = null){
$this->addToolBar();
parent::display($tpl);
}
protected function addToolbar()
{
require_once JPATH_COMPONENT . '/helpers/events.php';
$canDo = EventsHelper::getActions($this->state->get('filter.category_id'));
$user = JFactory::getUser();
JToolBarHelper::title('Event Manager', 'generic.png');
JToolBarHelper::addNew('add');
if (count($user->getAuthorisedCategories('com_events', 'core.create')) > 0)
{
//JToolBarHelper::addNew('add');
}
if (($canDo->get('core.edit')))
{
JToolBarHelper::editList('edit');
}
if ($canDo->get('core.edit.state'))
{
if ($this->state->get('filter.state') != 2)
{
JToolBarHelper::divider();
JToolBarHelper::publish('publish', 'JTOOLBAR_PUBLISH', true);
JToolBarHelper::unpublish('unpublish', 'JTOOLBAR_UNPUBLISH', true);
}
}
if ($this->state->get('filter.state') == -2 && $canDo->get('core.delete'))
{
JToolBarHelper::deleteList('', 'remove', 'JTOOLBAR_EMPTY_TRASH');
JToolBarHelper::divider();
}
elseif ($canDo->get('core.edit.state'))
{
JToolBarHelper::trash('remove');
JToolBarHelper::divider();
}
}
function displayEdit($eventId,$tpl = NULL)
{
JToolBarHelper::title('Event'.': [<small>Edit</small>]');
JToolBarHelper::save();
JToolBarHelper::cancel();
$model = $this->getModel();
$event = $model->getEvent($eventId);
$this->event = $event;
parent::display($tpl);
}
function displayAdd($tpl = NULL){
JToolBarHelper::title('Event'.': [<small>Add</small>]');
JToolBarHelper::save();
JToolBarHelper::cancel();
parent::display($tpl);
}
}
default.php
<td colspan="9"><?php echo $this->pagination->getListFooter(); ?></td>
Can any help me what is wrong or what i am missing
This might be because the required Javascript frameworks aren't available. To ensure if this is the case, you can check your javascript console.
If that is the case, in your view extending JViewLegacy, before the line:
$this->pagination = $this->get('Pagination');
Insert below line:
JHtml::_('behavior.framework');
Also, make sure your template is not removing the required frameworks.
unset($doc->_scripts[JURI::root(true) . '/media/system/js/core.js']);
Comment out this line if you see it in your template index.php
Hope this helps :)
Extend class JModelList instead of JModelLegacy, that should sorry it out.