How do i return an error statement if the query is empty? - prepared-statement

I would like echo something if the query is empty.
session_start();
include 'inc/db.php';
$student_id = $_POST['username'];
$password = $_POST['password'];
if($stmt = $conn->prepare("SELECT p.parent_id, ps.student_id, p.password
FROM parent p,
parentstudent ps
WHERE p.parent_id = ps.parent_id
AND student_id = ? limit 1")) {
$stmt->bind_param("s", $student_id);
$stmt->execute();
$stmt->bind_result($id, $student_id, $bindpassword);
while ($stmt->fetch()) {
if(password_verify($password, $bindpassword)){
$_SESSION['parent_id']= $id;
$_SESSION['student_id'] = $student_id;
header("location: parent.php");
}
else
echo "The student ID or password you have entered is inccorrect";
}
}
$stmt->close();

since you got only one row to retrieve from the database you could just replace the while with an if (i've deleted my previous response)
session_start();
include 'inc/db.php';
$student_id = $_POST['username'];
$password = $_POST['password'];
$stmt = $conn->prepare("SELECT p.parent_id, ps.student_id, p.password
FROM parent p,
parentstudent ps
WHERE p.parent_id = ps.parent_id
AND student_id = ? limit 1") ;
$stmt->bind_param("i", $student_id);
$stmt->bind_result($id, $student_id, $bindpassword);
$stmt->execute();
if($stmt->fetch()) {
if(password_verify($password, $bindpassword)){
$_SESSION['parent_id']= $id;
$_SESSION['student_id'] = $student_id;
header("location: parent.php");
}
else {
echo "The student ID or password you have entered is inccorrect";
}
}
else {
echo "nothing was fetch";
}
$stmt->close();
I've put two else, one if the password is incorrect, and one if there was no fetchs in the database

Related

Cant fix my if-else condition in login.php

I have created a condition to check if name and password are correct the only issue here is when i test it it goes complete the opposite of what i want. It doesnt matter if i put it right or wrong the message will always be "You have successfuly logged in". Im using PDO just to know
<?php
include('connection.php');
$name = $_POST['name'];
$password = $_POST['password'];
$data = $_POST;
$statment = $connection->prepare('SELECT * FROM registration WHERE name = :name AND password = :password');
if($statment){
$result = $statment->execute([
':name' => $data['name'],
':password' => $data['password']
]);
}
if($data['name'] == $name && $data['password'] == $password){
echo 'You have successfuly logged in';
}else {
die('Incorrect username or password');
}
?>
You have made your script overly complicated .. The easiest way is to bind and execute .. Then you can simply check if there are any rows, and THEN compare with your data array created from the executed statement.
<?php
include('connection.php');
$name = $_POST['name'];
$password = $_POST['password'];
$statment = $connection->prepare("SELECT name, password FROM registration
WHERE name = ? AND password = ?");
$statment ->bind_param("ss", $name, $password);
$statment ->execute();
$result = $stmt->get_result();
if ($result ->num_rows > 0) {
$data = $result->fetch_array();
}else{
echo "No results found";
}
if($data['name'] == $name && $data['password'] == $password){
echo 'You have successfuly logged in';
}else {
die('Incorrect username or password');
}
?>
(bear in mind I wrote that freehand, and it has not been tested or debugged, but the principals are there)
ON A SIDE NOTE
That being said .. You should never be storing passwords in a open "text" field. You should be encrypting them. The easiest way is to use bcrypt to build out a hash:
$options = [
'cost' => 12,
];
$newPass = password_hash($pass, PASSWORD_BCRYPT, $options);
And store that in your database .. Then you can compare it like so ..
if (password_verify($pss, $pwdCheck)
$pss being what was sent in from the form .. and $pwdCheck being the hash you SELECTED from the database -- Brought into your current code set, would look something like:
if($data['name'] == $name && password_verify($password, $data['password']){

row() return null for specific field

Im trying to save specific field from a record into a session, for my user-role. The problem here is i cannot take any other field except nama.
controller/verify_login
public function index(){
$this->load->model('verify_login_model');
$username = $this->input->post('username');
$password = $this->input->post('password');
$result = $this->verify_login_model->verify($username, $password);
if($result == $username) {
$name = $this->verify_login_model->getinfo($username);
$this->session->set_userdata('logged_in', TRUE);
$this->session->set_userdata('username', $username);
$this->session->set_userdata('name', $name);
$this->load->view('home_view');
} else {
redirect('login');
}
model/verify_login_model
function verify($username, $password){
$this->db->select('username', 'password');
$this->db->from('tb_user');
$this->db->where('username', $username);
$this->db->where('password', MD5($password));
$this->db->limit(1);
$query = $this->db->get();
if($query->num_rows()==1) {
return $username;
} else {
return false;
}
}
function getinfo($username) {
$this->db->select('nama', 'username');
$this->db->from('tb_userInfo');
$this->db->where('username', $username);
$this->db->limit(1);
$query = $this->db->get();
if($query->num_rows()==1) {
$result = $query->row();
return $result->nama;
} else {
return false;
}
}
view
<?php echo $this->session->userdata['name']?>
the var_dump($result) : object(stdClass)#22 (1) { ["nama"]=> string(4) "test" }
if i change the return $result->nama; to $result->username; i get error : Undefined property: stdClass::$username even tho im sure 200% there's username field in the table, and tried the query directly.
There's an error in your select statement, it must be
$this->db->select('nama,username');
You are separating each column, and that's not correct, all of the columns go in one string, that's why it tells you its undefined since the only column you are sending is nama and you're sending username as the second parameter for the select.
Here's a link on active record for CodeIgniter 2.2.0

How can get user id from database to arrowchat intergration

In my php i have this code, to see if the user is logged in
$auth=new auth();
$username = $auth->loggedIn();
global $crt_usr;
if(!$username) { header("Location: ".$config_live_site."/login.php?loc=account_info.php"); exit(0); }
$smarty->assign("username",$username);
$usr = new users();
$user = $usr->getUser($crt_usr);
$smarty->assign("user",$user);
And i have and this intergraton for the arrowchat
function get_user_id()
{
$userid = NULL;
if (isset($_COOKIE['userid']))
{
$userid = $_COOKIE['userid'];
}
return $userid;
}
My user id field name in my database is "id"
you can set a session that have your user id and put it to the get_user_id() function
if (isset($_SESSION['userid']))
{
$userid = $_SESSION['userid'];
}

Which of Database::<QUERY_TYPE> I should use in Kohana 3.3?

I need perform query "LOCK TABLE myTable WRITE"
<?php
$db = Database::instance();
$query = 'LOCK TABLE `myTable` WRITE';
$db->query(Database::WHAT_IS_THE_TYPE_SHOULD_SPECIFY_HERE_?, $query);
In framework Kohana 3.3
file ~/modules/database/classes/Kohana/Database.php
implements folowing types:
const SELECT = 1;
const INSERT = 2;
const UPDATE = 3;
const DELETE = 4;
but none of them fit in my case.
Any idea. Thanks.
Google works wonders. http://forum.kohanaframework.org/discussion/6401/lockunlock/p1
You can pass NULL as the first argument:
$db = Database::instance();
$query = 'LOCK TABLE `myTable` WRITE';
$db->query(NULL, $query);
From Kohana: http://kohanaframework.org/3.3/guide-api/Database_MySQL#query
if ($type === Database::SELECT)
{
// Return an iterator of results
return new Database_MySQL_Result($result, $sql, $as_object, $params);
}
elseif ($type === Database::INSERT)
{
// Return a list of insert id and rows created
return array(
mysql_insert_id($this->_connection),
mysql_affected_rows($this->_connection),
);
}
else
{
// Return the number of rows affected
return mysql_affected_rows($this->_connection);
}
As you can see that's why you're able to pass NULL.

JRequest::getVar is keeping previous values even after refreshing

I am writing a mail function as a module in joomla 3. e mail works fine, but when i reload the page and insert a different email and send, but it seemed to return the previous email by JRequest::getVar function. Is there a way to solve this issue? thanks in advance..
this is the code i used:
<?php
defined('_JEXEC') or die('Direct Access to this location is not allowed.');
require_once(dirname(__FILE__) . DS . 'helper.php');
//declaration
$input = JFactory::getApplication()->input;
$form_send = $input->get('form_send', 'notsend');
$fanme = $input->get('firstName');
$lname = $input->get('lastinput');
$email = $input->get('email', 0 , 'STRING');
$mail=false;
$emailexist=false;
echo '<script>
var php_var = "chk is first:'.$email.'";
alert(php_var);
</script>';
switch ($form_send) {
case 'send':
if ((is_null($fanme) || is_null($lname) || is_null($email)) || (!filter_var($email, FILTER_VALIDATE_EMAIL))) {
echo '<div> Fields are empty or not valid. <br></div>';
} else {
$mail = ModLittleContactHelper::SendMail($email, $fanme, $lname);
echo '<script>
var php_var = "chk when mail sending:'.$email.'";
alert(php_var);
</script>';
$input = JFactory::getApplication();//i have tried $app also
$input ->setUserState('mod_mycontact.email', null);
}
//echo $respond
if (!$mail) {
echo 'Error sending email:';
require(JModuleHelper::getLayoutPath('mod_myecontact', 'default_tmpl'));
}else{
require(JModuleHelper::getLayoutPath('mod_mycontact', 'sendok_tmpl'));
break;
}
default:
require(JModuleHelper::getLayoutPath('mod_littlecontact', 'default_tmpl'));
unset($var);
}
?>
#Mario this is the helper code:
class ModLittleContactHelper{
public function SendMail($email, $fname, $lname) {
$body = "<p style='font-family:arial;font-size:20px;'>Hi " . $fname . " " . $lname . ",</p>";
$body.="<p style='font-family:arial;font-size:20px;'>Welcome to Crowd Logistics! Please verify your email address below.</p><br/><br/>";
$body.= "<hr><br/>";
$body.= "<p style='align:center;background-color:#40B3DF;font-family:arial;color:#FFFFFF;font-size:20px;'><a href='http://suriyaarachchi.com/crowdlogistics/index.php?option=com_content&view=article&id=192' target='_blank'>Verify " . $email . "</a></p>";
$body.= "<br/><hr><br/>";
$body.="<p style='text-align:right;font-family:arial;font-size:20px;'>Or, paste this link into your browser:<br/>";
$body.= "http://crowdlogistics/index.php?option=com_content&view=article&id=192<br/><br/>";
$body.= "Thanks.<br/>";
$body.= "CrowdLogistics</p><br/>";
$mailer = & JFactory::getMailer();
$mailer->setSender('info#crowdlogistics.com');
$mailer->addRecipient($email);
$mailer->setSubject('Mail from CrowdLogistics - Confirm your email');
$mailer->setBody($body);
$mailer->IsHTML(true);
$send = & $mailer->Send();
return $send;
}
Since you're trying to run your code on Joomla 3, there are a few things that are wrong. Below os your code, corrected where I was able to correct it. Now you have to test it in your module environment with the class being instantiated (in other words, test the below code in your module).
<?php
defined('_JEXEC') or die('Direct Access to this location is not allowed.');
require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'helper.php');
//declaration
$doc = JFactory::getDocument();
$app = JFactory::getApplication();
$input = $app->input;
$form_send = $input->get('form_send', 'notsend');
$fanme = $input->get('firstName');
$lname = $input->get('lastinput');
$email = $input->get('email', 0 , 'STRING');
$mail=false;
$emailexist=false;
$doc->addScriptDeclaration('
var php_var = "chk is first:'.$email.'";
alert(php_var);
');
switch ($form_send) {
case 'send':
if ((is_null($fanme) || is_null($lname) || is_null($email)) || (!filter_var($email, FILTER_VALIDATE_EMAIL))) {
echo '<div> Fields are empty or not valid. <br></div>';
} else {
$mail = ModLittleContactHelper::SendMail($email, $fanme, $lname);
$doc->addScriptDeclaration('
var php_var = "chk when mail sending:'.$email.'";
alert(php_var);');
$app->setUserState('mod_littlecontact.email', null);
}
//echo $respond
if (!$mail) {
echo 'Error sending email:';
require(JModuleHelper::getLayoutPath('mod_littlecontact', 'default_tmpl'));
break;
}else{
require(JModuleHelper::getLayoutPath('mod_littlecontact', 'sendok_tmpl'));
break;
}
default:
require(JModuleHelper::getLayoutPath('mod_littlecontact', 'default_tmpl'));
unset($var);
}
?>
First, JRequest class is deprecated in J3. You should use JInput:
$input = JFactory::getApplication()->input;
$your_var = $input->get('your_var');
Then, regarding the email, you probably need to unset the session variables when the success is achieved (mail sent), or in other words, when you don't need them any longer.
$app = JFactory::getApplication();
// your_var is the variable you want to unset
$app->setUserState('mod_your_module.your_var', null);
Hope it helps
you can use this code
$email = $input->get('email', 0 , 'STRING','');
4th argument for the default value,

Resources