CodeIgniter - On click create table in database - codeigniter

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

Related

How to save dynamic form in laravel?

I Have a for where you can add multiple lines by click on a button and I want to store the data into the database
This is the error I get when I submit the form - Array to string conversion
Form inputs I didn't post the form element since I don't think I needed to show it here.
<input type="text" class="form-control" name="title[]" />
<input type="text" class="form-control" name="link[]" />
Controller
public function help_store(Request $request)
{
$helps = collect([]);
if ($request->title) {
foreach ($request->title as $key => $title) {
$model = Help::updateOrCreate([
'title' => $title
], [
'link' => $request->link[$key]
]);
$helps->push($model);
}
}
Help::whereNotIn('id', $helps->pluck('id'))->delete();
return redirect()->back();
}
I see this error
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'title' cannot be null (SQL: insert into helps (title, link, updated_at, created_at) values (?, ?, 2021-01-15 20:02:42, 2021-01-15 20:02:42))

Array field always stores the last value of the field into database

Help me working with array inputs on my project.
This is the form field:
<form action="" method="">
<input type="text" class="form-control" name="scores[]">
<input type="hidden" name="lesson_id[]" value="">
<input type="hidden" name="year_id" value="">
<input type="hidden" name="grade_id" value="">
<input type="hidden" name="clas_id" value="">
<input type="hidden" name="student_id" value="">
</form>
My Controller:
public function store(Request $request)
{
foreach ($request->scores as $score)
{
$scr = new Assestment;
$scr->year_id = $request->year_id;
$scr->grade_id = $request->grade_id;
$scr->clas_id = $request->clas_id;
$scr->student_id = $request->student_id;
foreach($request->lesson_id as $lesson)
{
$scr->lesson_id = $lesson;
}
$scr->score = $score;
$scr->save();
}
}
My Model:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Assestment extends Model
{
protected $table = 'assestments';
protected $fillable = [
'year_id', 'grade_id', 'clas_id', 'student_id', 'lesson_id', 'score',
];
public function students()
{
return $this->belongsToMany('App\Models\Student');
}
}
I would like to make the value of field "scores[]" and "lesson_id[]" as array so that they store multiple data to database.
But when I submit the form, the "lesson_id[]" always store the last value of the form. For example, the field "lesson_id[]" contains multiple values like "1, 2, 3 , 4", but the value stored into database is always "4 (the last value of the field)".
What should I do?
Only the last value is stored because you stored the data after foreach loop.
If you want to store the socres[] and lesson_id[] as an array in the same table, you can use serialize()
$scr = new Assestment;
$scr->year_id = $request->year_id;
$scr->grade_id = $request->grade_id;
$scr->clas_id = $request->clas_id;
$scr->student_id = $request->student_id;
$scr->lesson_id = serialize($request->lesson_id);
$scr->score = serialize($request->$score);
$scr->save();
To retreive each value, use unserialize()

Weird behaviour of CI after a redirect()

