update record database in CodeIgniter - php

I already add,view,delete record but I can't update record in database. however when i try update name,alamat,etc is unchanged in database. I have listed my controller , model and view below:
model code
function update($id,$siswa)
{
$this->db->where($this->primary_key,$id);
$this->db->update($this->table_name,$siswa);
}
controller code
function update($id=1)
{
$this->_set_fields();
$siswa = $this->siswa_model->get_by_id($id)->row();
$this->form_validation->id = $id;
$this->form_validation->nama = $siswa->nama;
if (isset($_POST['jenis_kelamin'])) {
$_POST['jenis_kelamin'] = strtoupper($data['siswa']['jenis_kelamin']);
}
if (isset($_POST['tanggal_lahir'])) {
$data['siswa']['tanggal_lahir'] = date('d-m-Y',strtotime($data['siswa']['tanggal_lahir']));
}
$data['title'] = 'Update siswa';
$data['message'] = '';
$data['action'] = site_url('siswa/updateSiswa');
$data['link_back']= anchor('siswa/index/','Back to list of siswas',array('class'=>'back'));
$this->load->view('siswaEdit',$data);
}
function updateSiswa()
{
//set common properties
$data['title'] = 'Update siswa';
$data['action'] = site_url('siswa/updateSiswa');
$data['link_back']= anchor('siswa/index/','Back to list of siswas',array('class'=>'back'));
//$this->load->library('form_validation');
//set validation properties
$this->_set_fields();
$this->_set_rules();
//$data['action']=('siswa/update/'.$id);
//run validation
if ($this->form_validation->run() === FALSE) {
$data['message']='';
$data['siswa'] = $this->siswa_model->get_by_id($id)->row_array();
if (isset($_POST['jenis_kelamin'])) {
$_POST['jenis_kelamin'] = strtoupper($data['siswa']['jenis_kelamin']);
}
if (isset($_POST['tanggal_lahir'])) {
$data['siswa']['tanggal_lahir'] = date('d-m-Y',strtotime($data['siswa']['tanggal_lahir']));
}
//set common properties
$data['title']='Update siswa';
$data['message']='';
}
else
{
//save data
$id = $this->input->post('id');
$siswa=array( 'id'=>$id,
'nama'=>$this->input->post('nama'),
'alamat'=>$this->input->post('alamat'),
'jenis_kelamin'=>$this->input->post('jenis_kelamin'),
'tanggal_lahir'=>date('Y-m-d', strtotime($this->input->post('tanggal_lahir'))));
$this->siswa_model->update($id,$siswa);
$data['siswa'] = $this->siswa_model->get_by_id($id)->row_array();
//set user message;
$data['message']='update siswa success';
}
$data['link_back']= anchor('siswa/index/','Lihat Daftar Siswa',array('class'=>'back'));
//load view
$this->load->view('siswaEdit',$data);
}
view code
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>SIMPLE CRUD APPLICATION</title>
<link href="<?php echo base_url();?>style/style.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div class="content">
<h1><?php echo $title;?></h1>
<div class="data">
<table>
<tr>
<td width="30%">ID</td>
<td><?php
if (isset($siswa->id)) {
echo $siswa->id;}
;?>
</td>
</tr>
<tr>
<td valign="top">Name</td>
<<td><?php
if (isset($siswa->nama)) {
echo $siswa->nama;}
;?>
</td>
</tr>
<tr>
<td valign="top">Alamat</td>
<td><?php
if (isset($siswa->alamat)) {
echo $siswa->alamat;}
;?>
</td>
</tr>
<tr>
<td valign="top">Jenis Kelamin</td>
<td><?php if (isset($siswa->jenis_kelamin)){
echo ($siswa->jenis_kelamin) =='M'?'Laki-Laki':'Perempuan';}
;?>
</td>
</tr>
<tr>
<td valign="top">Tanggal Lahir (dd-mm-yyyy)</td>
<td><?php if (isset($siswa->jenis_kelamin)){
echo date('d-m-Y',strtotime($siswa->tanggal_lahir));}
;?>
</td>
</tr>
</table>
</div>
<br/>
<?php echo $link_back;?>
</div>
</body>
</html>
can you help me find problem solving from my program?

