Query not executed as expected - php

I am working on a User's registration system. This is the URL called to activate a user's account:
http://../verify.php?id=40&code=fdc6604289e5a58fe1ab9dffa8e2f870
And this is the code for verify.php:
<?php
require_once 'class.user.php';
$user = new USER();
if(empty($_GET['id']) && empty($_GET['code']))
{
$user->redirect('index.php');
}
if(isset($_GET['id']) && isset($_GET['code']))
{
$id = $_GET['id'];
$code = $_GET['code'];
$statusY = "Y";
$statusN = "N";
$stmt = $user->runQuery("SELECT userID,userStatus FROM tbl_users WHERE userID=:uID AND tokenCode=:code LIMIT 1");
$stmt->execute(array(":uID"=>$id,":code"=>$code));
$row=$stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() > 0)
{
if($row['userStatus']==$statusN)
{
$stmt = $user->runQuery("UPDATE tbl_users SET userStatus=:status WHERE userID=:uID");
$stmt->bindparam(":status",$statusY);
$stmt->bindparam(":uID",$id);
$stmt->execute();
$msg = "
<div class='alert alert-success'>
<button class='close' data-dismiss='alert'>×</button>
<strong>WoW !</strong> Your Account is Now Activated : <a href='index.php'>Login here</a>
</div>
";
}
else
{
$msg = "
<div class='alert alert-error'>
<button class='close' data-dismiss='alert'>×</button>
<strong>sorry !</strong> Your Account is allready Activated : <a href='index.php'>Login here</a>
</div>
";
}
}
else
{
$msg = "
<div class='alert alert-error'>
<button class='close' data-dismiss='alert'>×</button>
<strong>sorry !</strong> No Account Found : <a href='signup.php'>Signup here</a>
</div>
";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Confirm Registration</title>
<!-- Bootstrap -->
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen">
<link href="bootstrap/css/bootstrap-responsive.min.css" rel="stylesheet" media="screen">
<link href="assets/styles.css" rel="stylesheet" media="screen">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<script src="js/vendor/modernizr-2.6.2-respond-1.1.0.min.js"></script>
</head>
<body id="login">
<div class="container">
<?php if(isset($msg)) { echo $msg; }
?>
</div> <!-- /container -->
<script src="vendors/jquery-1.9.1.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>
</body>
</html>
This is the record from the database:
The problem is that $_GET['id'] and $_GET['code'] are the correct values, but the page shows the option: NO ACCOUNT FOUND...
I am searching for the reason for hours, but no success.
Any help to find the source of the issue is welcome

Related

Using php session to display two different html pages based on logged in status

I have created a login system with php, mysql, and html. I am trying to figure out how to display a different home page with html code based on whether someone is logged in or not.
I have tried to display profile button on the header if they are logged in and if they are not logged in it displays Login/Signup on the header.
index.php
<?php session_start();
include('server.php');
if (isset($_SESSION['username'])){
?>
<!DOCTYPE html>
<html lang = "en">
<!--
Capstone Project "Zoeker"
Michael Burnett, Annie Lalor, Sophia Michael, Hannah Smith
5/6/2021
-->
<head>
<title>Home Page</title>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Stylesheets -->
<link rel="stylesheet" href="CSS/Normalize.css?v=<?php echo time(); ?>">
<link rel="stylesheet" href="CSS/Styles.css?v=<?php echo time(); ?>">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<script>
function myFunction() {
var x = document.getElementById("myTopnav");
if (x.className === "topnav") {
x.className += " responsive";
} else {
x.className = "topnav";
}
}
</script>
<!-- Menu Bar -->
<div class="topnav" id="myTopnav">
<img src="Images/Logo.png" alt="Zoeker">
About
Contact
Stores Near You
Profile
<a href="javascript:void(0);" class="icon" onclick="myFunction()">
<i class="fa fa-bars"></i>
</a>
</div>
<!-- Strip container for opening home page -->
<div class = "strip1">
</div>
<!-- FOOTER Containers-->
<div class="footer">
<div class="footer-box">
<ul>
<li><img src="Images/Logo.png" alt="Zoeker"></li>
</ul>
</div>
<div class="footer-box">
<h2>Navigation</h2>
<ul>
<li>Stores</li>
<li>About Us</li>
<li>Contact</li>
</ul>
</div>
<div class="footer-box">
<h2>Service Areas</h2>
<ul>
<li>Bloomington</li>
</ul>
</div>
<div class="footer-box">
<h2>Contact Us</h2>
<ul>
<li>812-123-4567</li>
<li>Support#Zoeker.com</li>
</ul>
</div>
</div>
</body>
</html>
<?php
}else{
// not logged in
}
?>
<!DOCTYPE html>
<html lang = "en">
<!--
Capstone Project "Zoeker"
Michael Burnett, Annie Lalor, Sophia Michael, Hannah Smith
5/6/2021
-->
<head>
<title>Home Page</title>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Stylesheets -->
<link rel="stylesheet" href="CSS/Normalize.css?v=<?php echo time(); ?>">
<link rel="stylesheet" href="CSS/Styles.css?v=<?php echo time(); ?>">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<script>
function myFunction() {
var x = document.getElementById("myTopnav");
if (x.className === "topnav") {
x.className += " responsive";
} else {
x.className = "topnav";
}
}
</script>
<!-- Menu Bar -->
<div class="topnav" id="myTopnav">
<img src="Images/Logo.png" alt="Zoeker">
About
Contact
Stores Near You
Login/Signup
<a href="javascript:void(0);" class="icon" onclick="myFunction()">
<i class="fa fa-bars"></i>
</a>
</div>
<!-- Strip container for opening home page -->
<div class = "strip1">
</div>
<!-- FOOTER Containers-->
<div class="footer">
<div class="footer-box">
<ul>
<li><img src="Images/Logo.png" alt="Zoeker"></li>
</ul>
</div>
<div class="footer-box">
<h2>Navigation</h2>
<ul>
<li>Stores</li>
<li>About Us</li>
<li>Contact</li>
</ul>
</div>
<div class="footer-box">
<h2>Service Areas</h2>
<ul>
<li>Bloomington</li>
</ul>
</div>
<div class="footer-box">
<h2>Contact Us</h2>
<ul>
<li>812-123-4567</li>
<li>Support#Zoeker.com</li>
</ul>
</div>
</div>
</body>
</html>
server.php
<?php
session_start();
$username = "";
$email = "";
$errors = array();
//Connect to the database
$conn = mysqli_connect("db.luddy.indiana.edu", "i494f20_team36", "my+sql=i494f20_team36", "i494f20_team36");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: ";
}
//if the register button is clicked
if (isset($_POST['register'])){
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
//Check database for username and email already in use
$sql_u = "SELECT * FROM users WHERE username='$username'";
$sql_e = "SELECT * FROM users WHERE email='$email'";
$res_u = mysqli_query($conn, $sql_u);
$res_e = mysqli_query($conn, $sql_e);
//ensure form fields are filled in
if(empty($username)){
array_push($errors, "Username is required");
}
if(empty($email)){
array_push($errors, "Email is required");
}
if(empty($password)){
array_push($errors, "Password is required");
}
if(mysqli_num_rows($res_u) > 0) {
array_push($errors, "Username is already taken");
}
if(mysqli_num_rows($res_e) > 0) {
array_push($errors, "Email is already taken");
}
//if no errors, insert new user into database
if (count($errors) == 0){
$sql = "INSERT INTO users(username, email, password)
VALUES ('$username', '$email', '$password')";
mysqli_query($conn, $sql);
$_SESSION['username'] = $username;
$_SESSION['success'] = "You are now logged in";
header('location: index.php'); //redirect to home page
}
else{
echo "not quite, but you'll get it";
}
}
// log user in from login page
if (isset($_POST['login'])){
$username = $_POST['username'];
$password = $_POST['password'];
if(empty($username)){
array_push($errors, "Username is required");
}
if (empty($password)){
array_push($errors, "Password is required");
}
if (count($errors) == 0){
$sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) == 1){
// log user in
$_SESSION['username'] = $username;
$_SESSION['success'] = "You are now logged in";
header('location: index.php'); //redirect to home page
}else{
array_push($errors, "Wrong username/password combination");
}
}
}
?>
The else was empty and the html version for users that are not logged in was always shown. By moving the closing else-bracket to the end of the file, you get the 2 versions depending on the user being logged in or not.
<?php
}else{
// not logged in
// THE CLOSING BRACKET IS NOW AT THE BOTTOM
?>
<!DOCTYPE html>
<html lang = "en">
<!-- LINES DELETED FOR BREVITY ->
</body>
</html>
<?php } // MOVED CLOSING BRACKET TO THE END