I have a strange bug during the password recovery process.
When a user loses his pwd, the app send an email with a token inside the recovery link ( http://localhost/reset-password/f38fd00aa975b28c70f54d948d20de40 for exemple ) This token is an unique key inside the user table.
In the routes.php, i have :
$route['reset-password/(:any)'] = "/user/reset_password_form/$1";// new password form
$route['reset-password'] = "/register/reset_password"; //simple email form
then, reset_password_form generates a form with the token as hidden input :
public function reset_password_form($hash = NULL) { //create form to change password, with user validation hash inside
$user_id = $this->user_model->get_id_by_confirmation_code(strip_tags($hash));
if (isset($user_id)) {
$this->data['validation_code'] = $hash;
$this->data['title'] = $this->lang->line('user_title_password_edit', FALSE);
$this->template->load('default', 'register/reset_password_form', $this->data);
}
else{
$this->session->set_flashdata('error', $this->lang->line('user_error_reset_password', FALSE));
redirect('reset-password');
}
the view:
<?php $attributes = array('class' => '');
echo form_open('user/edit_password', $attributes) ?>
<input type="hidden" id="validate" name="validate" value="<?=$validation_code?>">
<div class="form-group">
<input type="password" id="password" name="password" placeholder="Password" class="form-control" value="<?php echo set_value('password'); ?>">
</div>
<div class="form-group">
<input type="password" id="password_confirm" name="password_confirm" placeholder="Password confirmation" class="form-control">
</div>
<button type="submit" name="submit" class="btn btn-success">Change password</button>
</form>
Finally, the user/edit_password function changes the user password with a new one.
public function edit_password() { //get new password and change it
$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[6]');
$this->form_validation->set_rules('password_confirm', 'Confirm Password', 'trim|required|matches[password]');
$this->form_validation->set_rules('validate', 'Validate', 'trim|alpha_numeric|required');
if ($this->form_validation->run() === false) {
//STRANGE BUG
$URL = '/reset-password/'.$this->input->post('validate');
$this->session->set_flashdata('error', validation_errors());
redirect($URL);
}
else {
//change pssword
}
}
The bug happen when the form validation fail : i'm suposed to be redirected to the previous form ( /reset-password/hash) with a flashdata error message, but the error message dont display.
Much more weird : even if i'm on the right form ( but without error message) if i decides to click on another menu item (for exemple /home) , it immediately displays the /reset-password form ( /register/reset_password in the routes) with the error message i was supposed to get previously.
As if the full php instruction was kept in stamp and launched after whatever action.
PS : as edit_password() and reset_password_form() are in the same controller, i could have used $this->reset_password_form($hash) instead of redirect() but it has exactly the same effect !
ps2: here is the register/reset_password:
public function reset_password() {
//display forgotten password form page
$this->data['title'] = 'Forgotten password';
$this->template->load('default', 'register/reset_password', $this->data);
}
you recovery link http://localhost/reset-password/f38fd00aa975b28c70f54d948d20de40 is not finding controller. CI is looking for your token number as controller

wamp not saving data using codeigniter

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

Error 1054 in Codeigniter 2.1.3

I have the 1054 error in Codeigniter and I don't know why. I want to create a login form and check if the user is logged or not.
But I only create a simple view and controller and the following error is displayed:
Error Number: 1054
Unknown column 'user_data' in 'field list'
INSERT INTO `ci_sessions` (`session_id`, `ip_address`, `user_agent`, `last_activity`, `user_data`) VALUES ('c392322ac31b7fac1c2d79cfbde9edf7', '127.0.0.1', 'Opera/9.80 (Windows NT 6.1) Presto/2.12.388 Version/12.15', 1368010716, '')
Filename: C:\wamp\www\..\system\database\DB_driver.php
Line Number: 330
I only created the table session with this script:
CREATE TABLE IF NOT EXISTS `ci_sessions` (
session_id varchar(40) DEFAULT '0' NOT NULL,
ip_address varchar(45) DEFAULT '0' NOT NULL,
user_agent varchar(50) NOT NULL,
last_activity int(10) unsigned DEFAULT 0 NOT NULL,
PRIMARY KEY (session_id)
);
The view:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Anuncios</title>
<link rel="stylesheet" href="/Pruebas/css/estilos.css" type="text/css"
media="screen"/>
</head>
<body>
<div id="contenedor">
<div id="menu">
<label for="home" id="inicio"><a href="http://localhost/Pruebas/index.php/
cindice/">Inicio</a></label>
<label for="acceso" id="login"><a href="http://localhost/Pruebas/index.php/
cindice/publicar">Publicar anuncio</a></label>
<label for="reg" id="registro"><a href="http://localhost/Pruebas/index.php/
cindice/registro">Registro</a></label>
<label for="empresa" id="sobrempresa"><a href="http://localhost/Pruebas/
index.php/cindice/sobempresa">Sobre nosotros</a></label>
<label for="contacto" id="contactar"><a href="http://localhost/Pruebas/
index.php/cindice/contacto">Contáctanos</a></label>
</div>
</div>
</body>
</html>
The controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Cindice extends CI_Controller {
function __construct() {
parent::__construct();
}
public function index()
{
$this->load->view('indice');
}
public function publicar()
{
echo "Aquí se publica el anuncio";
}
public function acceso()
{
echo "Esto es el acceso";
}
}
?>
How can I fix this issue?
Thanks.
The manual states your ci_sessions table should be created like this:
CREATE TABLE IF NOT EXISTS `ci_sessions` (
session_id varchar(40) DEFAULT '0' NOT NULL,
ip_address varchar(45) DEFAULT '0' NOT NULL,
user_agent varchar(120) NOT NULL,
last_activity int(10) unsigned DEFAULT 0 NOT NULL,
user_data text NOT NULL,
PRIMARY KEY (session_id),
KEY `last_activity_idx` (`last_activity`)
);
Note the "user_data" field that's missing from your table.

Resources