why it is not updating url in database - php

I have a page named ques.php. If the user's answer is correct he will be directed to next ques1.php. The answer posted by the user is checked by check.php and if it is correct I want to store the new URL (ques1.php) in the users account in the database.
check.php
<?php
require_once("./include/membersite_config.php");
if (!$fgmembersite->CheckLogin()) {
$fgmembersite->RedirectToURL("login.php");
exit;
}
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("simplelogin") or die(mysql_error());
$data = mysql_query("SELECT * FROM member") or die(mysql_error());
while($info = mysql_fetch_array( $data )) {
// print $info['username'];
if ($info['username'] == $fgmembersite->UserName()) {
$fullname = $info['name'];
$username = $info['username'];
$password = $info['password'];
$email = $info['email'];
$url = $info ['url'];
break;
}
}
$answer = $_POST['answer'];
if ($answer == "correct") {
"UPDATE `simplelogin`.`member`
SET `url` = 'ques1.php'
WHERE
`member`.`name` = '$fullname'
AND `member`.`email` = '$email'
AND `member`.`username` = '$username'
AND `member`.`password` = '$password'
AND `member`.`confirmcode` = 'y'
AND `member`.`url` = '$url'";
//in place of above update query i had also used
//"UPDATE member
//SET url = 'ques1.php'
//WHERE username = '$username'"
Header("Location:ques1.php");
} else {
Header("Location: ques.php");
}
?>
function UserName() {
return isset($_SESSION['user_name'])?$_SESSION['user_name']:'';
}
login.php
<?php
require_once("./include/membersite_config.php");
if (isset($_POST['submitted'])) {
if ($fgmembersite->Login()) {
//$fgmembersite->RedirectToURL("login-home.php");
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("simplelogin") or die(mysql_error());
$data = mysql_query("SELECT * FROM member") or die(mysql_error());
while ($info = mysql_fetch_array( $data )) {
if ($info['username']==($fgmembersite->SafeDisplay('username'))) {
$url = $info['url'];
break;
}
}
$fgmembersite->RedirectToURL("$url");
}
}
?>
In login.php I am retrieving the URL from the database and redirecting the user - by default URLfor the user is ques.php.
Why is my query not updating the url in my database?