I think the view page that you have shown above, it just list the record. you can list it in form to submit the data.

Related

I want my button to change the Status set, but instead of changing it, goes to a href page instead

First off: There are no YouTube videos or tutorials for this as far as I know. I found some but they were JavaScript, but I have no knowledge of it so I can't do it in a very short time.
I recently posted the same question but altered my codes after some people's suggestions. I got a lot of errors instead of a solution...
Anyway, I have a picture of my site and what I want to do.
Site:
https://imgur.com/a/hcpuA
and here's a picture of what I want to do:
https://imgur.com/a/Vuuk9
And finally my codes are below, I cut down the HTML parts which isn't really necessary.
adduser.php:
<?php
session_start();
if (!isset($_SESSION['username']))
{
header('location: login.php');
die();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Manage users</title>
<link rel="icon" type="image/png" sizes="16x16" href="image/favicon-16x16.png">
<link rel="icon" type="image/png" sizes="32x32" href="image/favicon-32x32.png">
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" type="text/css" href="css/table.css">
</head>
<body>
<?php include ("header.php"); ?>
<?php
require ("config.php");
?>
<form name="frmSearch" method="post" action="adduser.php">
<div class="table-container">
<div class="table-something">
<div class="table-header">
<span id="message"></span>
<h2>Admin List<span class="blink">_</span> </h2>
<input name="var1" type="text" id="var1" />
<input class="dede" type="submit" name="search" value="search" />
</div>
<div class="table-body">
<table class="table-hen">
<?php
if (isset($_POST['var1'])) {
$var1 = $_POST['var1'];
}
else {
$var1 = 1;
}
$sql= "SELECT user_id, fname, mname, lname, username, type, a_e_num, user_status FROM users WHERE a_e_num LIKE :search";
$stmt = $db->prepare($sql);
$stmt->bindValue(':search', '%' . $var1 . '%', PDO::PARAM_INT);
$stmt->execute();
if ($stmt->rowCount() > 0) {
?>
<tr>
<th>User Id</th>
<th>Name </th>
<th>Username</th>
<th>Employee # </th>
<th>User Type</th>
<th>Status</th>
<th>Action</th>
</tr>
<?php
$result = $stmt->fetchAll();
foreach ($result as $row):
?>
<tr>
<td><?php echo $row['user_id']; ?></td>
<td><?php echo $row['fname']; ?> <?php echo $row['mname']; ?> <?php echo $row['lname']; ?> </td>
<td><?php echo $row['username']; ?></td>
<td><?php echo $row['a_e_num']; ?> </td>
<td><?php echo $row['type']; ?></td>
<td>
<?php if ($row['user_status']=='Enable') echo "Active";
if ($row['user_status']=='Disable') echo "Disabled" ?>
</td>
<td>
<?php
$user_id = $row['user_id'];
$status = '';
if ($row['user_status'] == 'Enable') {
$status = 'Enable';
}
else if ($row['user_status'] == 'Disable') {
$status = 'Disable';
}
?>
<?php
$user_id = $row['user_id'];
$status = $row['user_status'];
?>
<a class="archive" action="archive.php" onclick="
return confirm('Are you sure you want to <?php if ($row['user_status']=='Enable') echo "disable";
if ($row['user_status']=='Disable') echo "enable"?> this user account?')"
href="archive.php?user_id=<?= $user_id?>&status=<?=$status?>">
<?php if ($row['user_status']=='Disable')
echo "Unarchive";
if ($row['user_status']=='Enable')
echo "Archive" ?>
</a></td>
</tr>
<?php endforeach;
} else {
echo 'there is nothing to show';
}
?>
</table>
</form>
</div>
</div>
</div>
<br><h1></h1>
<br><h1></h1>
<br><h1></h1>
<br><h1></h1>
<br><h1></h1>
<?php include ("footer.php"); ?>
</body>
</html>
And here's my Archive.php:
<?php
require ("config.php");
$user_id= $_GET['user_id'];
$user_status = $_GET['user_id'];
$query = $db->prepare ("SELECT * FROM users WHERE user_id = :user_id, user_status = :user_status");
$query->bindParam(':user_id', $user_id);
$query->bindParam(':user_status',$user_status);
$query->execute();
if ($user_status=='Enable')
{
$sql = "UPDATE users SET user_status = 'Disable' WHERE user_id = :user_id";
}
if ($user_status=='Disable')
{
$sql = "UPDATE users SET user_status='Enable' WHERE user_id = :user_id";
}
if ($query->execute([':user_status'=>$user_status, ':user_id'=>$user_id])){
header("Location:adduser.php");
}
?>
First you need to clear your statement and separate your parameters like below.
Step 1:
Parameters are (Query String) which start with ? and more paramters will be followed by &
<?php
$user_id = $row['user_id'];
$status = '';
if ($row['user_status'] == 'Enable') {
$status = 'Enable';
} else if ($row['user_status'] == 'Disable') {
$status = 'Disable';
}
?>
<a href="archive.php?user_id=<?=$user_id?>&user_status=<?=$status?>">
IF your $row['user_status'] value is always same as conditional statement then you don't need condition simply follow assign variable.
<?php
$user_id = $row['user_id'];
$status = $row['user_status'];
?>
<a href="archive.php?user_id=<?=$user_id?>&status=<?=$status?>">
Step 2:
Then this
$id= $_GET['user_id'];
To
$user_id= $_GET['user_id'];
$user_status = $_GET['user_status'];
because your bind parameters take variable which is not defined in your Archive.php
$query->bindParam(':user_id', $user_id);
$query->bindParam(':user_status',$user_status);
EDIT 2:
change your ` where it start with
<td>
<?php
$user_id = $row['user_id'];
$status = $row['user_status'];
Just replace with below.
<td>
<?php
$user_id = $row['user_id'];
$status = $row['user_status'];
$btn_confirm = '';
if ($status == 'Enable') {
$btn_confirm = "disable";
} else if ($status == 'Disable') {
$btn_confirm = "enable";
}
?>
<a class="archive" onclick="return confirm('Are you sure you want to <?= $btn_confirm; ?> this user account?')"
href="Archive.php?user_id=<?= $user_id ?>&status=<?= $status ?>">
<?php if ($status == 'Disable') {
echo "Unarchive";
} else if ($status == 'Enable') {
echo "Archive"; }
?>
</a>
</td>
Note: your file name is Archive.php not archive.php this causing issue for blank page

PHP codeigniter - how to return to DB table after updating row

I want my admin table view to reload after uses selects Edit, changes entry and selects Update Entry with the edits reflected in the revised table row.
The admin edit page is working fine, and I know the solve for redirecging the update to the table page is basic. Some light guidance would be much appreciated!
Admin View:
<html>
<head>
<title>Admin Page</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body background=http://wallpapercave.com/wp/ItmVuT6.jpg>
<div class="container">
<table class="table table-bordered">
<center>
<thead>
<tr style="font-size: 24; color: white;">
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th colspan="2">Actions</th>
</tr>
</thead>
</center>
<tbody style="background-color: #F0F8FF;">
<?php
foreach($users as $u)
{
$class = "btn btn-primary";
$button = "Approve";
?>
<tr style="font-size: 20;">
<td><?php echo $u->first_name; ?></td>
<td><?php echo $u->last_name; ?></td>
<td><?php echo $u->email; ?></td>
<td><a class="btn btn-success" href="<?php echo site_url('myform/edituser/' . $u->id); ?>">Edit</a></td>
<td><a class="<?php echo $class;?>" href="/ci/index.php/myform/approve/?user_id=<?php echo $u->id;?>"><?php echo $button;?></a></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</body>
</html>
Admin Edit View:
<html>
<head>
<title>Edit User Info</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body background=http://wallpapercave.com/wp/ItmVuT6.jpg>
<div class="container">
<div class="jumbotron">
<form action="" method="post">
<p><font color="black" font size='5'/><strong>Entry for ID </strong><strong>"<?php echo $id; ?>"</strong></font></p>
<font color="black" font size='5'/><strong>First Name </strong></font><input type="text" name='first_name' value="<?php echo $first_name; ?>"?><br/>
<font color="black" font size='5'/><strong>Last Name </strong></font><input type="text" name='last_name' value="<?php echo $last_name; ?>"/><br/>
<font color="black" font size='5'/><strong>Email </strong></font><input type="text" name='email' value="<?php echo $email; ?>"/><br/>
<br/>
<input type="button" class="btn btn-info" value="Update Entry">
</div>
</div>
</form>
</body>
</html>
Controller:
<?php
class Myform extends CI_Controller{
public function __construct(){
parent::__construct();
}
public function index(){
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('user[first_name]', 'First Name', 'required');
$this->form_validation->set_rules('user[last_name]', 'Last Name', 'required');
$this->form_validation->set_rules('user[email]', 'Email Address', 'required|trim');
$form['userValues'] = [
'first_name' => $this->input->post('user[first_name]'),
'last_name' => $this->input->post('user[last_name]'),
'email' => $this->input->post('user[email]'),
'id' => $this->input->post('id'),
];
if ($this->form_validation->run() == FALSE)
{
$this->load->view('myform');
}
else
{
$user = $this->input->post('user');
//$company = $this->input->post('company');
echo '<pre>';
print_r($user);
//print_r($company);
if ($this->input->post('id') !== '' && $this->input->post('id') !== NULL)
{
$this->db->where('id', (int) $this->input->post('id'));
$this->db->update("User_Inputs", $user);
}
else
{
$this->db->insert("User_Inputs", $user);
}
//$this->db->insert("companies", $company);
redirect("/myform/successmessage");
}
}
public function successmessage(){
$this->load->view('formsuccess');
}
public function getDatabase(){
$data['users'] = $this->db->get("User_Inputs")->result();
$this->load->view('adminlogin', $data);
}
public function approve(){
$id = $this->input->get("user_id");
$this->db->where("id", $id);
$data['user'] = $this->db->get("User_Inputs")->row();
echo "<pre>";
print_r($this->db->last_query());
print_r($data);
echo "<h1>". $data['user']->email."</h1>";
die();
}
public function edituser($user_id = NULL)
{
$user_id = (int) $user_id;
$data['user'] = $this->db
->where('id', $user_id)
->get("User_Inputs")
->row();
$form['dbValue'] = [
'first_name' => $data['user']->first_name,
'last_name' => $data['user']->last_name,
'email' => $data['user']->email,
'id' => $user_id
];
$this->load->view('editfields', $data['user']);
}
}

MySQL Table Editing w/ PHP CodeIgniter

I'm unsure how to get my editfields.php file to load when an administrator selects the Edit button for whatever row in my SQL table (adminlogin.php).
I feel my editfields.php file has the right stuff, but I'm stuck when it comes to getting the data and having that data display in my view as opposed to what I have printing according to my edituser function.
** PLEASE ignore the approve function for now, as well as the if conditionak in adminlogin.php, both items for separate discussion **
Below are the following files:
Controller (Myform.php)
<?php
class Myform extends CI_Controller{
public function __construct(){
parent::__construct();
}
public function index(){
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('user[first_name]', 'First Name', 'required');
$this->form_validation->set_rules('user[last_name]', 'Last Name', 'required');
$this->form_validation->set_rules('user[email]', 'Email Address', 'required|trim');
if ($this->form_validation->run() == FALSE){
$this->load->view('myform');
}
else{
$user = $this->input->post('user');
$company = $this->input->post('company');
echo '<pre>';
print_r($user);
print_r($company);
$this->db->insert("User_Inputs", $user);
$this->db->insert("companies", $company);
redirect("/myform/successmessage");
}
}
public function successmessage(){
$this->load->view('formsuccess');
}
public function getDatabase(){
$data['users'] = $this->db->get("User_Inputs")->result();
$this->load->view('adminlogin', $data);
}
public function approve(){
$id = $this->input->get("user_id");
$this->db->where("id", $id);
$data['user'] = $this->db->get("User_Inputs")->row();
echo "<pre>";
print_r($this->db->last_query());
print_r($data);
echo "<h1>". $data['user']->email."</h1>";
die();
}
public function edituser(){
$data['user'] = $this->db->get("User_Inputs")->row();
echo "<pre>";
print_r($this->db->last_query());
print_r($data);
echo "<h3>Showing results for ID #". $data['user']->id."</h3>";
die();
/* $data = array($id);
$this->db->where('id', $id);
$this->db->update('users', $data); */
}
}
Table View (adminlogin.php)
<html>
<head>
<title>Admin Page</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body background=http://wallpapercave.com/wp/ItmVuT6.jpg>
<div class="container">
<table class="table table-bordered">
<center>
<thead>
<tr style="font-size: 24; color: white;">
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th colspan="2">Actions</th>
</tr>
</thead>
</center>
<tbody style="background-color: #F0F8FF;">
<?php foreach($users as $u){
$class = "btn btn-primary";
$button = "Approve";
if ($u->id == 7){
$class = "btn btn-danger";
$button = "Deny";
} ?>
<tr style="font-size: 20;">
<td><?php echo $u->first_name; ?></td>
<td><?php echo $u->last_name; ?></td>
<td><?php echo $u->email; ?></td>
<td><a class="btn btn-success" href="/ci/index.php/myform/edituser?user_id=<?php echo $u->id;?>">Edit</a></td>
<td><a class="<?php echo $class;?>" href="/ci/index.php/myform/approve?user_id=<?php echo $u->id;?>"><?php echo $button;?></a></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</body>
</html>
Edit View (editfields.php)
<html>
<head>
<title>Edit User Info</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body background=http://wallpapercave.com/wp/ItmVuT6.jpg>
<form action="" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<div>
<p><strong>ID:</strong><?php echo $id; ?></p>
<strong>First Name</strong><input type="text" name='first_name' value="<?php echo $first_name; ?>"?>"/><br/>
<strong>Last Name</strong><input type="text" name='last_name' value="<?php echo $last_name; ?>"/><br/>
<strong>Email</strong><input type="hidden" name='email' value="<?php echo $email; ?>"/><br/>
<input type="submit" name="submit" value="Update">
</div>
</form>
</body>
</html>
The most basic, fundamental example I want to achieve at this juncture is at the following, though this example may not fit according to my code:
http://www.killersites.com/community/index.php?/topic/1969-basic-php-system-vieweditdeleteadd-records/
I've updated my answer with the full test code for controller and views:
Myform.php
<?php
class Myform extends CI_Controller {
public function __construct()
{
parent::__construct();
// Added form and url helper so all functions can use them.
$this->load->helper(array('form', 'url'));
}
public function index()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('user[first_name]', 'First Name', 'required');
$this->form_validation->set_rules('user[last_name]', 'Last Name', 'required');
$this->form_validation->set_rules('user[email]', 'Email Address', 'required|trim|valid_email');
// The only reason i store the values in this variable is to
// allow the re-use of the same form for both index and edituser
// functions. This allows the re-population rule to work.
$form['dbValue'] = [
'first_name' => $this->input->post('user[first_name]'),
'last_name' => $this->input->post('user[last_name]'),
'email' => $this->input->post('user[email]'),
'id' => $this->input->post('id'),
];
if ($this->form_validation->run() == FALSE)
{
$this->load->view('myform', $form);
}
else
{
// I've disabled company here as i could not find any reference to it
// in the form you have given as an example
$user = $this->input->post('user');
// $company = $this->input->post('company');
echo '<pre>';
print_r($user);
// print_r($company);
if ($this->input->post('id') !== '' && $this->input->post('id') !==NULL)
{
// id is defined so we update the user
$this->db
->where('id', (int) $this->input->post('id'))
->update("User_Inputs", $user);
}
else
{
// id is not define so we create the user
$this->db->insert("User_Inputs", $user);
}
// $this->db->insert("companies", $company);
redirect("/myform/getDatabase");
}
}
public function successmessage()
{
$this->load->view('formsuccess');
}
public function getDatabase()
{
$data['users'] = $this->db->get("User_Inputs")->result();
$this->load->view('adminlogin', $data);
}
public function approve()
{
$id = $this->input->get("user_id");
$this->db->where("id", $id);
$data['user'] = $this->db->get("User_Inputs")->row();
echo "<pre>";
print_r($this->db->last_query());
print_r($data);
echo "<h1>" . $data['user']->email . "</h1>";
die();
}
public function edituser($user_id = NULL)
{
// Just making sure we are capturing the id as an integer
$user_id = (int) $user_id;
// Get the user based on the $user_id
$data['user'] = $this->db
->where('id', $user_id)
->get("User_Inputs")
->row();
// We will use the below variable to set the form fields to the correct values.
$form['dbValue'] = [
'first_name' => $data['user']->first_name,
'last_name' => $data['user']->last_name,
'email' => $data['user']->email,
'id' => $user_id
];
$this->load->view('myform', $form);
}
}
View: adminlogin.php
<html>
<head>
<title>Admin Page</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body background=http://wallpapercave.com/wp/ItmVuT6.jpg>
<div class="container">
<table class="table table-bordered">
<center>
<thead>
<tr style="font-size: 24; color: white;">
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th colspan="2">Actions</th>
</tr>
</thead>
</center>
<tbody style="background-color: #F0F8FF;">
<?php
foreach ($users as $u)
{
$class = "btn btn-primary";
$button = "Approve";
if ($u->id == 7)
{
$class = "btn btn-danger";
$button = "Deny";
}
?>
<tr style="font-size: 20;">
<td><?php echo $u->first_name; ?></td>
<td><?php echo $u->last_name; ?></td>
<td><?php echo $u->email; ?></td>
<td><a class="btn btn-success" href="<?php echo site_url('myform/edituser/' . $u->id); ?>">Edit</a></td>
<td><a class="<?php echo $class; ?>" href="<?php echo site_url('myform/approve/' . $u->id); ?>"><?php echo $button; ?></a></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</body>
</html>
View: myform.php
<?php
// if the set_value default values are not set set them to NULL
echo form_open('myform');
echo form_label('First Name', 'first_name');
echo form_input('user[first_name]', set_value('user[first_name]', isset($dbValue['first_name'])) ? $dbValue['first_name'] : '' );
echo form_label('Last Name', 'last_name');
echo form_input('user[last_name]', set_value('user[last_name]', isset($dbValue['last_name'])) ? $dbValue['last_name'] : '' );
echo form_label('Email', 'email');
echo form_input('user[email]', set_value('user[email]', isset($dbValue['email'])) ? $dbValue['email'] : '' );
echo form_hidden('id', set_value('id', isset($dbValue['id'])) ? $dbValue['id'] : '' );
echo form_submit('Submit', 'submit');
echo form_close();
echo validation_errors();
OK, for ajax see the below modifications:
I've added jquery library and bootstrap library,
adminlogin.php
<html>
<head>
<title>Admin Page</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
</head>
<body background=http://wallpapercave.com/wp/ItmVuT6.jpg>
<div class="container">
<table class="table table-bordered">
<center>
<thead>
<tr style="font-size: 24; color: white;">
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th colspan="2">Actions</th>
</tr>
</thead>
</center>
<tbody style="background-color: #F0F8FF;">
<?php foreach ($users as $u): ?>
<?php
// added approve class
$class = "approve btn btn-primary";
$button = "Approve";
if ($u->id == 7)
{
$class = " deny btn btn-danger";
$button = "Deny";
}
?>
<!-- id is added to each row to uniquely identify them so we can change it's color-->
<tr id="row_<?= $u->id ?>"style="font-size: 20;">
<td><?php echo $u->first_name; ?></td>
<td><?php echo $u->last_name; ?></td>
<td><?php echo $u->email; ?></td>
<td><a class="btn btn-success" href="<?php echo site_url('myform/edituser/' . $u->id); ?>">Edit</a></td>
<!-- data-id was added to store the user id -->
<td><a class="<?php echo $class; ?>" data-id="<?= $u->id ?>" href="<?php echo site_url('myform/approve/' . $u->id); ?>"><?php echo $button; ?></a></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<script>
$('.approve').on("click", function (e) {
// prevent the browser to loading the page directly
e.preventDefault();
// get the user id from the button we clicked.
var userid = $(this).data('id');
//initiate ajax request
$.ajax({
url: $(this).attr('href'),
method: 'POST',
success: function (data) {
// on success add the bootstrap success class to the row
$('#row_' + userid).addClass('success')
},
error: function (data) {
// on error add boorstrap dange class to the row
$('#row_' + userid).addClass('danger')
}
});
});
</script>
</body>
</html>
for testing purposes i've changed the myform/approve function
public function approve()
{
//do something this is for testing
$result = true;
if ($result)
{
// success you have done was OK and we send back success code
$this->output->set_status_header(200);
} else
{
// failure we send back an 4* cient error code
$this->output->set_status_header(400);
}
}

Search not functiong using pdo

I have a project that I'm doing now and my project consist of CRUD functions and it works fine. My project also has its pagination and search function.
The pagination is working but the search function does not seem to work. What I want is, a search where I can search anything within my table like I want to search all the fields or maybe a live search. Can somebody please help me.
Dbconfig.php
<?php
$db_host = 'localhost'
$db_username = 'root';
$db_password = '';
$db_name = 'survey';
try{
$db_con = new PDO("mysql:host={$db_host};dbname={$dbname}",db_username,$db_password);
}
catch(PDOException $exception{
echo $exception->getMessage();
}
include_once 'class.paginate.php'
$paginate = new paginate($DB_con);
?>
Class.paging.php
<?php
class paginate{
private $db;
function __construct($DB_con)
{
$this->db = $DB_con;
}
public function dataview($query)
{
$stmt = $this->db->prepare($query);
$stmt->execute();
if($stmt->rowCount()>0)
{
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
?>
<tr>
<td><?php echo $row['user_id']; ?></td>
<td><?php echo $row['username']; ?></td>
<td><?php echo $row['password']; ?></td>
<td><?php echo $row['province']; ?></td>
<!-- <td>visit</td> -->
</tr>
<?php
}
}
else
{
?>
<tr>
<td>Nothing here...</td>
</tr>
<?php
}
}
public function search($query)
{
$stmt=$this->db->prepare($query);
$query = '%' . $query . '%';
$stmt->bindparam('query', $query, PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_OBJ);
if(empty($result) or $result == false)
return array();
else
return $result;
}
public function paging($query,$records_per_page)
{
$starting_position=0;
if(isset($_GET["page_no"]))
{
$starting_position= ($_GET["page_no"]-1)*$records_per_page;
}
$query2=$query." limit. $starting_position,$records_per_page";
return $query2;
}
public function paginglink($query,$records_per_page)
{
$self = $_SERVER['PHP_SELF'];
$stmt = $this->db->prepare($query);
$stmt->execute();
$total_no_of_records = $stmt->rowCount();
if($total_no_of_records > 0)
{
?><tr><td colspan="4" align="center"><?php
$total_no_of_pages=ceil($total_no_of_records/$records_per_page);
$current_page=1;
if(isset($_GET["page_no"]))
{
$current_page=$_GET["page_no"];
}
if($current_page!=1)
{
$previous =$current_page-1;
echo "<a href='".$self."?page_no=1'>First</a> ";
echo "<a href='".$self."?page_no=".$previous."'>Previous</a> ";
}
for($i=1;$i<=$total_no_of_pages;$i++)
{
if($i==$current_page)
{
echo "<strong><a href='".$self."?page_no=".$i."' style='color:red;text-decoration:none'>".$i."</a> </strong> ";
}
else
{
echo "<a href='".$self."?page_no=".$i."'>".$i."</a> ";
}
} if($current_page!=$total_no_of_pages)
{
$next=$current_page+1;
echo "<a href='".$self."?page_no=".$next."'>Next</a> ";
echo "<a href='".$self."?page_no=".$total_no_of_pages."'>Last</a> ";
}
?></td></tr><?php
}
}
}
Index.php
<html>
<head>
<link rel="stylesheet" href="style.css" type="text/css" />
<link rel="stylesheet" type="text/css" href="Bootstrap/bootstrap.css">
<script type="text/javascript" src="js/jquery-2.1.3.min.js"></script>
<body>
<div id="search-wrapper">
<form name="search" method="GET" action="">
<table id="search" class="table-responsive">
<tr>
<input name="var1" type="text" id="search-box">
<button id="submit" name="submit" type="submit">Search</button>
</tr>
</table>
<?php
$query = "SELECT * FROM `login` WHERE (`username` like :query or `password` like :query) ";
$paginate->search($query)
?>
</form>
</div>
<div id="table-wrapper" class="table-responsive">
<table id="data" class="table table-striped table-hover">
<thead>
<tr>
<th>ID</th>
<th>Username</th>
<th>Password</th>
<th>Actions</th>
</tr>
</thead>
<?php
$query = "SELECT * FROM login";
$records_per_page=20;
$newquery = $paginate->paging($query,$records_per_page);
$paginate->dataview($newquery);
$paginate->paginglink($query,$records_per_page);
?>
</table>
</div>
<div id="footer">
cleartuts.blogspot.com
</div>
</body>
</html>

PHP search with class and public function

How can i run search function? i cant display the any result with this code and i don't know how to handle this class and function.. i'm a newbie with this kind of code..please review my codes....thanks!!!
<?php
$txtsearch = $_POST['txtsearch'];
class BlogController{
public function search($txtsearch){
$mysqli = new mysqli("localhost","root","","sample_db");
$display_query = "SELECT * FROM `tb_blogs` WHERE id='$txtsearch' ";
$result = $mysqli->query($display_query);
}
}
if(isset($_POST["btnsearch"])){
echo BlogController::search();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
Create New Blog<br>
<form action="function.php" method="post">
<input text-align:right type="text" name="txtsearch" placeholder="search">
<input type="submit" name="btnsearch" value="Search">
<table border="1" width="60%" cellpadding="2" cellspacing="0">
<thead>
<tr>
<th width="5%">ID</th>
<th width="20%">Title</th>
<th width="20%">Author</th>
<th width="40%">Content</th>
<th width="15%">Action</th>
</tr>
</thead>
<tbody>
<?php while($blog = $result->fetch_object()): ?>
<tr>
<td><?php echo $blog->id?></td>
<td><?php echo $blog->title?></td>
<td><?php echo $blog->author?></td>
<td><?php echo $blog->content?></td>
<td>
Edit
<a class ="btn_del" href="delete.php?blog_id=<?php echo $blog->id;?>">Delete</a>
</td>
</tr>
<?php endwhile?>
</tbody>
</table>
<script type="text/javascript">
$(function(){
$(".remove-btn").on('click',function(){
var is_confirm = confirm("Do you want to delete record?");
if(is_confirm){
window.location = $(this).attr('href');
}
return false;
});
});
</script>
</form>
</body>
</html>
Try this :
class BlogController{
public $txtsearch;
function __construct($search) {
$this->$txtsearch = $search;
}
public function search(){
$mysqli = new mysqli("localhost","root","","sample_db");
$display_query = "SELECT * FROM `tb_blogs` WHERE id='$this->$txtsearch' ";
$result = $mysqli->query($display_query);
return $result;
}
}
Create an instance and then call the function search
$myclass = new BlogController($_POST['txtsearch']); //pass value to the construct function
print_r($myclass->search()); // will return an array

Categories