I have problem in updating fields in database via codeigniter update method
My controller:
$database = array(
'last_location' => $url[5]."-".$url[6],
'last_date_location' => $url[3]." ".$url[4],
);
$user = $this->API_model->get_user($url[0]);
print_r($user);
if ($this->db->update('user', $database , $user['id']) === true) {
print_r($database);
echo "MEI_TRUE";
}else {
echo "MEI_FALSE";
}
browser return MEI_TRUE that mean database successfully updated but when I check database in phpmyadmin nothing changed :(
what 's the problem?
It should work now.
$database = array(
'last_location' => $url[5]."-".$url[6],
'last_date_location' => $url[3]." ".$url[4],
);
$user = $this->API_model->get_user($url[0]);
print_r($user);
$query = $this->db->where('id',$user['id'])
->update('user', $database);
if ($query) {
print_r($database);
echo "MEI_TRUE";
}else {
echo "MEI_FALSE";
}
Can you try something like below,
$database = array(
'last_location' => $url[5]."-".$url[6],
'last_date_location' => $url[3]." ".$url[4],
);
$this->db->where('id', $user['id']);
$this->db->update('user', $database );
Hope this will help you
the thing is - what do you want to update ?
the 3rd parameter of the update query lets you enable the where clause as a string
although your example is pretty dangerous, try the following
if ($this->db->update('user', $database , "id = ".$user['id']) === true)
{
print_r($database);
echo "MEI_TRUE";
}
else
{
echo "MEI_FALSE";
}
the better way would be (as Dhanesh already mentioned):
$blnUpdateSuccess = $this->db->where("id", $user['id'])->update("user",$database);
if ($blnUpdateSuccess)
{
print_r($database);
echo "MEI_TRUE";
}
else
{
echo "MEI_FALSE";
}
For more information read the Documentation here
Related
I use CI 2.2 to build a simple login system. But I get problem when I try to generate session. Of course I have properly set up libraries (database, session) and User_M. When I retrieve data from database (without session), that's work fine. This is my Controller code:
public function verify()
{
// Define variable
$user = $this->input->post('username');
$pass = $this->input->post('password');
// Check input data
if (!empty($user) AND !empty($pass))
{
// Check match data from db
$checks = $this->User_M->check_user($user, $pass);
if($checks->num_rows() == 1)
{
foreach ($checks->result() as $check)
{
$sess = array (
'username' => $check->username,
'logged_in' => TRUE
);
$rest = $this->session->set_userdata($sess);
if ($rest)
{
echo "working";
} else {
echo "not working";
}
}
} else {
echo "Not found";
}
} else {
echo "You've empty field";
}
}
Additional explain, I check the result with if ($rest)...bla..bla..bla, that's echoing Not Working. Please let me know where's my mistakes?
Thank in advance
I think the problem is with this statement
$rest = $this->session->set_userdata($sess);
the set_userdata() does not return anything, so according to your condition it will always execute the else part.
Try to change your condition like this
if (!empty($this->session->userdata("username"))){
echo "Working";
}else{
echo "Not Working";
}
I have retrieved data from DB and inserted into a html table however I want to make each value in the table a hyperlink to another page. Below I have tried making the pupil_id and link to a profile.php but all pupil_id values have now vanished!
(if (!isset($_POST['search'])) {
$pupils = mysql_query("SELECT * FROM pupil") or die("Cant find Pupils");
$count = mysql_num_rows($pupils);
if ($count == 0) {
$totalpupil = "There are currently no Pupils in the system.";
} else {
while ($row = mysql_fetch_array($pupils)) {
?>
<tr>
<td><?php echo '<a href="profile.php?id=' .$row['pupil_id'] . '"</a>' ?></td>
<td><?php echo $row['pupil_name'] ?></td>
<td><?php echo $row['class_id'] ?></td>
</tr>
<?php
}
}
})
The finishing table should display every hyperlink as a hyperlink to another page. Any help?
Because your HTML is invalid, you are missing a closing > and you have no text defined for the hyperlink
<?php echo '<a href="profile.php?id=' .$row['pupil_id'] . '"</a>' ?> //Wrong
Correct would be
<?php echo ''.$row['pupil_id'].''; ?>
Try replace this:
<?php echo '<a href="profile.php?id=' .$row['pupil_id'] . '"</a>' ?>
with this:
<?php echo "<a href='profile.php?id=".$row['pupil_id']."'>link</a>"; ?>
Also, you dont have <table> tags at all.
You don't put any text between your link tags, text here
Maybe this will help you:
<td><?php echo ''.$row['pupil_name'].'' ?></td>
http://uk3.php.net/mysql_query
Watch out, which ever resource you are learning from may well be quite old. mysql_query is now deprecated.
http://uk3.php.net/manual/en/ref.pdo-mysql.php is a replacement.
Here is a kick starter to using PDO (this is much much safer) i write a while ago.
Include this file in which ever php script needs to access your db. An example file name would be 'database.php' but that is your call. Set the namespace from 'yourproject' to whatever your project is called. Correct the database credentials to suit your database
This will save you a lot of headaches hopefully!
I have given some example uses at the bottom for you. I remember when i started out getting clear advice was sometimes hard to come by.
//***** in a database class file*****/
namespace yourproject;
class Database {
private $db_con = '';
/*** Function to login to the database ***/
public function db_login()
{
// Try to connect
try{
// YOUR LOGIN DETAILS:
$db_hostname = 'localhost';
$db_database = 'yourdatabasename';
$db_username = 'yourdatabaseusername';
$db_password = 'yourdatabasepassword';
// Connect to the server and select database
$this->db_con = new \PDO("mysql:host=$db_hostname;dbname=$db_database",
"$db_username",
"$db_password",
array(\PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
// Prevent emulation of prepared statements for security
$this->db_con->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);
$this->db_con->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
return true;
}
// If it fails, send user to maintenance page
catch(PDOException $e)
{
header("location:http://yourwebsiteurl.com/maintenance.php");
exit();
}
}
/*** Function for database control ***/
public function db_control($query , $parameters, $returnID = false)
{
if(!is_array($query) && is_array($parameters))
{
try{
//prepare the statement
$statement = $this->db_con->prepare($query);
//execute the statement
$statement->execute($parameters);
//check whether this is a select, if it is then we need to retrieve the selected data
if(strpos($query, 'SELECT') !== false)
{
//fetch the results
$result = array();
while( $row = $statement->fetch(\PDO::FETCH_ASSOC) )
{
$result[] = $row;
}
//count the results
$count = count($result);
//return the array
return array( 'results' => $result, 'result_count' => $count );
}
//else return the number of affected rows
else{
//count the affected rows and place into a returnable array
$affected_rows = $statement->rowCount();
$returnArray = array('result_count' => $affected_rows);
//check to see if we are to return a newly inserted autoincrement ID from an INSERT
if($returnID)
{
//find the newly created ID and add this data to the return array
$insertID = $this->db_con->lastInsertId();
$returnArray['ID'] = $insertID;
}
return $returnArray;
}
}
catch(PDOException $e)
{
return false;
}
}
else{
return false;
}
}
}
// Start the database class and connect to the database then create a globally accessible function for ease of reference
$db = new \yourproject\Database();
$db->db_login();
function _db( $sql , $params , $returnID = false ){
return $GLOBALS['db']->db_control( $sql , $params , $returnID );
}
When you include this file you now have a new function: _db(). As the function is global it can be called from within any class or std file. When called into a variable as demonstrated below will result in an array like this:
array(
'result_count' => 3,
'results' => array(
array(/*row 1*/),
array(/*row 2*/),
array(/*row 3*/),
.. etc etc
)
)
Now include your database file in your php script:
//call in the database file
require_once 'database.php';
//your query as in the op
$sql = 'SELECT * FROM pupil';
//your params for the query
$params = array();
//running the query and getting the results returned into a variable called $query
$query = _db($sql,$params);
//if no results
if( $query['result_count'] == 0 )
{
echo 'sorry no pupils in the system';
}
else
{
//looping through each result and printing into a html table row
for( $i = 0 ; $i < $query['result_count'] ; ++$i )
{
echo '<tr><td><a href="profile.php?id=' . $query['results'][$i]['pupil_id'] . '"</a></td>';
echo '<td>'. $query['results'][$i]['pupil_name'] . '</td>';
echo '<td>'. $query['results'][$i]['class_id'] . '</td></tr>';
}
}
Your original query but with some parameters passed through
//Passing parameters to the query
//your query
$sql = 'SELECT * FROM pupil WHERE pupil_id = :pupil_id AND class_id = :class_id';
//your params for the query
$params = array(
':pupil_id' => 12,
':class_id' => 17,
);
//running the query and getting the results returned into a variable called $query
$query = _db($sql,$params);
//deal with the results as normal...
If you set the 3rd param as true you can return the automatic id of the row just entered eg:
//where $sql is a query that will INSERT a row
$query = _db($sql,$params, true);
Ive got a Codeigniter login system here, and just wondering where im going wrong. Heres my code:
View
<?php
echo form_open('handyman/logIn');
echo form_label('Email: ','useremail');
echo form_input('useremail');
echo "<br />";
echo form_label('Password: ','userpassword');
echo form_input('userpassword');
echo "<br />";
echo form_submit('Logmein','Log In');
echo form_close();
?>
Controller
public function logIn(){
$useremail=$this->input->post('useremail');
$userpassword=md5($this->input->post('userpassword'));
$this->load->model("HandymanModel");
if($useremail && $userpassword && $this->HandymanModel->logInUser($useremail,$userpassword)){
$data['msg']="Successfully Logged in!";
$data['title']="Logged In";
$this->load->view("header",$data);
$this->load->view("confirmation",$data);
$this->load->view("footer",$data);
} else{
$data['title']="Sign up / Log in";
$this->load->view("header",$data);
$this->load->view("page3", $data);
$this->load->view("footer",$data);
}
}
Model
function logInUser($useremail,$userpassword) {
$this->db->where('email',$useremail );
$this->db->where( 'password', $userpassword );
$login = $this->db->get()->result();
if (is_array($login) && count($login) == 1) {
return true;
} else {
return false;
}
I'm getting Error Number: 1064 which is check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE email = 'email#gmail.com' AND password = '1a1dc91c9073' at line 2
Thanks
You re missing the table name
$login = $this->db->get( )->result();
^^here
Try this by adding table name
$login = $this->db->get('your table name')->result();
$this->db->get();
I would change your model to something like...
function logInUser($useremail,$userpassword) {
$query = $this->db->query('SELECT * FROM tbl_name WHERE account_email="'.$useremail.'" AND account_password = "'.$userpassword.'"');
if ($query->num_rows() != 0){
return true;
} else {
return false;
}
}
I would also suggest encrypting user passwords as well. take a look at MD5. Make sure you use a hash as well.
Cheers!
I am getting the following error message for each variable:
Message: Undefined index: on lines 59, 60, 61, 62
I cannot understand why as it is definitely getting the sessions data and also the databases are setup and their is a user which matches that criteria.
jobs.php(apply function):
public function apply(){
if($this->session->userdata('is_logged_in')){
$this->load->view('header');
$this->load->view('job');
$id = $this->session->userdata('id');
$query = $this->db->get_where('jobseeker_profiles', array('jobseeker_id' => $id));
$user = $query->row_array();
$points = $user['total_points_value'];
$name = $user['name'];
$email = $user['email'];
$jobseeker_profile_id = $user['id'];
$employer_profile_id = $this->input->post('employer_id');
$job_id = $this->input->post('job_id');
$this->db->set('jobseeker_profile_id', $jobseeker_profile_id);
$this->db->set('employer_profile_id', $employer_profile_id);
$this->db->set('job_id', $job_id);
$this->db->set('name', $name);
$this->db->set('email', $email);
$this->db->set('points_value', $points);
if($this->input->post('submit')){
$this->db->insert('applications');
}
redirect('applied-for');
}else{
redirect('login');
}
}
}
Hope fully you can help, thanks!
Have you checked if the 4 database variables you are setting in those lines are rightly declared in the table ? They have to match to work.
do some quick error checking directly from the controller or model like
// check if query did not come back
if ( ! $query = $this->db->get_where('jobseeker_profiles',array('jobseeker_id' => $id)) )
{ echo 'OMFG WHERE IS MY QUERY ???' ; }
else
{ $user = $query->row_array();
echo 'QUERY WORKED, User Name is:' . $user['name'] ;
}
and if this does not work, go back and make sure you are loading the database, that the user/password is correct, etc
I'm trying to pull data off my sql table with php unique to the session's ID, however I only get the position that the user is in when I echo anything out!
<?php
include 'core/init.php';
$user_info = $_SESSION['user_id'];
?>
<html>....
<h1><?php echo $user_info['firstname'];?> <?php echo $user_info['firstname'];?> </h1>
displays as:
5 5
if I log in with the fifth position in the database!
The reason why you are getting 5 is for this code:
<?php echo $user_info['firstname'];?>
is that $_SESSION['user_id'] 's value is 5. So after the assignment $user_info's value is 5. Now because the $_SESSION['user_id'] is not set to an array as your intention seems to be. The result is that $user_info is taken as a string and ['firstname'] evaluates to [0]. If you like, you can update the ID 5 to 54, etc. You will always get the first character of your ID.
To correct this, try changing the last 2 lines before the return in your user_data function to:
$data = mysql_fetch_assoc(mysql_query("SELECT $fields FROM `users` WHERE `user_id` = $user_id"));
$data = array_merge(array($user_id), $data);
return $data;
if (logged_in() === true) {
$user_data = user_data($_SESSION['user_id'], 'username', 'first_name', 'last_name', 'email');
$user_data = user_data($session_user_id, 'user_id', 'username', 'first_name', 'last_name', 'email');
}
to:
if (logged_in() === true) {
$user_data = user_data($_SESSION['user_id'], 'username', 'first_name', 'last_name', 'email');
$_SESSION['user_id'] = $user_data;
}
if (logged_in === true) {
should be
if (logged_in()) {
for me it seems like you forgot to update data in session.
lets say here:
if (logged_in() === true) {
$user_data = user_data($_SESSION['user_id'], 'username', 'first_name', 'last_name', 'email');
$user_data = user_data($session_user_id, 'user_id', 'username', 'first_name', 'last_name', 'email');
$_SESSION = array_merge($_SESSION, $user_data);
}
hope it helps you to resolve your problems.
What I see that your in this line
<h1><?php echo $user_info['firstname'];?> <?php echo $user_info['firstname'];?> </h1>
you are using "firstname", whereas in database it is named as "first_name", see underscore
<h1><?php echo $user_info['first_name'];?> <?php echo $user_info['first_name'];?> </h1>
Let me know if this solves or not as I too want to know its answer
May help you some changes in your code
function user_data($user_id) {
$data = array ();
$user_id = (int)$user_id;
$func_num_args = func_num_args();
$func_get_args = func_get_args();
if ($func_num_args > 1) {
unset($func_get_args[0]);
$fields = '`'. implode('`, `', $func_get_args). '`';
echo '<br>'.
$que = "SELECT $fields FROM `users` WHERE `id` = $user_id";
$data = mysql_fetch_assoc(mysql_query($que));
print_r ($data);
return $data;
}
}
function logged_in() {
return (isset($_SESSION['id'])) ? true : false;
}
if (logged_in() === true) {
$user_data = user_data($_SESSION['user_id'], 'username', 'firstname', 'email');
//$user_data = user_data($session_user_id, 'user_id', 'username', 'firstname', 'email');
print_r($user_data);
}
echo
$user_info = $user_data;//$_SESSION['user_id'];
?>
<h1><?php echo $user_info['firstname'];?> <?php echo $user_info['firstname'];?> </h1>
function user_data($data=array(),$whereData=array()) {
$str='';
if(isset($whereData) && is_array($whereData))
{
foreach($whereData as $key=>$val)
{
if($val!='')
if($str=='')
$str = $key." = '".$val."'";
else
$str .= " AND ".$key." = '".$val."'";
}
}
$condition =
$fields = implode(',' , $data);
if($str!=''){
$data = mysql_fetch_assoc(mysql_query("SELECT $fields FROM `users` WHERE $str"));
}
else
{
$data = mysql_fetch_assoc(mysql_query("SELECT $fields FROM `users` ));
}
return $data;
print_r ($data);
}
}
and
if (logged_in() === true) {
$data = array('username', 'first_name', 'last_name', 'email');
$where=array('user_id'=>$_SESSION['user_id'])
$_SESSION['data'] = user_data($data, $where);
}
and
<?php
include 'core/init.php';
$user_info = $_SESSION['data'];
?>
<html>....
<h1><?php echo $user_info['firstname'];?> <?php echo $user_info['firstname'];?> </h1>
From experience of creating large code bases in PHP and when you expand the application you will find you are using more and more data all over the place from the users table. Also, the table should only really contain the most vital data that is comonly used and you do NOT want to be sending more than 1 or 2 queries to the users table per page hit as it can soon become a bottle neck. For this reason you are better storing all of the data data (move large fields to another table or fields rarely used). Then store the whole user record in a session which means any function, class etc can use it as it becomes a superglobal and you can trust it enough to use it throughout the entire application without needed to re-query the users table again and again.
I have written a working example (suing your db table structure) and commented it all throughout explaining why i have done it the way i have and some points you might want to consider.
//change from user_data() to get_user_data() so we know we are "getting" it, makes it a little clearer
function get_user_data($user_id) {
//protect agains sql injections
$user_id = mysql_real_escape_string($user_id);
//you should also be using mysqli or PDO, not the outdated mysql library - just check the php documentation if you don't believe me ;)
$result = mysql_query("SELECT * FROM `users` WHERE `id` = '{$user_id}' LIMIT 1");
//only if the previous query returned a result do we want to fetch an array from it
if ($result) {
return mysql_fetch_assoc($result);
}
//query didn't work (syntax error for example) so return blank array
return array();
}
//start and restore the session
session_start();
//if first page hit, set the user details element
if (isset($_SESSION['user_details']) == false) {
$_SESSION['user_details'] = array();
}
//if already logged in, refresh their user details incase there were any changes
if (isset($_SESSION['user_details']->user_id)) {
//refresh the user data
$_SESSION['user_details'] = get_user_data($_SESSION['user_details']->user_id);
}
//login
if (empty($_POST['id']) == false) {
$_POST['id'] = trim($_POST['id']);
if (is_numeric($_POST['id'])) {
$_SESSION['user_details'] = get_user_data($_POST['id']);
}
}
//logout
if (isset($_GET['logout'])) {
if ($_GET['logout'] == session_id()) {
$_SESSION['user_details'] = array();
}
}
//see if logged in so we know what to display
if (empty($_SESSION['user_details'])) {
//not logged in
print "<form method='post' action=''><label>User ID</label><input type='text' name='id' value='5' /><input type='submit' value='Login' /></form>";
} else {
//is logged in
print "<a href='?logout=" . rawurlencode(session_id()) . "'>logout</a>";
}
//proof that it works
print '<pre>';
print_r($_SESSION['user_details']);
print '</pre>';
P.S. Also you may want to start using LIMIT in your SQL queries as LIMIT 1 in the query above tells mysql that it can stop searching after it finds 1 result - and you should have an index on that column (preferably a primary index or unique index) to keep it lightening fast (or at least in the beginning anyway >< ).