CodeIgniter function not taking parameters - php

I defined this function
function login_user($emailusername, $password) { }
the function uses the variables but, when I try to call it using
$this->login->login_user('username', 'password');
it returns an error saying that those variables are undefined in the function.
EDIT: I set the function in a login model
I get these errors:
A PHP Error was encountered
Severity: Notice
Message: Undefined index: password
Filename: models/login.php
Line Number: 20
line 20: $pass = crypt($password, $hash['password']);
A PHP Error was encountered
Severity: Notice
Message: Undefined index: username
Filename: models/login.php
Line Number: 26
line 26: if ($user_data['username'] == $emailusername || $user_data['email'] == $emailusername) {
A PHP Error was encountered
Severity: Notice
Message: Undefined index: email
Filename: models/login.php
Line Number: 26
line 26: if ($user_data['username'] == $emailusername || $user_data['email'] == $emailusername) {
This is the function
function login_user($emailusername, $password) {
//To initiate session set this cookie
$query = $this->db->query("SELECT password FROM usrs WHERE username = '$emailusername' or email = '$emailusername'");
$hash = $query->result();
$pass = crypt($password, $hash['password']);
$nq = $this->db->query("SELECT usr_id, username, email from usrs WHERE email = '$emailusername' or username = '$emailusername' and password = '$pass'");
$user_data = $nq->result();
if($emailusername&&$password) {
if ($user_data['username'] == $emailusername || $user_data['email'] == $emailusername) {
if($hash['password'] == $pass) {
$_SESSION['login'] = True;
$_SESSION['uid'] = $user_data['usr_id'];
$_SESSION['username'] = $user_data['username'];
return True;
} else
return False;
} else
return False;
} else
return False;
}

This error is not in your variables.
There is no index calldes 'password' in your $hash table;
Check Your $hash table first.
$hash = $query->result();
function return object array consist
$hash->password = '';
If want to get single row and result is to be array use row_array() function
$hash = $query->row_array();
this returns
$hash['password']

The issue originates from this line:
$hash = $query->result();
As per the documentation, result() does the following:
This function returns the query result as an array of objects, or an empty array on failure. Typically you'll use this in a foreach loop...
So, $hash contains no indices named password, username, or email - hence the error messages you're receiving.
If you're only concerned with the first row returned from that query (which is my assumption), you can use row_array() to return only the first record and as an array, which will make those indices available, like this:
$hash = $query->row_array();
// $hash['password'], $hash['username'], and $hash['email'] are now available

Considering that you are using codeignitor, if the function is in a controller 'Login' then use
$this->login_user('username', 'password');
If the function is in a library, then make sure that you have loaded the library and the name of the instance is 'login'
And if you have included the file directly then just make an object and call the method
$loginObj = new login();
$loginObj->login_user('username', 'password');
Cheers,
Vedant

Related

Notice: Undefined variable: login

i have this code
<?php
$host = "localhost";
$user = "root";
$pass = "";
$dabname = "tutorial";
$login = mysqli_connect($host, $user, $pass, $dabname) or die('Could not connect to mysql server.');
mysqli_select_db($login, $dabname) or die('Could not select database.');
$nama_karyawan = $_POST['nama_karyawan'];
$umur_karyawan = $_POST['umur_karyawan'];
function proses_hoby($id_karyawan) {
if (isset($_POST["rincian_hoby"])) {
$hoby = $_POST["rincian_hoby"];
reset($hoby);
while (list($key, $value) = each($hoby)) {
$rincian_hoby = $_POST["rincian_hoby"][$key];
$jenis_hoby = $_POST["jenis_hoby"][$key];
$sql_hoby = "INSERT INTO tbl_hoby(rincian_hoby,jenis_hoby,id_karyawan)
VALUES('$rincian_hoby','$jenis_hoby','$id_karyawan')";
$hasil_hoby = mysqli_query($login, $sql_hoby);
}
}
}
$sql = "INSERT INTO tbl_karyawan(nama_karyawan,umur_karyawan)
VALUES('$nama_karyawan','$umur_karyawan')";
$hasil = mysqli_query($login, $sql);
$id_karyawan = mysqli_insert_id($login);
if ($hasil) {
proses_hoby($id_karyawan);
echo "Data berhasil diinput";
} else {
echo "Data Gagal diinput";
}
?>
But i do get this error
Notice: Undefined variable: login in C:\xampp\htdocs\2\proses.php on
line 23
Warning: mysqli_query() expects parameter 1 to be mysqli, null given
in C:\xampp\htdocs\2\proses.php on line 23
Notice: Undefined variable: login in C:\xampp\htdocs\2\proses.php on
line 23
Warning: mysqli_query() expects parameter 1 to be mysqli, null given
in C:\xampp\htdocs\2\proses.php on line 23
Data berhasil diinput
I know there are lot of similiar Thread name but i dont found that match my problem
Here is the source code https://drive.google.com/file/d/16FNr5SJeO_53_-XUJo7RIV1rLqgZwagV/view?usp=sharing
please help
any help would be very appreciated
thank you
You should learn about variable scopes inside php. $login is declared outside the function proses_hoby so proses_hoby can't access this var. To access $login inside the function, you need to make it global (the unclean way..) or pass $login as an function parameter.
Modern approaches would be to move the whole thing inside a class and make $login a class var. So every member of the class could access the var.
Btw. your code is prone to sql injections. You should use prepared statements.

Variable $connection is undefined. Impossible, what is happening there?

Objective: I am in the process of creating a php login script.
Problem: I can't seem to be able to make my includes recognize the $connection variable even though it should be clearly defined in connection.php. As a result the value of my variable is nothing / NULL.
What I tried: I started with mysql but quickly noticed that it was the wrong approach and converted my code to mysqli. I checked for typos in all the $connection variables I have. I made sure the paths are correct. As a last resort I did a Google search but didn't find an answer or any useful hint to my scenario.
Problem: What is the reason for my variable not being defined?
Error Messages:
All those messages are related to this single variable no being defined for some reason:
Php Notice: Undefined variable: connection in C:\xampp\htdocs\aspie\Php\Core\Common.php on line 4
Php Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, null given in C:\xampp\htdocs\aspie\Php\Core\Common.php on line 4
Php Notice: Undefined variable: connection in C:\xampp\htdocs\aspie\Php\Core\Functions\Members.php on line 4
Php Warning: mysqli_query() expects parameter 1 to be mysqli, null given in C:\xampp\htdocs\aspie\Php\Core\Functions\Members.php on line 4
Php Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, null given in C:\xampp\htdocs\aspie\Php\Core\Functions\Members.php on line 5
// INITIALIZER
<?php
session_start();
// error_reporting(NULL);
include 'Connection.php';
include 'Common.php';
include 'Functions/Members.php';
?>
**// ERROR MESSAGES **
<?php
$connection_error = 'Our website is experiencing technical issues, please come back later.';
$wrong_login = 'Password and name are wrong.';
$member_registered = 'Access has been denied. You do not seem to be a registered user.';
?>
**// CONNECTION **
<?php
include 'Errors.php';
$connection = mysqli_connect('localhost', 'root', '', 'project') or exit ($connection_error);
?>
**// COMMON **
<?php
error_reporting();
function sanitize($connection, $data) {
global $connection;
global $data;
return mysqli_real_escape_string($connection, $data);
}
?>
**// MEMBERS **
<?php
function member_registered($connection, $name) {
$name = sanitize($connection, $name);
$query = mysqli_query($connection, "SELECT COUNT(`id`) FROM `members` WHERE `name` = '$name'");
return (mysqli_num_rows($query) == 1) ? true : false;
}
?>
**// LOGIN **
<?php
include 'Php/Core/Initializer.php';
if (member_registered($connection, 'ee')) {
echo "exists";
}
die("eee");
echo error_reporting();
if (empty($_POST) == false) {
$name = $_POST['name'];
$password = $_POST['name'];
if (empty($name) OR empty($password)) {
echo $wrong_login;
}
else if (member_registered($connection, $name) == false) {
echo $member_registered;
}
}
?>
UPDATE:
Now what I get: existseee;
The conditional doesnt work now even though its all set up right. Username doesnt exist so it should'nt echo "exists:
if (member_registered($connection, 'ee')) {
echo "exists";
}
die("eee");
In your case, the $connection variable inside your sanitize function isn't reachable.
Try to pass the $connection variable into your function, like this:
function sanitize($data, $connection) {
return mysqli_real_escape_string($connection, $data);
}
Read more about it here: http://php.net/manual/en/language.variables.scope.php
UPDATE
In **// MEMBERS ** you need to include the new parameter as well:
function member_registered($name, $connection) {
$name = sanitize($name, $connection);
$query = mysqli_query($connection, "SELECT COUNT(`id`) FROM `members` WHERE `name` = '$name'");
return (mysqli_num_rows($query) == 1) ? true : false;
}
and because of that your **// LOGIN ** should be updated as well:
include 'Php/Core/Initializer.php';
if (member_registered('ee', $connection)) {
echo "exists";
}
die("eee");
echo error_reporting();
if (empty($_POST) == false) {
$name = $_POST['name'];
$password = $_POST['name'];
if (empty($name) OR empty($password)) {
echo $wrong_login;
}
else if (member_registered($name, $connection) == false) {
echo $member_registered;
}
}
And make sure that the $connection variable is reachable everywhere where you need it.
UPDATE #2
Answer to your update:
it should be like this:
if (member_registered('ee', $connection)) {
echo "exists";
}
and not like this:
if (member_registered($connection, 'ee')) {
echo "exists";
}
the $connection is the second parameter.

PHP Error, Undefined index error

In my codeigniter project I have this function in my model
function get_rtc_info($id)
{
$query = $this->db->get_where('rtc_info', array('id' => $id));
$query = $query->row_array();
$query = $query['id'].', '.$query['name'].', '.$query['address']; //line# 313
return $query;
}
I get the following error/warning when running the code
A PHP Error was encountered
Severity: Notice
Message: Undefined index: id , name and address
Filename: models/form_model.php
line number 313
I am not sure why I get this undefined index warnings. Can someone guide me on this error and how to resolve it. Thank you in advance
There are no rows in your table rtc_info. This is why you are watching this kind of notice. If you want, not show this notice check your variable with isset() before using
function get_rtc_info($id)
{
$query = $this->db->get_where('rtc_info',array('id' => $id));
$query = $query->row_array();
if(isset($query['id']) && isset($query['name']) && isset($query['address'])) {
$query = $query['id'].', '.$query['name'].', '.$query['address']; //line# 313
return $query;
}else{
return 'no data';
}
}
if these 3 fields are optional you may use following without else block
function get_rtc_info($id)
{
$query = $this->db->get_where('rtc_info',array('id' => $id));
$query = $query->row_array();
if(isset($query['id'])){
$row_id = $query['id'];
}else{
$row_id = 'no id';
}
if(isset($query['name'])){
$name = $query['name'];
}else{
$name = 'no name';
}
if(isset($query['address'])){
$address= $query['address'];
}else{
$address = 'no address';
}
$query = $row_id.', '.$name.', '.$address; //line# 313
return $query;
}
hope now clear

Using both MySQL procedure and session db in code igniter cause `2014` error

I have a controller like this:
$r_result = $this->storedprocedure->user_email_exist($in_email);
if($r_result->num_rows() == 1)
{
foreach ($r_result->result() as $row)
{
$salt = $row->salt;
$hash = $row->hash_password;
if(strcasecmp(Application_Helper::hash_password($aData['password'], $salt),
$hash)==0)
{
//Login success
echo('login success');
$newdata = array('user_id' => $row->id);
$this->session->set_userdata($newdata);
}
}
}
In the Storedprocedure model, is something like this:
public function user_email_exist($aEmail)
{
$r_result = $this->db->query("CALL user_email_exist('".$aEmail."')");
return $r_result;
}
I tested it, it can login success, but print an error:
A Database Error Occurred
Error Number: 2014
Commands out of sync; you can't run this command now
UPDATE ci_sessions SET last_activity = 1358764263, user_data =
'a:2:{s:9:\"user_data\";s:0:\"\";s:7:\"user_id\";s:2:\"35\";}' WHERE
session_id = '05e340b2aa6bd9b21261ed0d20354b3c'
Filename: libraries/Session.php
Line Number: 289
The problem is, I must use the MySQL procedure to implement the model layer, but it seems that have some conflict between the ci_session. Any recommend solutions for that issue? Thanks.
This error is caused due to the fact that mySQL Stored Procedures return MULTI RESULTS
even if there is only one select statement in them . Solution is to simply call $r_result->next_result() to loose the expected extraneous resultset.
I got the idea from this link.
please Replace the controller code like below:
$r_result = $this->storedprocedure->user_email_exist($in_email);
if($r_result->num_rows() == 1)
{
$row = $r_result->row_array();
$r_result->next_result(); // Dump the extra resultset.
$r_result->free_result(); // Does what it says.
$salt = $row->salt;
$hash = $row->hash_password;
if(
strcasecmp(Application_Helper::hash_password($aData['password'], $salt),$hash)==0
) {
//Login success
echo('login success');
$newdata = array('user_id' => $row->id);
$this->session->set_userdata($newdata);
}
}

Warning: mysql_result(): supplied argument is not a valid MySQL result resource in (...) on line 4

Here is my snippet.
I've checked some other questions similar to my error, but so far I can't get it solved.
<?php
function user_exists ($username) {
$username = sanitize($username);
return (mysql_result(mysql_query("SELECT COUNT(user_id) FROM users WHERE username = $username"), 0) == 1) ? true : false;
}
?>
You should split your code in some more lines to handle those errors or special cases. mysql_query will return zero to n rows or an error if it occurs. The returned resource will therefore only be true on non-error queries. This can be used to handle such situations like follows.
At first build and execute query, next process the resource.
$query="SELECT COUNT(user_id) FROM users WHERE username = ".$username;
$result = mysql_query($query);
u may use the following to determine what is going on in case of an error:
if(!$result) die("SELECT failed: ".mysql_error());
or these idea to handle the problem
if (!$result=mysql_query($query)) {
return false; // or similar operation
}
if (mysql_num_rows($result)!=1){
return false;
}else{
return true;
}
This could happen, when mysql_query returns false, if it fails for some reason. So you should split this into multiple statements and check the return values
$sql = "SELECT COUNT(user_id) FROM users WHERE username = $username";
$result = mysql_query($sql);
if ($result === false) {
// error handling
return false;
}
return (mysql_result($result, 0) == 1) ? true : false;

Categories