Update operation not working in Php MySQL database - php

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

Related

Give A Report when Unsuccesfull update database

i'm very new in PHP programming. I have a code for update database value with 2 condition. Here is my code.
<?php
$objConnect = mysql_connect("localhost","root","");
$objDB = mysql_select_db("");
$id = $_REQUEST["id"];
$serial_number = $_REQUEST["serial_number"];
$email = $_REQUEST["email"];
$nama = $_REQUEST["nama"];
$password = $_REQUEST["password"];
/*** Check Email Exists ***/
$strSQL = "SELECT * FROM iot WHERE email = '".$email."' AND id != '".$id."'";
$objQuery = mysql_query($strSQL);
$objResult = mysql_fetch_array($objQuery);
if($objResult)
{
$arr['StatusID'] = "0";
$arr['Error'] = "Email Exists!";
echo json_encode($arr);
exit();
}
/*** Update ***/
$strSQL = " UPDATE iot SET
email = '".$email."'
,nama = '".$nama."'
,password = '".$password."'
WHERE id = '".$id."' AND serial_number = '".$serial_number."'
";
$objQuery = mysqli_query($objConnect,$strSQL);
if(!$objQuery)
{
$arr['Report'] = "Cannot save data!";
}
else
{
$arr['Report'] = "Saved";
}
mysql_close($objConnect);
echo json_encode($arr);
?>
What i want is if one of two condition not meet, then it will show a report " Cannot Save Data".
Sorry for my bad english.
Cheers.

PHP choose another username

