hi i am trying to insert data into mysql database from my codeigniter form but its not working, instead it redirects me back to wampserver homepage. I am using wampserver and windows 2008 operating system. earlier on I had changed the httpd.conf port listen to 8080 since wamp was not working.
my database is;
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(32) NOT NULL,
`email` varchar(32) NOT NULL,
`password` varchar(32) NOT NULL,
`gender` varchar(8) NOT NULL,
`registered` varchar(16) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=6 ;
my model is:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class User_model extends CI_Model {
public function __construct()
{
parent::__construct();
}
public function add_user()
{
$data=array(
'username'=>$this->input->post('username'),
'email'=>$this->input->post('email'),
'password'=>md5($this->input->post('password')),
'gender'=>$this->input->post('gender'),
'registred'=>time()
);
$this->db->insert('users',$data);
return true;
}
}
my controller is:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class User extends CI_Controller {
public function index()
{
$this->load->view('register_view');
}
public function register()
{
$this->load->view('register_view');//loads the register_view.php file in views folder
}
public function do_register()
{
if($this->input->post('register'))//$_POST["register"];
{
$this->load->model('user_model');//loads the user_model.php file in models folder
if($this->user_model->add_user())
{
echo "hi ".$this->input->post('username')." Registred successfully" ;
}
else
{
echo "Registration failed";
}
}
}
}
my view is:
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf- 8"></head>
<body>
<div class="container">
<table>
<tr>
<form action="<?=site_url('user/do_register')?>" method="post">
<td><label for="username">User Name</label>
<input type="text" name="username"/></td>
<tr><td><label for="email">Email</label>
<input type="text" name="email"/></td></tr>
<tr><td><label for="password">Password</label>
<input type="password" name="password"/></td><tr>
<tr><td><label for="gender">Gender</label>
<input type="radio" name="gender" value="male"/>male
<input type="radio" name="gender" value="female"/>female</tr></td>
<tr><td><input type="submit" value="Sign up" name="register"/>
</tr></td>
</tr>
</form>
</table>
</div>
</body>
</html>
kindly assist me remove this error
Related
I'm new to laravel and I want to submit a registration user form that when clicked, data will be sent to my database (which is already configured) and the page will be directed to the login page but when I click submit button laravel, it says
"The POST method is not supported for this route. Supported methods: GET, HEAD."
I've searched a lot but i am clueless as i don't understand what to do.
My registration view
<?php
// Include config file
// Define variables and initialize with empty values
$username = $password = $confirm_password = "";
$username_err = $password_err = $confirm_password_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate username
if(empty(trim($_POST["username"]))){
$username_err = "Please enter a username.";
} else{
// Prepare a select statement
$sql = "SELECT id FROM users WHERE username = ?";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "s", $param_username);
// Set parameters
$param_username = trim($_POST["username"]);
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
/* store result */
mysqli_stmt_store_result($stmt);
if(mysqli_stmt_num_rows($stmt) == 1){
$username_err = "This username is already taken.";
} else{
$username = trim($_POST["username"]);
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
// Close statement
mysqli_stmt_close($stmt);
}
}
// Validate password
if(empty(trim($_POST["password"]))){
$password_err = "Please enter a password.";
} elseif(strlen(trim($_POST["password"])) < 6){
$password_err = "Password must have atleast 6 characters.";
} else{
$password = trim($_POST["password"]);
}
// Validate confirm password
if(empty(trim($_POST["confirm_password"]))){
$confirm_password_err = "Please confirm password.";
} else{
$confirm_password = trim($_POST["confirm_password"]);
if(empty($password_err) && ($password != $confirm_password)){
$confirm_password_err = "Password did not match.";
}
}
// Check input errors before inserting in database
if(empty($username_err) && empty($password_err) && empty($confirm_password_err)){
// Prepare an insert statement
$sql = "INSERT INTO users (username, password) VALUES (?, ?)";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "ss", $param_username, $param_password);
// Set parameters
$param_username = $username;
$param_password = password_hash($password, PASSWORD_DEFAULT); // Creates a password hash
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Redirect to login page
header("location: /");
} else{
echo "Something went wrong. Please try again later.";
}
// Close statement
mysqli_stmt_close($stmt);
}
}
// Close connection
mysqli_close($link);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sign Up</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
<style type="text/css">
body{ font: 14px sans-serif; }
.wrapper{ width: 350px; padding: 20px; }
</style>
</head>
<body>
<div class="wrapper">
<h2>Sign Up</h2>
<p>Please fill this form to create an account.</p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group <?php echo (!empty($username_err)) ? 'has-error' : ''; ?>">
<label>Username</label>
<input type="text" name="username" class="form-control" value="<?php echo $username; ?>">
<span class="help-block"><?php echo $username_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($password_err)) ? 'has-error' : ''; ?>">
<label>Password</label>
<input type="password" name="password" class="form-control" value="<?php echo $password; ?>">
<span class="help-block"><?php echo $password_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($confirm_password_err)) ? 'has-error' : ''; ?>">
<label>Confirm Password</label>
<input type="password" name="confirm_password" class="form-control" value="<?php echo $confirm_password; ?>">
<span class="help-block"><?php echo $confirm_password_err; ?></span>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Submit">
<input type="reset" class="btn btn-default" value="Reset">
</div>
<p>Already have an account? Login here.</p>
</form>
</div>
</body>
</html>
My Routes
<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/','LoginController#login');
Route::get('registration','LoginController#registration');
Route::get('welcome','LoginController#welcome');
My Controller (Not sure if this could be the source of the problem but....)
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class LoginController extends Controller
{
public function login()
{
return view('login');
}
public function registration()
{
return view('registration');
}
public function welcome()
{
return view('welcome');
}
}
And last but not least my login file which i don't think is necessary but I'll just share as well.
<?php
// Initialize the session
session_start();
// Check if the user is already logged in, if yes then redirect him to welcome page
if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true){
header("location: /welcome");
exit;
}
// Define variables and initialize with empty values
$username = $password = "";
$username_err = $password_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Check if username is empty
if(empty(trim($_POST["username"]))){
$username_err = "Please enter username.";
} else{
$username = trim($_POST["username"]);
}
// Check if password is empty
if(empty(trim($_POST["password"]))){
$password_err = "Please enter your password.";
} else{
$password = trim($_POST["password"]);
}
// Validate credentials
if(empty($username_err) && empty($password_err)){
// Prepare a select statement
$sql = "SELECT id, username, password FROM users WHERE username = ?";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "s", $param_username);
// Set parameters
$param_username = $username;
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Store result
mysqli_stmt_store_result($stmt);
// Check if username exists, if yes then verify password
if(mysqli_stmt_num_rows($stmt) == 1){
// Bind result variables
mysqli_stmt_bind_result($stmt, $id, $username, $hashed_password);
if(mysqli_stmt_fetch($stmt)){
if(password_verify($password, $hashed_password)){
// Password is correct, so start a new session
session_start();
// Store data in session variables
$_SESSION["loggedin"] = true;
$_SESSION["id"] = $id;
$_SESSION["username"] = $username;
// Redirect user to welcome page
header("location: /welcome");
} else{
// Display an error message if password is not valid
$password_err = "The password you entered was not valid.";
}
}
} else{
// Display an error message if username doesn't exist
$username_err = "No account found with that username.";
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
// Close statement
mysqli_stmt_close($stmt);
}
}
// Close connection
mysqli_close($link);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
<style type="text/css">
body{ font: 14px sans-serif; }
.wrapper{ width: 350px; padding: 20px; }
</style>
</head>
<body>
<div class="wrapper">
<h2>Login</h2>
<p>Please fill in your credentials to login.</p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group <?php echo (!empty($username_err)) ? 'has-error' : ''; ?>">
<label>Username</label>
<input type="text" name="username" class="form-control" value="<?php echo $username; ?>">
<span class="help-block"><?php echo $username_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($password_err)) ? 'has-error' : ''; ?>">
<label>Password</label>
<input type="password" name="password" class="form-control">
<span class="help-block"><?php echo $password_err; ?></span>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Login">
</div>
<p>Don't have an account? Sign up now.</p>
</form>
</div>
</body>
</html>
I have an input field and a button. when I click on the button, a table must be created in the database, and its name should be the input from the input field.
CONTROLLER:
function create()
{
$table = $this->input->post('table');
$this->M_users->create($table);
}
MODEL:
function create($table)
{
$sql = "CREATE TABLE ".$table." (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";
$query = $this->db->query($sql);
return $query;
}
VIEW:
<form method="post" action="<?php echo base_url('create');?>">
<input type="text" name="table">
<input type="submit" name="">
</form>
If you want to do it with forge class, refer the following link:
https://www.codeigniter.com/user_guide/database/forge.html
I am new to Laravel and I am trying to create a simple form that adds a record into a database table (that has 2 fields: ID and name).
Here is the code I have so far:
routes.php
Route::group(['middleware' => ['web']], function () {
Route::get('/banks/add', 'BanksController#add');
Route::post('/banks/add', 'BanksController#store');
});
BanksController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Requests\BankFormRequest;
use App\Bank;
class BanksController extends Controller
{
public function add() {
return view('banks.add');
}
public function store(BankFormRequest $request) {
$bank = new Bank(array(
'name' => $request->get('name'),
));
$bank->save();
return redirect('/banks/add')->with('status', 'Your bank has been created! Its name is: '.$request->get('name'));
}
}
BankFormRequest.php
<?php
namespace App\Http\Requests;
use App\Http\Requests\Request;
class BankFormRequest extends Request
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'name' => 'required|unique:banks|max:255',
];
}
}
Bank.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Bank extends Model
{
public $timestamps = false;
protected $guarded = ['id'];
}
banks/add.php
<form id="registerForm" role="form" method="post">
<pre><?=var_dump($errors)?></pre>
<pre>
<?php if (session()->has('status')): ?>
<?=session('status')?>
<?php endif; ?>
</pre>
<?php if (isset($errors) && $errors->any()): ?>
<?php foreach ($errors->all() as $error): ?>
<p class="alert alert-danger"><?=$erorr?></p>
<?php endforeach; ?>
<?php endif; ?>
<input type="hidden" name="_token" value="<?=csrf_token()?>">
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" placeholder="Bank name" name="name">
</div>
<button type="submit" class="btn btn-primary">Add</button>
</form>
banks table
CREATE TABLE `banks` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8
In the banks/add view I have the form and 2 var_dumps of the $errors and session('status') variables, but they are always NULL. Otherwise, the form validator works well and it inserts my input into the database if it passes the rules I defined.
Anyone knows what causes my errors to not be shown?
in your banks/add.php
<p class="alert alert-danger"><?=$erorr?></p>
$erorr is wrong
If you are using laravel 5.2 try to remove web middleware on the route group this will fix your problem. why? because the RouteServiceProvider class will add it for you.
line 53 - 60 as of this writing.
protected function mapWebRoutes(Router $router)
{
$router->group([
'namespace' => $this->namespace, 'middleware' => 'web',
], function ($router) {
require app_path('Http/routes.php');
});
}
i want create a search box , where we input student name then show all records of that students.my controller code is
public function search_function_in_controller()
{
if ($this->session->userdata('admin_login') != 1)
redirect('login', 'refresh');
$keyword = $_POST['keyword']; // you can also use $this->input->post('keyword');
$data['search_result'] = $this->crud_model->search($keyword);
$this->load->view('search_result', $data);
}
my model is :
function search($keyword)
{
$this->db->like('name',$keyword);
$query = $this->db->get('student');
return $query->result();
}
my view is :
<body>
<form action="<?=site_url('admin/search_function_in_controller')?>" method="post">
search: <input type="text" name="keyword" />
<input type="submit" value="Submit" />
</form>
<div>
<?php
// List up all results.
foreach ($results as $val)
{
echo $val['username'];
}
?>
</div>
</div>
</body>
but when we give input on search box then it give "Unable to load the requested file: search_result.php" , can anyone help me??
Verify the path that you've called in your view.
I think you intended to call the view admin/search_result in your function search_function_in_controller;
I want to do some api work in codeigniter,I am beginner with codeIgniter , I started studying codeigniter. know i want to know how to send the value to view.
In View folder I have written like this:
<h1 align="center">Test Sample CI Framwork</h1>
<form name="f1" action="" method="post"/>
<input type="text" name="firstname" value="" size="100" />
<input type="text" name="lastname" value="" size="100"/>
<div><input type="submit" value="Submit" name="submit"/></div>
</form>
<h1>The values from form:<?php echo $result; ?></h1>
IN controller:
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class add extends CI_Controller
{
public function index()
{
$this->load->view('add');
$this->getvalue();
}
function getvalue()
{
if ($this->input->post('submit'))
{
$data=$this->input->post('firstname');
$data=$this->input->post('lastname');
//help me what i have to do here.
}
}
}
?>
Yes, basically for transmit a data to the view, use :
$this->load->view('you-page',$data);
Your controller should be like this:
class add extends CI_Controller {
public function index() {
$data = array();
if ($this->input->post()) {
$data['firstname'] = $this->input->post('firstname');
$data['lastname'] = $this->input->post('lastname');
}
$this->load->view('add', $data);
}
}
////add.php////
<h1 align = "center">Test Sample CI Framwork</h1>
<form name = "f1" action = "" method = "post"/>
<input type = "text" name = "firstname" value = "" size = "100" />
<input type = "text" name = "lastname" value = "" size = "100"/>
<div>
<input type = "submit" value = "Submit" name = "submit"/>
</div>
</form>
<h1>The values from form:<?=$firstname . '-' . $lastname?></h1>