problem :- it is inserting data in table blank even after using form_validation
and i tried if condition for checking cat_title then it works
so basically i want to use it without using if contidtion.
i think the problem is in my controller.
this one is my controller
class Cat extends CI_Controller {
//insert in table
public function addcat()
{
$this->form_validation->set_rules('cat_title', 'Category', 'required');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('admin/addcategory');
}
else
{
$this->load->view('admin/addcategory');
}
$data['cat_title'] = $this->input->post('cat_title');
$this->cat_model->create_cat('category',$data);
}
// print data
public function showcat()
{
$data['result'] = $this->cat_model->get_cat();
$this->load->view('admin/showcategory',$data);
}
}
?>
this is my model
<?php
class Cat_model extends CI_Model {
// get table from database
public function get_cat(){
$query = $this->db->get('category');
return $query->result();
}
public function create_cat($table,$data){
//insert data in table
$query = $this->db->insert($table,$data);
return $query;
}
}
?>
and this my form in html i create form using codeigniter
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<?php $this->load->view('includes/admincss');?>
</head>
<style>
</style>
<body>
<?php $this->load->view('includes/adminheader');?>
<section>
<div class="col-lg-12 mrg-top">
<div class="row">
<?php $this->load->view('includes/header_nav');?>
<div class="col-lg-10">
<h1>Add Category</h1>
<?php echo validation_errors(); ?>
<?php echo form_open('cat/addcat'); ?>
<div class="form-group">
<label for="pwd">Type in below Input</label>
<input type="text" class="form-control" name="cat_title">
</div>
<button type="submit" name="submit" class="btn btn-dark">Submit</button>
<?php echo form_close(); ?>
</div>
</div>
</div>
</section>
<?php $this->load->view('includes/adminfooter');?>
</body>
</html>
MySQL column is not null set it for example ,if column be nullable your code works
ALTER TABLE table_name MODIFY mycolumn varchar(255) null;
Related
having an issue with page chrome saying there are too many redirects, the page, finally does what i want(at least does function correctly as far as i know, as i tested it with a close connection, sticking at the top of page, and it is displaying the userID. When logged in this page does the redirecting, im not too sure how to fix this, found lots of different posts online, and each one was so different from the next.
<?php session_start();
include'../../connection.php';?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="description" content="">
<meta name="keywords" content="">
<link rel="stylesheet" type="text/css" href=".../../../../style.css">
<title>Home</title>
<!--[if IE]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<?php include('../../main/main.php');?>
</head>
<body>
<div class=containermain>
<h1>I5-6600k.php</h1>
<form action="ratepost.php" method="post">
<label for="rating">rating:</label>
<select name="rating" id="rating" value="rating" >
<option>
<option value="1">1 </option>
<option value="2">2</option>
<option value="3">3 </option>
<option value="4">4</option>
<option value="5">5</option>
</option>
</select>
<input type="submit" value="Submit">
</form>
<h2>graphics card write up................</h2>
<?php echo "Hello " . $_SESSION['user']; ?>
<p> </p>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
</div>
<div
class="fb-like"
data-share="true"
data-width="450"
data-show-faces="true">
</div>
<!---------------------------------------COMMENT BOX---------------------------------------------------->
<div class="comments" align="center">
<form action="" method="post" >
<textarea rows="4" cols="50" name="comment">
Please type a comment if you are logged in....
</textarea>
<input type="submit" value="Submit">
</form>
<?php
if (isset($_SESSION['login_id']) && !empty($_SESSION['login_id'])) {
$id = $_SESSION['login_id'];
$sqlinsert = "INSERT INTO comment (userID, comment, dCpuID) VALUES ('$id', '$comment', '1')";
if(mysqli_query($conn, $sqlinsert)){
header("Location: i5-6600k");
} else {
echo "ERROR: Could not able to execute $sqlinsert. " . mysqli_error($conn);
}
}
// close connection
$sql = "SELECT `users`.`username`, `comment`.`comment`, `comment`.`timestamp`\n"
. "FROM `users`\n"
. "LEFT JOIN `comment` ON `users`.`userID` = `comment`.`userID` \n"
. "where dCpuID = 1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>Username</th><th>Comment</th><th>Timestamp</th>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["username"]. "</td><td>" . $row["comment"]."</td><td>" . $row["timestamp"]. "</td>";
}
echo "</table>";
} else {
echo "0 results";
}
?>
</div>
<?php include('../../assets/footer.php');?>
<div class="fb-comments" data-href="http://www.computercomparison.tk/#home" data-numposts="5"></div>
</body>
</html>
I think I see what you are doing here, you are missing how to effectively process an action. You are triggering your comment by checking if something, which is persistent, exists and acting on it. If it's a session variable, it will persist, therefore the action is infinite until it stops persisting. You need an action in your submission.
I would have a config page that you include with all pages that contains re-usable variables. It would be stored in the root of the site. In general, you have some HTML errors and some unsafe SQL injection issues. I have created a little more complicated version of your page (without the bottom half, that needs a lot of work and should be wrapped as well) but it's only complicated to make the view less complicated...if that makes sense. Anyway, if you have issues let me know, I haven't tested this.
/config.php
<?php
# Create some absolute defines for consistent includes
define('DS',DIRECTORY_SEPARATOR);
define('ROOT_DIR',__DIR__);
define('VENDOR',ROOT_DIR.DS.'vendor');
define('SITE_URL','http://www.example.com');
# Start session
session_start();
# Autoloads all the classes we intend to use
spl_autoload_register(function($class){
$path = VENDOR.DS.trim(str_replace('\\',DS,$class),DS).'.php';
if(is_file($path))
require_once($path);
});
/vendor/App.php
<?php
# General/base class used for various time-saving actions
class App
{
# Store this object for re-use
protected static $singleton;
# Store others (if using getHelper() method)
protected static $apps;
# Create singleton
public function __construct()
{
if(!(self::$singleton instanceof \App))
self::$singleton = $this;
# Return back the same object
return self::$singleton;
}
# Get either the full post or just one key/value
public function getPost($key=false)
{
if(!empty($key))
return (isset($_POST[$key]))? $_POST[$key] : false;
return $_POST;
}
# Get session or just one key/value pair
public function getSession($key=false)
{
if(!empty($key))
return (isset($_SESSION[$key]))? $_SESSION[$key] : false;
return $_SESSION;
}
# Write and destroy session value
public function writeError($key)
{
$error = $this->getSession($key);
$this->destroy($key);
return $error;
}
public function destroy($key = false)
{
if(!empty($key)) {
if(isset($_SESSION[$key]))
$_SESSION[$key] = NULL;
return;
}
session_destroy();
}
# Sets a session value
public function setSession($key,$value)
{
$_SESSION[$key] = $value;
}
# Consistent way to write the site url (set in the config)
public function siteUrl($path = false,$ssl=false)
{
return ($ssl)? str_replace('http://','https://',SITE_URL).$path : SITE_URL.$path;
}
# Creates an instance if this object
public static function call()
{
return new \App();
}
# Saves and uses classes
public function getHelper($class,$inject=NULL)
{
$setKey = str_replace('\\','',$class);
if(isset(self::$apps[$setKey]))
return self::$apps[$setKey];
self::$apps[$setKey] = new $class($inject);
return self::$apps[$setKey];
}
}
/vendor/Router/Model.php
<?php
# Use for redirects, can be expanded out to do other router-type things
namespace Router;
class Model extends \App
{
public function addRedirect($path)
{
header('Location: '.$path);
exit;
}
}
/vendor/View/Model.php
<?php
# This is a wrapper for the page
namespace View;
class Model extends \App
{
public function render($path)
{
if(!is_file($path))
return;
# Create a buffer and render contents
ob_start();
include($path);
$data = ob_get_contents();
ob_end_clean();
return $data;
}
}
/vendor/Commenter/Model.php
<?php
namespace Commenter;
class Observer extends \Router\Model
{
# Listen for action name, do action when required
public function listen($conn)
{
if($this->getPost('action') != 'addcomment')
return false;
if(!empty($this->getSession('login_id'))) {
$id = $this->getSession('login_id');
# You will want to bind parameters on this. This is an opening for SQL Injection (Google it)
$sqlinsert = "INSERT INTO comment (userID, comment, dCpuID) VALUES ('$id', '".$this->getPost('comment')."', '1')";
if(mysqli_query($conn, $sqlinsert))
$this->addRedirect("i5-6600k");
else
$this->setSession('error',"ERROR: Could not able to execute $sqlinsert. " . mysqli_error($conn));
}
}
}
whatever this page is called...
<?php
# Create separator
$DS = DIRECTORY_SEPARATOR;
# Include config file
include(realpath(__DIR__.$DS.'..'.$DS.'..').$DS.'config.php');
# Check to see if this file is being wrapped by render class
if(!isset($this)) {
# Include this file into the renderer
echo \App::call()->getHelper('\View\Model')->render(__FILE__);
exit;
}
# Include connection
include(ROOT_DIR.DS.'connection.php');
# Listen for the add comment action
$this->getHelper('\Commenter\Observer')->listen($conn);
?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="description" content="">
<meta name="keywords" content="">
<link rel="stylesheet" type="text/css" href="<?php echo $this->siteUrl('/style.css') ?>">
<title>Home</title>
<!--[if IE]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<?php include(ROOT_DIR.DS.'main'.DS.'main.php');?>
</head>
<body>
<div class="containermain" style="padding-bottom: 60px;">
<h1>I5-6600k.php</h1>
<form action="ratepost.php" method="post">
<label for="rating">rating:</label>
<select name="rating" id="rating" value="rating">
<?php for($i=1; $i<=5;$i++) { ?>
<option value="<?php echo $i ?>"><?php echo $i ?></option>
<?php } ?>
</select>
<input type="submit" value="Submit">
</form>
<h2>graphics card write up................</h2>
Hello <?php echo $this->getSession('user') ?>
</div>
<div class="fb-like" data-share="true" data-width="450" data-show-faces="true"></div>
<!--- COMMENT BOX --->
<div class="comments" align="center">
<?php echo $this->writeError('error') ?>
<form action="" method="post" >
<!-- YOU NEED TO SEND AN ACTION WORD HERE AND CHECK FOR IT
TO PROCESS POST -->
<input type="hidden" name="action" value="addcomment" />
<textarea rows="4" cols="50" name="comment">Please type a comment if you are logged in...</textarea>
<input type="submit" value="Submit">
</form>
...etc.
I'm trying to develop a simple login system, but i'm facing issue during data validation.
Everything works if I enter valid data.
but when i enter invalid data it like empty user or password, it gives me validation erorr, but after that if i enter the correct user data. it wont work, it will just reload the the same page.
The strange thing that i noticed is that the url on the address bar keeps getting longer.
My login url after clicking submit button the first time.
http://localhost/ci/login/validate
My login url after clicking submit button the second time.
http://localhost/ci/login/login/validate
Every time i click the submit button, it keeps adding an extra '/login' to url.
any idea what the problem is?
My main controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login extends CI_Controller {
public function index()
{
$this->load->view('login/header');
$this->load->view('login/login_view');
$this->load->view('login/footer');
}
public function validate()
{
$this->load->model('login_model');
$this->load->library('form_validation');
$this->form_validation->set_rules('username','Username', 'trim|required|min_length[6]|max_length[50]|valid_email|xss_clean');
$this->form_validation->set_rules('password','Password', 'trim|required|xss_clean');
//validation check
if ($this->form_validation->run() == FALSE)
{
$this->load->view('login/header');
$this->load->view('login/login_view');
$this->load->view('login/footer');
}
else
{
$userdata['username'] = $_POST['username'];
$userdata['password'] = md5($_POST['password']);
//check whether user exist int the database or not
$result = $this->login_model->login_validation($userdata);
//in case user exists
if($result == 1)
{
$this->set_sessions_details();
}
//in case user doesnt exist
else
{
$data['flag'] = "Incorrect Username or Password!";
$this->load->view('login/header');
$this->load->view('login/login_view', $data);
$this->load->view('login/footer');
}
}
}
//load a view in case user exists in the db.
public function set_sessions_details()
{
$this->load->view('test');
}
}
My model to check user data in db.
login_model
class Login_model extends CI_Model
{
function login_validation($userdata)
{
$user=$userdata['username'];
$pass=$userdata['password'];
$result = $this->db->get_where('users', array('username' => $user, 'password' => $pass));
return $result->num_rows();
}
}
?>
My views:
login_view
<h3>Please Login</h3>
<form method='post' action='login/validate'>
<div class="form-group" >
<label for="username">Username</label>
<input type="email" class="form-control" name="username" id="username" placeholder="Enter Username">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" name="password" id="password" placeholder="Enter Password">
</div>
<button type="submit" class="btn btn-success">Login</button>
<?php echo validation_errors('<p class"errors">');?>
</form>
<?php if (isset($flag)){ ?>
<p><?php echo $flag; ?> </p>
<?php } ?>
header
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>WFD</title>
<link href="<?php echo base_url();?>assets/css/bootstrap.min.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class='container'>
<div class="header">
<center><img src="<?php echo base_url();?>assets/images/logo.png" alt="logo" style="margin-top: 10px; padding-bottom: 20px; opacity: 1;">
<h2>
Welfare Foundation Database
</h2>
</center>
</div>
Footer
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="/ci/assets/js/bootstrap.min.js"></script>
</body>
</html>
try using the form open tag in Form Helper link : https://ellislab.com/codeigniter/user-guide/helpers/form_helper.html
echo form_open('email/send');
which in the backend will create
See if this solves your issue.
I believe that, besides #Abhijit answer, your problem is the logic itself. You aren't redirecting to anywhere, and you should be. Besides you're calling repeated code unnecessarily, such as:
$this->load->view('login/header');
$this->load->view('login/login_view');
$this->load->view('login/footer');
This should only be called in one function,
public function index(){
$this->load->view('login/header');
$this->load->view('login/login_view');
$this->load->view('login/footer');
}
public function validate(){
// your validation logic
if ($this->form_validation->run() == FALSE){
$this->session->set_flashdata('error', array('msg' => 'Upps, something went wrong..', 'anotherParam' => 'anotherText'));
// this will load again the views
redirect('login');
return;
}
}
You are now able to maintain the form as you have:
<form method="POST" action="login/validate">
</form>
<?php if($this->session->flashdata('error')){ ?>
<p><?php echo $this->session->flashdata('error')->msg; ?></p>
<?php } ?>
Use url library in controllers:
$this->load->helper('url');
Use it on view
<form action="<?php echo base_url('login/validate'); ?>" method="POST">
<!-- your input -->
</form>
I am trying to create a login form using CodeIgniter in PHP. I have implemented the functionality, working okay, however I cannot manage to style my for with a custom stylesheet.
Here is the code I have for the login view:
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset="UTF-8" />
<title>
DTI Manager
</title>
<link rel="stylesheet" type="text/css" href="/DTIManager/assets/css/style.css" />
</head>
<body>
<div id="wrapper">
<?php echo validation_errors();?>
<?php $attributes = array('class' => 'LoginController', 'id' => 'login-form');
echo form_open('LoginController/checkLogin', $attributes);?>
<form name="login-form" class="login-form" action="" method="post">
<div class="header">
<h1>Autentificare</h1>
<span>Pentru a accesa informatii despre comenzi transporturi trebuie sa fiti autentificat.</span>
</div>
<div class="content">
<input name="username" type="text" class="input username" placeholder="Utilizator" />
<div class="user-icon"></div>
<input name="password" type="password" class="input password" placeholder="Parola" />
<div class="pass-icon"></div>
</div>
<div class="footer">
<input type="submit" name="submit" value="Login" class="button"/>
</div>
</form>
</div>
<div class="gradient"></div>
</body>
</html>
And this is my LoginController class:
class LoginController extends CI_Controller {
function __construct() {
parent::__construct();
}
public function index() {
$this->load->view('login');
}
public function checkLogin() {
$this->form_validation->set_rules('username', 'Utilizator', 'required');
$this->form_validation->set_rules('password', 'Parola', 'required|callback_verifyUser');
if ($this->form_validation->run() == false) {
$this->load->view('login');
} else {
redirect('HomeController/index');
}
}
public function verifyUser() {
$name = $this->input->post('username');
$pass = $this->input->post('password');
$this->load->model('LoginModel');
if ($this->LoginModel->login($name, $pass)) {
return true;
} else {
$this->form_validation->set_message('verifyUser', 'Incorrect Email or Password. Please try again.');
return false;
}
}
}
I tried adding the attribute to the form_open function the ID of my form but it wasn't successful, the buttons and fields are still not styled accordingly.
Any hints are highly appreciated.
Try echoing the base_url() in front of your linked css files.
<link rel="stylesheet" type="text/css" href="<?php echo base_url();?>DTIManager/assets/css/style.css" />
Of course, if you use an .htaccess you should ignore the folder that has the assets in your project with a proper rewrite rule.
RewriteCond $1 !^(index\.php|DTIManager|assets|robots\.txt|error\.html)
Im a newbie in CodeIgniter and I just followed a tutorial for CRUD operations within framework but my data is not getting inserted in my database. Here is my code:
Controller: site.php
<?php
class Site extends CI_Controller
{
function index()
{
$this->load->view("home");
}
function create()
{
$data=array('title'=>$this->input->post("title"),
'song'=>$this->input->post("song")
);
$this->site_model->add_record($data);
$this->index();
}
}
View: home.php
<html>
<head>
<title>my page</title>
<style type="text/css">
input,label
{
display:block;
}
</style>
</head>
<body>
<?php echo form_open('site/create'); ?>
<p>
<label for="title">Title:</label>
<input type="text" name="title" id="title" />
</p>
<p>
<label for="content">Song:</label>
<input type="text" name="song" id="song" />
</p>
<p>
<input type="submit" value="submit"/>
</p>
<?php echo form_close(); ?>
</body>
</html>
Model: site_model.php
<?php
class site_model extends CI_Model
{
function getAll()
{
$q=$this->db->get('name');
return $q->result();
}
function add_record($data)
{
$this->db->insert("name",$data);
return;
}
function update_record($data)
{
$this->db->where("id",14);
$this->db->update('name',$data);
}
function delete_row($data)
{
$this->db->where("id",$this->uri->segment(3));
$this->db->delete('name',$data);
}
}
My table name is name and I have 3 fields: id(auto_increment), title, and song. Help would be much appreciated.
Add this line before you calling model function.
$this->load->model('site_model');
after that call your model function
$this->site_model->add_record($data);
I think this will solve your problem
Regards
iijb
My controls receives some params from the user, I would like to place them inside the view I'm calling, how should I do this without splitting the view into multiple parts?
Thank you.
If I understand correctly, you should be able to do something like this for your controller
<?php
class Blog extends Controller
{
function index()
{
$data['title'] = "My Real Title";
$data['heading'] = "My Real Heading";
$this->load->view('blogview', $data);
}
}
?>
And something like this for your view:
<html>
<head>
<title><?php echo $title;?></title>
</head>
<body>
This is from the Codeignitor User guide here
In Controller:
function show_something() {
$data = array();
if ($this->input->post('some_form_field') {
$data['form_value'] = $this->input->post('some_form_field');
}
$this->load->view('some_view');
}
In View:
<html>
<head>
</head>
<body>
<?php if ($form_value): ?>
<h1><?= $form_value; ?></h1>
<?php endif; ?>
<form method="post" action="">
<input type="text" name="some_form_field" />
<input type="submit" value="Show Value on Page" />
</form>
</body>
</html>
in controller
function show_something() {
$data = array();
if ($this->input->post('some_form_field') {
$data['form_value'] = $this->input->post('some_form_field');
}
$this->load->view('some_view', $data);
}
in view
<html>
<head>
</head>
<body>
<?php if ($form_value): ?>
<h1><? echo $form_value; ?></h1>
<?php endif; ?>
<form method="post" action="">
<input type="text" name="some_form_field" />
<input type="submit" value="Show Value on Page" />
</form>
</body>
</html>