Change a html (text) to php (Users name)

On my index page what I'm trying to achieve is after login a dropdown button on the top right of my page to change from "Account" to "Welcome [User]" and the buttons inside to change from "Login" to "View Account" & "Log out"
I have the PHP code that says "Welcome [User]" but I'm not too sure on how to switch them out.
<?php
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
<head>
<title>Bootstrap Case</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<meta name="description" content="">
<meta name="author" content="">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="icon" href="../../favicon.ico">
<!-- Bootstrap core CSS -->
<link href="../../dist/css/bootstrap.min.css" rel="stylesheet">
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<link href="../../assets/css/ie10-viewport-bug-workaround.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<title>Carousel Template for Bootstrap</title>
<!-- Just for debugging purposes. Don't actually copy these 2 lines! -->
<!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]-->
<script src="../../assets/js/ie-emulation-modes-warning.js"></script>
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<!-- Custom styles for this template -->
<link href="carousel.css" rel="stylesheet">
</head>
<!-- NAVBAR ================================================== -->
<body style="height:1500px">
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">Jobsite</a>
</div>
<div>
<ul class="nav navbar-nav" style="display: inline-block;">
<li class="active">Home</li>
<li>Who are we?</li>
<li>Make a resume</li>
<li>Search for jobs</li>
<li>Profile</li>
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#"><b>
<!-- logged in user information -->
<?php if (isset($_SESSION['username'] )): ?>
<p>Welcome <strong><?php echo $_SESSION['username']; ?></strong></p>
<p>
<ul class="dropdown-menu">
logout </p>
<li>Login</li>
...
<?php endif ?>
...
...
</div>
</b>
//-----------------
// Etc...
//-------------------
I've seen(and attempted with no luck) str_replace(). I'm not sure how the best way to do this is.
Server.php
<?php
session_start();
// variable declaration
$username = "";
$email = "";
$errors = array();
$_SESSION['success'] = "";
// connect to database
$db = mysqli_connect('localhost', 'root', '', 'registration');
// REGISTER USER
if (isset($_POST['reg_user'])) {
// receive all input values from the form
$username = mysqli_real_escape_string($db, $_POST['username']);
$email = mysqli_real_escape_string($db, $_POST['email']);
$password_1 = mysqli_real_escape_string($db, $_POST['password_1']);
$password_2 = mysqli_real_escape_string($db, $_POST['password_2']);
// form validation: ensure that the form is correctly filled
if (empty($username)) { array_push($errors, "Username is required"); }
if (empty($email)) { array_push($errors, "Email is required"); }
if (empty($password_1)) { array_push($errors, "Password is required"); }
if ($password_1 != $password_2) {
array_push($errors, "The two passwords do not match");
}
// register user if there are no errors in the form
if (count($errors) == 0) {
$password = md5($password_1);//encrypt the password before saving in the database
$query = "INSERT INTO users (username, email, password)
VALUES('$username', '$email', '$password')";
mysqli_query($db, $query);
$_SESSION['username'] = $username;
$_SESSION['success'] = "You are now logged in";
header('location: index.php');
}
}
// ...
// LOGIN USER
if (isset($_POST['login_user'])) {
$username = mysqli_real_escape_string($db, $_POST['username']);
$password = mysqli_real_escape_string($db, $_POST['password']);
if (empty($username)) {
array_push($errors, "Username is required");
}
if (empty($password)) {
array_push($errors, "Password is required");
}
if (count($errors) == 0) {
$password = md5($password);
$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) {
$_SESSION['username'] = $username;
$_SESSION['success'] = "You are now logged in";
header('location: index.php');
}else {
array_push($errors, "Wrong username/password combination");
}
}
}
?>
You can change the whole dropdown content using php, so it shows what you want on each case. Something like this (adapt the content of each option to your case)...
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#"><b>
<?php if (isset($_SESSION['username'] )) { ?>
<p>Welcome <strong><?=$_SESSION['username']?></strong></p>
<p>logout</p>
<p>logout</p>
<?php } else { ?>
<p>Login</p>
<?php } ?>
You'll have to tweak it a little bit to use the html element distribution you prefer, but I hope you understand the idea. Just create all the dropdown content for each case.
I hope it helps
Ok got it thanks to A. Iglesias's code-
<li class="active">Home</li>
<li>Who are we?</li>
<li>Make a resume</li>
<li>Search for jobs</li>
<li>Profile</li>
<?php if (isset($_SESSION['username'] )) { ?>
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#"><b>
<p>Welcome <strong><?=$_SESSION['username']?></strong></p>
<ul class="dropdown-menu">
logout </p>
</b>
</a>
</div>
<?php } else { ?>
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#"><b>
<p>Account</p>
<ul class="dropdown-menu">
<p>Login</p>
<?php } ?>
</ul>
</li>
</ul>
</div>
</div>
</nav>
so now If a user is logged in it will show "Welcome [User]" in a drop-down bar (which includes the log out and soon to be account page) and when no one is logged in it shows "Account" which has a drop down to a log in page. Thanks Guys!