I have made a registration PHP file that runs through an authentication and connects to my database that I made in phpMyAdmin. The problem is, I can put in the same username without consequence and it adds to the database, so I could put; dogs as the username and then again put the same.
How can I make it so the user is told; that username already exists choose another one.
Here's my php so far;
Also please tell me where to insert it.
<?php
require('db.php');
// If form submitted, insert values into the database.
if (isset($_POST['username'])) {
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$username = stripslashes($username);
$username = mysql_real_escape_string($username);
$email = stripslashes($email);
$email = mysql_real_escape_string($email);
$password = stripslashes($password);
$password = mysql_real_escape_string($password);
$trn_date = date("Y-m-d H:i:s");
$query = "INSERT into `users` (username, password, email, trn_date) VALUES ('$username', '".md5($password)."', '$email', '$trn_date')";
$result = mysql_query($query);
if ($result) {
echo "<div class='form'><h3>You are registered successfully.</h3><br/>Click here to <a href='login.php'>Login</a></div>";
}
} else {
?>
You should query the database before inserting any record (user) to users table.
Try the code below:
<?php
$username = mysql_real_escape_string( $username ); //Sql injection prevention
$existance = mysql_query("SELECT username FROM users WHERE username = '" . $username . "'");
if( !$existance ){
$query = "INSERT into `users` (username, password, email, trn_date) VALUES ('$username', '".md5($password)."', '$email', '$trn_date')";
$result = mysql_query( $query );
if ( $result ) {
echo "<div class='form'><h3>You are registered successfully.</h3><br/>Click here to <a href='login.php'>Login</a></div>";
}
else{
//unsuccessful insertion
}
} else {
//the user existed already, choose another username
}
?>
Create an if-statement where you check if $username exists in the db. If it does, throw an error. If not, continue with the code.
Note
Your code is vulnerable to SQL-injection. Read this post: How can I prevent SQL injection in PHP?
Rewriting my entire answer to a working example. I'm going to assume your post variables are the same as mine: email, password, username
<?php
$errorMessage = "";
function quote_smart($value, $handle) {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
if (!is_numeric($value)) {
$value = "'" . mysql_real_escape_string($value, $handle) . "'";
}
return $value;
}
$email = $_POST['email'];
$password = $_POST['password'];
$username = $_POST['username'];
$email1 = $_POST['email'];
$username1 = $_POST['username'];
$password1 = $_POST['password'];
$email = htmlspecialchars($email);
$password = htmlspecialchars($password);
$username = htmlspecialchars($username);
$connect = mysql_connect("localhost","DBuser", "DBpassword");
if (!$connect) {
die(mysql_error());
}
mysql_select_db("DBName");
$results = mysql_query("SELECT * FROM users WHERE username = '$username'");
while($row = mysql_fetch_array($results)) {
$kudots = $row['username']; }
if ($kudots != ""){
$errorMessage = "Username Already Taken";
$doNothing = 1;
}
$result = mysql_query("SELECT * FROM users WHERE email = '$email'");
while($row2 = mysql_fetch_array($results)) {
$kudots2 = $row2['email']; }
if ($kudots2 != ""){
$errorMessage = "Email Already in use";
$doNothing = 1;
}
//test to see if $errorMessage is blank
//if it is, then we can go ahead with the rest of the code
//if it's not, we can display the error
if ($errorMessage == "") {
$user_name = "DBUsername";
$pass_word = "DBPassword";
$database = "DBName";
$server = "localhost";
$db_handle = mysql_connect($server, $user_name, $pass_word);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$email = quote_smart($email, $db_handle);
$password = quote_smart($password, $db_handle);
$username = quote_smart($username, $db_handle);
if ($username1 == ""){
$errorMessage = "You need a username";
}
if ($password1 == ""){
$errorMessage = $errorMessage . "<br>You need a password.";
}
if (!(isset($_POST['email']))){
$errorMessage = $errorMessage . "<br>You need an email.";
}
$SQL = "SELECT * FROM users WHERE email = $email";
$result = mysql_query($SQL);
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
$errorMessage = "email already exists";
$doNothing = 1;
}
if ($errorMessage == "") {
$SQL = "INSERT INTO users (email, username, password) VALUES ($email, $username, $password)";
$result = mysql_query($SQL);
mysql_close($db_handle);
//=================================================================================
// START THE SESSION AND PUT SOMETHING INTO THE SESSION VARIABLE CALLED login
// SEND USER TO A DIFFERENT PAGE AFTER SIGN UP
//=================================================================================
session_start();
$_SESSION['email'] = "$email1";
$_SESSION['password'] = "$password1";
header ("Location: myaccount.php");
else {
$errorMessage = "Database Not Found";
}
}
OK, now echo $errorMessage right below or above the form, to inform the user that the Email, or Username is taken. I'm pretty sure I have a duplicate function in here for the Email, but this code does work; disregard if somebody says it's vulnerable to SQL injection; this is a working EXAMPLE! If you want to do MySQL real escape string, just Google it. I had to rewrite a couple things because I don't want my full code on a public board, if for some odd reason this doesn't work; send me an eMail(canadezo121#gmail.com) and I'll send you the full page code. (Which WORKS!) This code will probably raise some concerns with other more professional coders, this example gives you a good logical viewpoint of what goes on and how it works. You can adjust it to MySQLi, PDO, etc as you get more familiar with PHP and MySQL.
1 you must verify if the username all ready exists in database (Select)
2 if not exists after you can insert the new user

Updating User Information using SQL query

Updated code, after information is typed in and the submit button clicked to run this code, it goes back to the account page but doesnt update the database:
<font face="ClearSans-Thin">
<font color="lightgray">
<?php
include 'editaccount.php';
include 'connection.php';
?>
<center>
<?php
if (isset($_POST['uregsubmit'])) {
$firstname = $_POST['ufirstname'];
$lastname = $_POST['ulastname'];
$email = $_POST['uemail'];
$dob = $_POST['udob'];
$user = $_POST['uregisterusername'];
$pass = $_POST['uregisterpassword'];
}
//the query
$query = "UPDATE Users SET FirstName='$firstname', LastName='$lastname' WHERE Username='$user'";
//execute the query
$result = mysqli_query($connection, $query)
or die("Error: ".mysqli_error($connection));
//check and see if any data returned
?>
</center>
Write sql query inside if statement
<?php
if (isset($_POST['uregsubmit'])) {
$firstname = $_POST['ufirstname'];
$lastname = $_POST['ulastname'];
$email = $_POST['uemail'];
$dob = $_POST['udob'];
$user = $_POST['uregisterusername'];
$pass = $_POST['uregisterpassword'];
//the query
$query = "UPDATE Users SET FirstName='$firstname', LastName='$lastname' WHERE Username='$user'";
//execute the query
$result = mysqli_query($connection, $query)
or die("Error: ".mysqli_error($connection));
//check and see if any data returned
}
?>
you have an extra comma before WHERE

Need help displaying username when user logs in php

So below I have my php code, everything works fine and dandy except when the user logs in and is redirected to the restricted page. When a person signs up, they fill out their first name, email, and password. In the login page it only requires email and password. When they are redirected I want to only display their first name though. I have tried making the session = $result which should return the result of the sql query, but if I do that it doesn't even redirect to the restricted page. What am I doing wrong?
<?php
// DATABASE VARIABLES
$user_name = "";
$pass_word = "";
$database = "";
$server = "";
// CONNECTS TO DATABASE
$db_handle = mysql_connect($server, $user_name, $pass_word);
$db_found = mysql_select_db($database, $db_handle);
// ACCOUNT INFORMATION
$email;
$password;
$num_rows = 0;
// IF SUBMIT IS CLICKED
if (isset($_POST['submit'])) {
// STORES INPUTS AS VARIABLES
$email = $_POST['email'];
$password = $_POST['password'];
// REMOVES HARMFUL CODE
$email = htmlspecialchars($email);
$password = htmlspecialchars($password);
if ($db_found) {
$SQL = "SELECT * FROM accounts WHERE email = '$email' AND password = '$password'";
$result = mysql_query($SQL);
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
session_start();
$_SESSION['login'] = ?;
header ("Location: loggedin/account.php");
}
else {
session_start();
$_SESSION['login'] = '';
}
}
else {
}
}
?>
Here is what I would do.....
// DATABASE VARIABLES
$user_name = "";
$pass_word = "";
$database = "";
$server = "";
// CONNECTS TO DATABASE
$db_handle = mysql_connect($server, $user_name, $pass_word);
$db_found = mysql_select_db($database, $db_handle);
// ACCOUNT INFORMATION
$email;
$password;
$num_rows = 0;
// IF SUBMIT IS CLICKED
if (isset($_POST['submit'])) {
// STORES INPUTS AS VARIABLES
$email = $_POST['email'];
$password = $_POST['password'];
// REMOVES HARMFUL CODE
$email = htmlspecialchars($email);
$password = htmlspecialchars($password);
if ($db_found) {
$SQL = "SELECT * FROM accounts WHERE email = '$email' AND password = '$password'";
$result = mysql_query($SQL);
$num_rows = mysql_num_rows($result);
// Grab user name from db
$row = mysql_fetch_row($result);
if ($num_rows > 0) {
// Add to session variable
session_start();
$_SESSION['login'] = $row['username'];
header ("Location: loggedin/account.php");
}
else {
//Either exit or redirect to login failure page.
}
}
else {
This seems alright to me although I cant test at current.
Edit
You may want to have a read on using the Mysqli and PDO connection, it is slightly quicker and definitely more secure, just a suggestion if you have the time. Also prepared statements would definitely be more secure.
This is how I do Login... You must have an ID for each user in mysql and define
$_SESSION['user_id'] = $fetched_id;
and in loggedin/account.php page you can simply make this:
$user_id = $_SESSION['user_id'];
$query = mysql_query("SELECT `first_name` FROM `users` WHERE `id` = '{$user_id}'");

why it is not updating url in database

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");

Categories