"UPDATE `simplelogin`.`member` SET `url` = 'ques1.php' WHERE
`member`.`name` ='$fullname'
AND `member`.`email` = '$email' AND `member`.`username` = '$username'
AND `member`.`password` = '$password'
AND `member`.`confirmcode` = 'y' AND `member`.`url` = '$url'" ;
Doesnt appear to be running as a query, you haven't placed it within the mysql_query() function so it has no idea what you are trying to do with that statement.
Try this instead:
mysql_query(
"UPDATE `simplelogin`.`member` SET `url` = 'ques1.php' WHERE
`member`.`name` ='$fullname'
AND `member`.`email` = '$email' AND `member`.`username` = '$username'
AND `member`.`password` = '$password'
AND `member`.`confirmcode` = 'y' AND `member`.`url` = '$url'");
Updated due to comments below:
Try this, it's been rewritten and simplified and should work, if not please port of you get the error message or not
mysql_query("
UPDATE
member
SET
url = 'ques1.php'
WHERE
name = '$fullname'
AND
email = '$email'
AND
username = '$username'
AND
password = '$password'
AND
confirmcode = 'y'
AND
url = '$url'
") or die('Unable to update members URL: ' . mysql_error());

As it is you are looping a set of database results and comparing against a value that you already have, just to get the value that you already have. At best this verifies that the user exists in the database, at worst it does nothing at all.
Really you need to be using the Primary Key of your database table for the UPDATE. Best practice dictates that this should be an auto-incrementing integer, which has no relevance to the data other than to identify the row. When you initialise the $fgmembersite object this value should be stored in it, so it can easily be used in any database query which requires a reference to the user. At worst, a unique index should be present on the username column of the table.
You can can remove the SELECT query completely - you already have the username, so you can just use this directly in the UPDATE:
check.php:
<?php
require_once("./include/membersite_config.php");
// Redirect to login page if not already authenticated
if (!$fgmembersite->CheckLogin()) {
$fgmembersite->RedirectToURL("login.php");
exit;
}
// Define DB connection info in variables for readability/maintainability
$dbHost = 'localhost';
$dbUser = 'root'; // NEVER use root for a live website!
$dbPass = ''; // A blank root password? Really?
$dbName = 'simplelogin';
// Connect to database - NEVER show the result of mysql_error() in a live site!
mysql_connect($dbHost, $dbUser, $dbPass) or die(mysql_error());
mysql_select_db($dbName) or die(mysql_error());
if ($_POST['answer'] == 'correct')
// Update the database with the new URL
$query = "
UPDATE `member`
SET `url` = 'ques1.php'
WHERE `username` = '".mysql_real_escape_string($fgmembersite->UserName())."'
";
mysql_query($query) or die(mysql_error());
// This line should help you debug the query. REMOVE IT before putting this script on a live site!
if (!mysql_affected_rows()) die("No rows were affected by the query.\nQuery: $query\nError: ".mysql_error());
// Redirect to ques1.php
// Note that a header redirect should provide a FULL url, not just a relative path.
header("Location:ques1.php");
} else {
// Redirect to ques.php
header("Location: ques.php");
}
?>
login.php
<?php
require_once("./include/membersite_config.php");
if (isset($_POST['submitted']) && $fgmembersite->Login()) {
// Define DB connection info in variables for readability/maintainability
$dbHost = 'localhost';
$dbUser = 'root'; // NEVER use root for a live website!
$dbPass = ''; // A blank root password? Really?
$dbName = 'simplelogin';
// Connect to database - NEVER show the result of mysql_error() in a live site!
mysql_connect($dbHost, $dbUser, $dbPass) or die(mysql_error());
mysql_select_db($dbName) or die(mysql_error());
// Fetch the URL from the database
$query = "
SELECT `url`
FROM `member`
WHERE `username` = '".mysql_real_escape_string($fgmembersite->UserName())."'
";
$result = mysql_query($query) or die(mysql_error());
if (!mysql_num_rows($result)) die('Invalid user name');
$info = mysql_fetch_assoc($result);
$url = $info['url'];
// Redirect to URL
// Add some error checking to verify that $url actually contains something valid!
$fgmembersite->RedirectToURL($url);
} else {
// What happens if the condition fails?
}
?>

execute the query dude.... use mysql_query("$your_update query");

Related

How to store a return result from an SQL statement in a PHP session variable

I was here yesterday with the same issue, but I have changed the code slightly. I am trying to fetch the user id of a user as they log in and store it as a session variable. I don't know what I'm doing wrong though, as when I try pass this session variable into another SQL INSERT statement in a different php file, it does not work. If I pass a local variable to the INSERT statement it works and inserts all values into my database. When I try pass the session variable, it does not work.
This is my login file where I declare the session variable:
<?php
session_start();
$db =mysqli_connect("localhost", "root", "", "project_website1");
if(isset($_POST['Login_Btn'])) {
$email = mysql_real_escape_string($_POST['email']);
$password = mysql_real_escape_string($_POST['password']);
$id_retrieve = mysqli_query("SELECT user_id FROM userdetails WHERE email='$email'");
$retrieved_id = mysqli_fetch_row($id_retrieve);
$password = md5($password);// Decrypt hash of password stored in database
$mySQLQuery = "SELECT * FROM userdetails WHERE email='$email' AND password='$password'";
$resultOfQuery = mysqli_query($db, $mySQLQuery);
if (mysqli_num_rows($resultOfQuery) == 1) {
$_SESSION['user_id'] = $retrieved_id[0];
header("location: User_Home_Page.html");
}else{
$_SESSION['message'] = "Login Fail";
header("location: User_Login.html");
}
}
?>
This is the file where I then try insert this session variable:
<?php
session_start();
$db =mysqli_connect("localhost", "root", "", "project_website1");
if(isset($_POST['upload_btn'])){
$user_id = $_SESSION[ 'user_id' ];
$taskTitle = mysql_real_escape_string($_POST['tasktitle']);
$taskDescription = mysql_real_escape_string($_POST['TaskDescription']);
$file = rand(1000,100000)."-".$_FILES['file_document']['name'];
$file_loc = $_FILES['file_document']['tmp_name'];
$file_size = $_FILES['file_document']['size'];
$file_type = $_FILES['file_document']['type'];
$folder="uploads/";
move_uploaded_file($file_loc,$folder.$file);
$numPages = mysql_real_escape_string($_POST['number_of_pages']);
$numWords = mysql_real_escape_string($_POST['number_of_words']);
$deadlineClaim = mysql_real_escape_string($_POST['deadline_claim']);
$deadlineComplete = mysql_real_escape_string($_POST['deadline_complete']);
$sql = "INSERT INTO task(user_id, title, description, file, file_type, file_size, pg_num, num_words, deadline_claim, deadline_completion) VALUES( '$user_id', '$taskTitle', '$taskDescription', '$file', '$file_type', '$file_size', '$numPages', '$numWords', '$deadlineClaim', '$deadlineComplete')";
mysqli_query($db, $sql);
header("location: User_Home_Page.html");
}
?>
If someone could provide a solution I would really appreciate it.
First you don't need 2 query because you need a query where you get user_id based on data where user must login.
So in this query first u check for email and password to match that user and if this match u will get more that 0 based on mysqli_num_rows.
When u check this and this works you use mysqli_fetch_array so you can use a data from it however you want.
You can remove error_reporting, ini_set, var_dump if its all ok, this is just for testing and to give you error if exists
Here is your code:
<?php
// turn on error reporting
error_reporting(1);
ini_set('error_reporting', E_ALL);
// start session
session_start();
// debug session
var_dump($_SESSION);
// database connection
$db = mysqli_connect("localhost", "root", "", "project_website1");
if(isset($_POST['Login_Btn']))
{
$email = mysql_real_escape_string($_POST['email']);
$password = mysql_real_escape_string($_POST['password']);
// Decrypt hash of password stored in database
$password = md5($password);
// get all data from userdetails table
$mySQLQuery = "SELECT * FROM userdetails WHERE email='$email' AND password='$password'";
$resultOfQuery = mysqli_query($db, $mySQLQuery);
// if query return more that 0 rows
if (mysqli_num_rows($resultOfQuery) > 0)
{
// fetch data
$uid = mysqli_fetch_array($resultOfQuery);
$_SESSION['user_id'] = $uid['user_id'];
header("location: User_Home_Page.html");
exit();
}
else
{
$_SESSION['message'] = "Login Fail";
header("location: User_Login.html");
exit();
}
}
?>
EDIT :
Don't use md5 its not secure use password_hash() and password_verify() to make yours password safe.

Update operation not working in Php MySQL database

I am learning php and MySql database. I am trying to make payroll management software. In my database both insert & delete operation are executing well but i am facing problem in update operation. Here is my php script :
<html>
<body>
<?php
session_start();
$submit = $_POST['submit'];
$term = $_POST['id'];
//open database
$connect = mysql_connect("localhost","root","#") or die("Couldn't connect");
mysql_select_db("caselab") or die("Couldn't connect");
$sql = mysql_query("SELECT id FROM users WHERE id='$term'");
$count = mysql_num_rows($sql);
if($count!=0)
{
// output data of each row
$id = $_POST['id'];
$name = strip_tags($_POST['name']);
$email = strip_tags($_POST['email']);
$address = strip_tags($_POST['address']);
$contactinfo = $_POST['contactinfo'];
if($submit)
{
//open database
$connect = mysql_connect("localhost","root","#") or die("Couldn't connect");
mysql_select_db("caselab") or die("Couldn't connect");
// Existence Check
if($name && $email && $address && $contactinfo)
{
$queryreg = mysql_query ("Update users SET username = '$name', email = '$email' , address = '$address' , contactinfo = '$contactinfo' WHERE id = $id");
echo ("Congratulations!! Your changes have been saved !! <a href='payroll.html'>Click to go back to home page</a>");
}
else
echo("Please fill all the details");
}
mysql_close($connect);
}
else
echo("No such employee. Please try again.<a href='payroll.html'>Click to go back to home page</a> ");
?>
</html>
</body>
I would be highly thankful if my problem gets resolved.
Why is there a ) before WHERE?
Update users SET username = $name, email = $email , address = $address , contactinfo = $contactinfo) WHERE id = $id");
Try this:
$myqry = "Update users SET username = '". $name."', email = '".$email."' , address = '".$address."', contactinfo = '".$contactinfo."' WHERE id = ".$id.";
echo($myqry;
$queryreg = mysql_query($myqry);
if .....
However, i need reminder you that this is not a good programming method and you need learn how to PDO after you understand the basic query concepts. http://php.net/manual/en/book.pdo.php

PHP/MySQL mysql_num_rows not returning values

I'm new to PHP and programming in general, but am working on doing a login. I've got the signup page completed, and my database populates the records fine. However, when this code gets output it says I have 0 rows from the mysql_num_rows($result);... when, it should be coming back successfully showing 1 row when I input the correct username/password. Whether I put in a successful user/pass combo or not, it outputs the same.
I appreciate any help you can provide, code is listed below:
$SQL = "SELECT * FROM account WHERE username = $username AND password = md5($password)";
$result = mysql_query($SQL);
$num_rows = mysql_num_rows($result);
echo $result;
echo $num_rows;
// CLOSE CONNECTION
mysql_close($db_handle);
// COMPARE $num_rows TO SEE IF A SUCCESSFUL LOGIN, THEN DIRECT TO MEMBERS PAGE
if ($result) {
if ($num_rows > 0) {
session_start();
$_SESSION['login'] = "1";
header ("Location: page1.php");
}
else {
$error_message = "Login failed. Please try again.";
echo $num_rows;
EDIT: Complete rewrite
Try this:
<?php
$host = "host";
$user = "user";
$password = "password";
$database = "database";
$username = 'jack'; /* Insert $_Post [''] here with username variable you pass. You could sanitize and validate with for example filter_var (), clean (), etc */
$password_user = 'password from jack'; // same here.
$link = mysqli_connect($host, $user, $password, $database);
IF (!$link){
echo ("Unable to connect to database!");
}
ELSE{
$query = "SELECT * FROM account WHERE username ='$username' AND password = md5('$password_user')";
$result = mysqli_query($link, $query);
$num_rows = mysqli_num_rows($result);
$row = mysqli_fetch_array($result, MYSQLI_BOTH);
// COMPARE $num_rows TO SEE IF A SUCCESSFUL LOGIN, THEN DIRECT TO MEMBERS PAGE
if ($row) {
session_start();
$_SESSION['login'] = "1"; // pleae not that 1 is converted into a string value
$_SESSION['username'] = $username; // added username, just to test.
header ("Location: page1.php");
}
else {
$error_message = "Login failed. Please try again.";
echo $error_message;
}
// CLOSE CONNECTION
mysqli_close($link);
}
?>
Sample data:
CREATE TABLE account (
id INT auto_increment primary key,
username VARCHAR(30),
password VARCHAR(50)
);
INSERT INTO account(username, password)
VALUES
("bob", md5('password from bob')),
("jack", md5('password from jack')),
('joe', md5('password from joe'));
SQL FIDDLE DEMO
Sample page1
<?php
session_start();
$login = $_SESSION['login'];
$username = $_SESSION['username'];
echo '<h1>It WORKS, <i>'.$username.'</i>!!!</h1>';
?>
Important to note is that I have used the MYSQLI library instead of the MYSQL library. If you have more than one column in you table you should select your output per column. For example, $result['id'].
I found that you didn't escape variable in and out in you SQL statement. I have to note that I didn't debug the part below COMPARE $num_rows TO SEE IF A SUCCESSFUL LOGIN, THEN DIRECT TO MEMBERS. I think you can manage that on your own.
W.R.T. the santization and validation you have to do some more work. I don't know how you data is past via the user login in form. Let say you will use POST. In that case you can start at the top of you page with first retrieving all the posted variable using $_POST. Then filter them to make sure you code in is not open for SQL injection. E.g. $username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);

Why doesn't the if statement work within this loop? PHP

I have a while loop that goes through the rows returned from an SQL query. The values of a particular column from that row are stored in an array. The array is then iterated through and each element is compared with the input from the user. If the input matches an array element then a boolean becomes true. I'm trying to do this so that the user can enter a password to access a particular page. However it just doesn't work. I have printed all of the values from the array as well as the input, so I know that there isn't a problem there. But for some reason, the if statement just doesn't compare them. Here is the code:
if (isset( $_POST['ok'])) {
$password = $_POST['pass'];
$matched = false;
$pw = array();
mysql_connect("localhost", "xxx", "xxx")or die("Error");
mysql_select_db("details")or die("Error");
$query="SELECT * FROM members";
$result=mysql_query($query);
while ($row = mysql_fetch_assoc($result) ){
$pw[] = $row["pass"];
}
foreach($pw as $p){
if(strcmp($p, $password) == 0){
$matched = true;
}
}
if ($matched==true) {
//Membership page
} else {
//Error message
}
} else {
....
It would be much easier and efficient to change your query to something like this
$dbh = mysql_connect("localhost", "xxx", "xxx") or die("Error");
mysql_select_db("details", $dbh ) or die("Error");
$pass = mysql_real_escape_string( $_POST['pass'], $dbh );
$user = mysql_real_escape_string( $_POST['user'], $dbh );
$sqlQuery = <<< EOQ
SELECT
*
FROM
`members`
WHERE
`user` COLLATE utf8_bin = '{$user}' COLLATE utf8_bin
AND
`password` COLLATE utf8_bin = '{$pass}' COLLATE utf8_bin
EOQ;
$result = mysql_query( $sqlQuery );
if ( $result and ( mysql_num_rows( $result ) === 1 ) {
echo "success";
$userDetails = mysql_fetch_assoc( $result );
} else {
echo "username or password wrong";
}
Edit: updated the password and username check to be case sensitive in any case
Edit2: above comments remind not to store passwords plaintext. To change to hashed passwords
UPDATE members SET pass = SHA1( pass );
Then change your check to
... AND pass = SHA1( '{$pass}' )
You need a break after finding a match so that $matched will be equal to true.
if ( isset( $_POST['ok'] ) ) {
$password = $_POST['pass'];
$matched = false;
$pw = array();
mysql_connect("localhost", "xxx", "xxx")or die("Error");
mysql_select_db("details")or die("Error");
$query="SELECT * FROM members";
$result=mysql_query($query);
while ($row = mysql_fetch_assoc($result) ){
$pw[] = $row["pass"];
}
foreach($pw as $p){
if(strcmp($p, $password) == 0){
$matched = true; // found match so break out and do the membership.
break;
}
}
if ($matched==true) {
//Memebrship page
} else {
//Error message
}
} else {
....
Sugestions:
1) Replace the direct mysql function calls with PDO: ( this will not require any escaping, since the PDO will handle everything )
$mysql_host = "localhost";
$mysql_user = "xxx";
$mysql_password = "xxx";
$mysql_database = "details";
$dbLink = new PDO("mysql:host=$mysql_host;dbname=$mysql_database;charset=utf8", $mysql_user, $mysql_password, array(PDO::ATTR_PERSISTENT => true));
$query = db()->prepare("select * from members WHERE pass = ? limit 1");
$query->execute(array($_POST['pass']));
$query->setFetchMode(PDO::FETCH_ASSOC);
$myMember = $query->fetch();
$query->closeCursor();
2) If you want to stick with your code, you could use $pwd = mysql_real_escape_string($_POSt['pass']) for the posted password and then select the row containing the escaped received password $pwd. Also, do not forget mysql_free_result($result);!!!
3) Make a hash of the password therefore you will not need to use mysql_real_escape_string. use $pwHash = md5($_POST['pass']) or $pwHash = sha1($_POST['pass']) or any combination.
4) Please align your code. It will make it more readable for people answering your questions (offering help) and also for future maintenance (you or someone else; believe me, you`ll forget the code in 2-3 years).
5) Your code should work, I'm not sure why it doesn't. Try adding var_dump for $pw and also write something on the screen when the password matches. Maybe you swapped the pages (members with error)
Why the foreach loop ? You can do it like this:
if (isset( $_POST['ok'])) {
$password = $_POST['pass'];
$matched = false;
$pw = array();
mysql_connect("localhost", "xxx", "xxx")or die("Error");
mysql_select_db("details")or die("Error");
$query="SELECT * FROM members";
$result=mysql_query($query);
while ($row = mysql_fetch_assoc($result) ){
$pw[] = $row["pass"];
}
$pw_tmp = flip_array($pw);
if(isset($pw_tmp[$password])){
//Membership page
}else{
//Error message
}
}else{
// something else ...
}

MySQL Database Check

This is my code
$username = $_POST['user'];
$password = $_POST['pass'];
if (isset($_POST['user'])); {
$db = mysqli_connect('localhost', 'root', '', 'db');
if($query = mysqli_query($db, "SELECT `pass` FROM `accounts` WHERE `user` = '$username'")){
while($row = mysqli_fetch_assoc($query)){
$row['pass'] = $setpassword;
}
mysqli_free_result($query);
}
}
What it currently does is from a form, retrive a username and password that the user has entered, take that username and find the row with that username and get the password from that row and set it as the variable $setpassword. Below is the code to check if the password matches the given username on the database.
if ($password=='') {
$verify = 0;
}
if ($password!='') {
if ($password!=$setpassword) {
$verify = 1;
}
if ($password==$setpassword) {
$verify = 2;
}
}
If verify is...
0 - The Login Form Will appear as nothing has been entered.
1 - Incorrect Password will be displayed along with the login form.
2 - Correct Password will be displayed and the username will be assigned to a session variable.
I'm having a problem where a user can enter a username that doesnt exist and any password wether its in the database or not and it will be verified.
What can I do to check if the username doesn't exist on the database?
When you are accepting the user's registration query the database to see if it already exists.
$result = mysqli_query("SELECT * FROM accounts where `user` = $username");
if(mysql_num_rows($result) >0) // if there are any rows returned then the username exists
{
//User Name already exists
}
else
{
//User name doesn't exist, add user
}
I'm not sure this is where you are doing that. But to eliminate duplicates you can do it that way. Also, you can define the column user as unique. That way the SQL will not allow duplicate values.
Also this line:
$row['pass'] = $setpassword; //setting $row['pass'] to $setpasswords value.
This is reversed. You should be doing it the other way around.
$setpassword = $row['pass']; //setting setpassword to $row['pass'] value.
Let me know if I need to clarify anything.
Try this:
$username = isset($_POST['user'])?$_POST['user']:''; // check if isset to avoid notice
$password = isset($_POST['pass'])?$_POST['pass']:'';
$verify = 0;
if (!empty($username)) {
$db = mysqli_connect('localhost', 'root', '', 'db');
if($query = mysqli_query($db, "SELECT `pass` FROM `accounts` WHERE `user` = '$username'")) {
while($row = mysqli_fetch_assoc($query)){
$setpassword = $row['pass'];
break; // exit the loop once you found the password
}
mysqli_free_result($query);
}
if (isset($setpassword)) {
$verify = 1;
if ($password == $setpassword) {
$verify = 2;
}
}
if (isset($_POST['user'])); {
there is an extra semicolon in this line, making whole code not working
to do your verification, all you need is to retrieve the password and compare it with entred one:
$row = mysqli_fetch_assoc($query));
if ($row AND $row['pass'] == $password)
$verify = 1;
}
note that $row could be ampty, so, you have to check it first
however, you can do both comparisons in the query, like this
"SELECT * FROM accounts where `user` = $username" AND `pass` = '$password';
However, your code suffers from 2 common problems.
It is better to save a hash instead of the plain password.
You should sanitize your data before adding it in the query
at least this way:
$username = mysqli_real_escape_string($db,$_POST['user']);

Categories