Update db table with an INT

Okay I can't get this figured out.
I want a logged in user to update a row with an amount (INT), I keep getting the invalid parameter error as well as a Call to member function execute() on a non-object.
Here is the php and html that should update the db
<?php
ini_set("log_errors", 1);
ini_set("error_log", "/tmp/php-error.log");
session_start();
require_once 'class.user.php';
$user_home = new USER();
if(!$user_home->is_logged_in())
{
$user_home->redirect('index.php');
}
$stmt = $user_home->runQuery("SELECT * FROM tbl_client_info WHERE UCODE=:uid");
$stmt->execute(array(":uid"=>$_SESSION['userSession']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() == 1)
{
if(isset($_POST['btn-update-data']))
{
$purchasedata = $_POST['purchasedata'];
$cpurchasedata = $_POST['cpurchasedata'];
if($cpurchasedata!==$purchasedata)
{
$msg = "<div class='alert alert-block'>
<button class='close' data-dismiss='alert'>×</button>
<strong>Sorry!</strong> Input Does Not Match. Make sure the details match.
</div>";
}
else
{
$stmt = $user_home->register("INSERT INTO tbl_client_info (purchasedata) VALUES (?)");
$stmt->execute(array(":purchasedata"=>$purchasedata));
//
$msg = "<div class='alert alert-success'>
<button class='close' data-dismiss='alert'>×</button>
Okay, we have added data to your account.
</div>";
}
}
}
else
{
$msg = "<div class='alert alert-success'>
<button class='close' data-dismiss='alert'>×</button>
No Sorry That Did Not Work, Try again
</div>";
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Forgot Password</title>
<!-- Bootstrap -->
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen">
<link href="bootstrap/css/bootstrap.css" rel="stylesheet" media="screen">
<link href="bootstrap/css/bootstrap-responsive.min.css" rel="stylesheet" media="screen">
<link href="assets/styles.css" rel="stylesheet" media="screen">
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="fonts/css/font-awesome.min.css" rel="stylesheet">
<link href="css/animate.min.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Custom styling plus plugins -->
<link href="css/custom.css" rel="stylesheet">
<link href="css/icheck/flat/green.css" rel="stylesheet">
<script src="js/vendor/modernizr-2.6.2-respond-1.1.0.min.js"></script>
<!-- Sweet Alert -->
<script src="dist/sweetalert-dev.js"></script>
<link rel="stylesheet" href="dist/sweetalert.css">
<!--.......................-->
</head>
<body style="background:#f3f3f3;">
<div id="wrapper">
<div id="login_content" class="animate form">
<section class="login_content">
<form method="post">
<h1>Purchase Data</h1>
<div class='alert alert-success'>
<strong>Hello </strong><?php echo $row['firstname'] ?>! //add more text here
</div>
<?php
if(isset($msg))
{
echo $msg;
}
?>
<input type="text" class="input-block-level" placeholder="500mb" name="purchasedata" required />
<input type="text" class="input-block-level" placeholder="Retype the bundle" name="cpurchasedata" required />
<hr />
<button class="btn btn-large btn-primary" type="submit" name="btn-update-data">Add data to my account</button>
<div class="clearfix"></div>
<div class="separator">
and here is the class_user.php
<?php
require_once 'dbconfig.php';
class USER
{
private $conn;
public function __construct()
{
$database = new Database();
$db = $database->dbConnection();
$this->conn = $db;
}
public function runQuery($sql)
{
$stmt = $this->conn->prepare($sql);
return $stmt;
}
public function lasdID()
{
$stmt = $this->conn->lastInsertId();
return $stmt;
}
public function register($uname,$email,$upass,$code,$purchasedata)
{
try
{
$password = md5($upass);
$stmt = $this->conn->prepare("INSERT INTO tbl_client_info(User_Name,billingemail,password,purchasedata,tokenCode)
VALUES(:User_Name, :billingemail, :password, :purchasedata, :active_code)");
$stmt->bindparam(":user_name",$uname);
$stmt->bindparam(":user_mail",$email);
$stmt->bindparam(":user_pass",$password);
$stmt->bindparam(":active_code",$code);
$stmt->bindparam(":purchasedata",$purchasedata);
$stmt->execute();
return $stmt;
}
catch(PDOException $ex)
{
echo $ex->getMessage();
}
}
public function login($email,$upass)
{
try
{
$stmt = $this->conn->prepare("SELECT * FROM tbl_client_info WHERE billingemail=:email_id");
$stmt->execute(array(":email_id"=>$email));
$userRow=$stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() == 1)
{
if($userRow['userStatus']=="Y")
{
if($userRow['password']==md5($upass))
{
$_SESSION['userSession'] = $userRow['UCODE'];
return true;
}
else
{
header("Location: index.php?error");
exit;
}
}
else
{
header("Location: index.php?inactive");
exit;
}
}
else
{
header("Location: index.php?error");
exit;
}
}
catch(PDOException $ex)
{
echo $ex->getMessage();
}
}
any help would really be appreciated
Look at your named placeholders:
(:User_Name, :billingemail, :password, :purchasedata, :active_code)
and
$stmt->bindparam(":user_name",$uname);
$stmt->bindparam(":user_mail",$email);
$stmt->bindparam(":user_pass",$password);
$stmt->bindparam(":active_code",$code);
$stmt->bindparam(":purchasedata",$purchasedata);
They don't match.
Each named placeholder must match and in lettercase.
Example:
:user_name and :User_Name are not the same.
so here:
(:user_name, :user_mail, :user_pass, :purchasedata, :active_code)
The manual is rather explicit on this:
http://php.net/manual/en/pdo.prepared-statements.php
and don't go live with this in using MD5, it's no longer safe.
Use password_hash():
http://php.net/manual/en/function.password-hash.php
Check for errors:
http://php.net/manual/en/pdo.error-handling.php
http://php.net/manual/en/function.error-reporting.php
and make sure your column names are correct and lettercase could be a factor.

Inserting value to database using prepared statement

I am trying to get a user to insert value of specific row in db table. However I keep getting an error: Call to a member function register()
Here is the php and html code that I am using to update the table
<?php
ini_set("log_errors", 1);
ini_set("error_log", "/tmp/php-error.log");
session_start();
require_once 'class.user.php';
$user_home = new USER();
if(!$user_home->is_logged_in())
{
$user_home->redirect('index.php');
}
$stmt = $user_home->runQuery("SELECT * FROM tbl_client_info WHERE UCODE=:uid");
$stmt->execute(array(":uid"=>$_SESSION['userSession']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() == 1)
{
if(isset($_POST['submit']))
{
$purchasedata = $_POST['purchasedata'];
$cpurchasedata = $_POST['cpurchasedata'];
if($cpurchasedata!==$purchasedata)
{
$msg = "<div class='alert alert-block'>
<button class='close' data-dismiss='alert'>×</button>
<strong>Sorry!</strong> Input Does Not Match. Make sure the details match.
</div>";
}
else
{
$stmt = $user-> register("UPDATE tbl_client_info SET purchasedata=? WHERE UCODE=:uid");
$stmt->execute(array(":purchasedata"=>$purchasedata,":uid"=>$rows['UCODE']));
//
$msg = "<div class='alert alert-success'>
<button class='close' data-dismiss='alert'>×</button>
Okay, we have added data to your account.
</div>";
}
}
}
else
{
$msg = "<div class='alert alert-success'>
<button class='close' data-dismiss='alert'>×</button>
No Sorry That Did Not Work, Try again
</div>";
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Forgot Password</title>
<!-- Bootstrap -->
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen">
<link href="bootstrap/css/bootstrap.css" rel="stylesheet" media="screen">
<link href="bootstrap/css/bootstrap-responsive.min.css" rel="stylesheet" media="screen">
<link href="assets/styles.css" rel="stylesheet" media="screen">
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="fonts/css/font-awesome.min.css" rel="stylesheet">
<link href="css/animate.min.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Custom styling plus plugins -->
<link href="css/custom.css" rel="stylesheet">
<link href="css/icheck/flat/green.css" rel="stylesheet">
<script src="js/vendor/modernizr-2.6.2-respond-1.1.0.min.js"></script>
<!-- Sweet Alert -->
<script src="dist/sweetalert-dev.js"></script>
<link rel="stylesheet" href="dist/sweetalert.css">
<!--.......................-->
</head>
<body style="background:#f3f3f3;">
<div id="wrapper">
<div id="login_content" class="animate form">
<section class="login_content">
<form method="post">
<h1>Purchase Data</h1>
<div class='alert alert-success'>
<strong>Hello </strong><?php echo $row['firstname'] ?>! //add more text here
</div>
<?php
if(isset($msg))
{
echo $msg;
}
?>
<input type="text" class="input-block-level" placeholder="500mb" name="purchasedata" required />
<input type="text" class="input-block-level" placeholder="Retype the bundle" name="cpurchasedata" required />
<hr />
<button class="btn btn-large btn-primary" type="submit" name="btn-update-data">Add data to my account</button>
<div class="clearfix"></div>
<div class="separator">
<p class="change_link">All Done ?
Go Home
my class.user.php looks like this:
<?php
require_once 'dbconfig.php';
class USER
{
private $conn;
public function __construct()
{
$database = new Database();
$db = $database->dbConnection();
$this->conn = $db;
}
public function runQuery($sql)
{
$stmt = $this->conn->prepare($sql);
return $stmt;
}
public function lasdID()
{
$stmt = $this->conn->lastInsertId();
return $stmt;
}
public function register($uname,$email,$upass,$code,$purchasedata)
{
try
{
$password = md5($upass);
$stmt = $this->conn->prepare("INSERT INTO tbl_client_info(User_Name,billingemail,password,purchasedata,tokenCode)
VALUES(:User_Name, :billingemail, :password, :purchasedata, :active_code)");
$stmt->bindparam(":user_name",$uname);
$stmt->bindparam(":user_mail",$email);
$stmt->bindparam(":user_pass",$password);
$stmt->bindparam(":active_code",$code);
$stmt->bindparam(":purchasedata",$purchasedata);
$stmt->execute();
return $stmt;
}
What is it that I am doing wrong? I have searched the error, but I can't see where I have gone wrong. Any help or links to help would be appreciated.
$user should be $user_home. You have used the wrong varible while calling register function.

Log users ip on login PHP mysql

I want to log the users IP when they login all I want it to do it update a column
I know $_SERVER['REMOTE_ADDR']; get their ip.
I want to log it on login on their username row in mysql.
Here's an image of my mysql table
https://gyazo.com/cf5b223df03d0da8a15bf61ed037d847
LoginCheck.php:
<?php
# Processes
function cleanString($con, $string) {
return mysqli_real_escape_string($con, stripcslashes($string));
}
# buttons use the request method
if (isset($_REQUEST['login'])) {
$username = strtolower(cleanString($con, $_POST['username']));
$password = cleanString($con, $_POST['password']);
$errors = array();
if (empty($username) || empty($password)) {
# If they left the shit blank like a jew
$errors[] = "Please make sure you entered a valid username and password";
}
$password = md5($password);
$db_check_username = mysqli_query($con, "SELECT username FROM users WHERE username='$username' OR email='$username'");
$db_check_userdata = mysqli_query($con, "SELECT username,password FROM users WHERE username='$username' AND password='$password' OR email='$username' AND password='$password'");
if (!$db_check_username || !$db_check_userdata) {
$errors[] = mysqli_error($con);
}
if (mysqli_num_rows($db_check_username) == 0) {
# If the username doesn't exist like a bitch
$errors[] = "No account could be found with that username.";
}
if (mysqli_num_rows($db_check_userdata) == 0) {
# If the Username and Password don't match
$errors[] = "Username and Password combination incorrect.";
}
if(empty($errors)) {
session_start();
$_SESSION['username'] = $username;
$success[] = "You have successfully logged in. Redirecting in a moment.";
echo '<meta http-equiv="refresh" content="5; url=index.php" />';
} else {
$danger = $errors;
}
}
?>
Login.php
<?php
# Include da files mate
include('includes/config.php');
include('includes/logincheck.php');
# Other Shit
//nothing yet
?>
<!DOCTYPE html>
<!--[if IE 8]> <html lang="en" class="ie8"> <![endif]-->
<!--[if !IE]><!-->
<html lang="en">
<!--<![endif]-->
<head>
<meta charset="utf-8" />
<title>Twisted Movies | Login Page</title>
<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport" />
<meta content="" name="description" />
<meta content="" name="author" />
<!-- ================== BEGIN BASE CSS STYLE ================== -->
<link href="http://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700" rel="stylesheet">
<link href="assets/plugins/jquery-ui/themes/base/minified/jquery-ui.min.css" rel="stylesheet" />
<link href="assets/plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet" />
<link href="assets/plugins/font-awesome/css/font-awesome.min.css" rel="stylesheet" />
<link href="assets/css/animate.min.css" rel="stylesheet" />
<link href="assets/css/style.min.css" rel="stylesheet" />
<link href="assets/css/style-responsive.min.css" rel="stylesheet" />
<link href="assets/css/theme/red.css" rel="stylesheet" id="theme" />
<!-- ================== END BASE CSS STYLE ================== -->
<!-- ================== BEGIN BASE JS ================== -->
<script src="assets/plugins/pace/pace.min.js"></script>
<!-- ================== END BASE JS ================== -->
</head>
<body class="pace-top">
<!-- begin #page-loader -->
<div id="page-loader" class="fade in"><span class="spinner"></span></div>
<!-- end #page-loader -->
<div class="login-cover">
<div class="login-cover-image"><img src="assets/img/login-bg/bg-1.jpg" data-id="login-cover-image" alt="" /></div>
<div class="login-cover-bg"></div>
</div>
<!-- begin #page-container -->
<div id="page-container" class="fade">
<!-- begin login -->
<div class="login login-v2" data-pageload-addclass="animated fadeIn">
<!-- begin brand -->
<div class="login-header">
<div class="brand">
<span class="logo"></span> Twisted Movies
<small>Where the best movies are AD free!</small>
</div>
<div class="icon">
<i class="fa fa-sign-in"></i>
</div>
</div>
<!-- end brand -->
<div class="login-content">
<form action="" method="POST" class="margin-bottom-0">
<div class="text-center">
<?php
if (!empty($success)) {
foreach ($success as $value) {
echo '<div class="alert alert-success">';
echo $value.'<br>';
echo '</div>';
}
} elseif (!empty($danger)) {
foreach ($danger as $value) {
echo '<div class="alert alert-danger">';
echo $value.'<br>';
echo '</div>';
}
} elseif (!empty($warning)) {
foreach ($warning as $value) {
echo '<div class="alert alert-warning">';
echo $value.'<br>';
echo '</div>';
}
} elseif (!empty($info)) {
foreach ($info as $value) {
echo '<div class="alert alert-info">';
echo $value.'<br>';
echo '</div>';
}
} else {
echo '<div class="alert alert-info">';
echo "Please enter a username and password.";
echo '</div>';
}
?>
</div>
<div class="form-group m-b-20">
<input type="text" name="username" placeholder="Username" class="form-control input-lg"/>
</div>
<div class="form-group m-b-20">
<input type="password" name="password" placeholder="Password" class="form-control input-lg"/>
</div>
<div class="checkbox m-b-20">
<label>
<input type="checkbox" /> Remember Me
</label>
</div>
<div class="login-buttons">
<button type="submit" name="login" class="btn btn-success btn-block btn-lg">Sign me in</button>
</div>
<div class="m-t-20">
Not a member yet? Click here to register.
</div>
<center><?php include 'includes/footer.php'; ?></center>
</form>
</div>
</div>
<!-- end login -->
</div>
<!-- end page container -->
<!-- ================== BEGIN BASE JS ================== -->
<script src="assets/plugins/jquery/jquery-1.9.1.min.js"></script>
<script src="assets/plugins/jquery/jquery-migrate-1.1.0.min.js"></script>
<script src="assets/plugins/jquery-ui/ui/minified/jquery-ui.min.js"></script>
<script src="assets/plugins/bootstrap/js/bootstrap.min.js"></script>
<!--[if lt IE 9]>
<script src="assets/crossbrowserjs/html5shiv.js"></script>
<script src="assets/crossbrowserjs/respond.min.js"></script>
<script src="assets/crossbrowserjs/excanvas.min.js"></script>
<![endif]-->
<script src="assets/plugins/jquery-hashchange/jquery.hashchange.min.js"></script>
<script src="assets/plugins/slimscroll/jquery.slimscroll.min.js"></script>
<script src="assets/plugins/jquery-cookie/jquery.cookie.js"></script>
<!-- ================== END BASE JS ================== -->
<!-- ================== BEGIN PAGE LEVEL JS ================== -->
<script src="assets/js/login-v2.demo.min.js"></script>
<script src="assets/js/apps.min.js"></script>
<!-- ================== END PAGE LEVEL JS ================== -->
<script>
$(document).ready(function() {
App.init(ajax=true);
LoginV2.init();
});
</script>
</body>
</html>
Right after you have session_start():
$ip = $_SERVER['REMOTE_ADDR'];;
$stmt = $con->prepare("UPDATE users SET `IP`=? WHERE username=?");
$stmt->bind_param("ss", $ip, $username);
$stmt->execute();
Some tips:
Try to always use prepared statements when dealing with user data.
use a HTTP class to get the IP. The IP is not always in REMOTE_ADDR, especially if the site is behind a proxy such as Cloudflare

Categories