Mysql update not changing values in data table? Query not made? - php

I am very new to mysql and am attempting to replace one value in a column with another. Right now I have 2 inputs and can echo the text value of these inputs here as well as the username of the person logged in:
<?php
session_start();
include("../php/Session.class.php");
$sess = new Session();
$sess->Init();
$cookie = isset($_COOKIE["session"]);
if($cookie)
{
$cookie = $_COOKIE["session"];
$account = $sess->Verify($cookie);
}
$pass1=$_POST['passwordText']; //name of input
echo $pass1;
$pass=$_POST['oldPass']; //name of input
echo $pass;
echo $account['username'];
I then connect to my database and am trying to set the previous password to the value of $pass1 where the user's username is located.
$dbh = new mysqli("localhost","username","password","sqlserver");
$checkforpass = "SELECT password FROM accounts WHERE username='".$account['username']."'";
$checkforpass = $dbh->query($checkforpass); //make query
$checkforpass = $checkforpass->fetch_assoc(); //prepare sql
$checkforpass = $checkforpass['password'];
echo $checkforpass;
if($checkforpass==$pass)
{
echo 'they got the password!';
$change = "UPDATE accounts SET password=".$pass1." WHERE username='".$account['username']."'";
//$change = $dbh->query($change);
$dbh->query($change); //make query
$dbh->close();
//change password
}
I get no errors but when checking my local data base the value of password stays the same. What am I doing wrong here?

I think its not getting inserted/updated because you are not using single quotes around varchar in the query.
Your query should be :
$change = "UPDATE accounts SET password='".$pass1."' WHERE username='".$account['username']."'";
OR
$change = "UPDATE accounts SET password='$pass1' WHERE username='".$account['username']."'";

Related

how to get verify if user is already registered

Guys, I am new in PHP and nowadays am working on android application and in this application I have connected my app with PHP MySQL DB and everything is working fine but the problem is now I want to check if user cnic no is available in DB so query give me to return back if no so it will be inserted in DB please help me i will be really thankful to you all of the guys
Thanks
<?php
// Create connection
$conn = new mysqli($HostName, $HostUser, $HostPass, $DatabaseName);
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$DefaultId = 0;
$ImageData = $_POST['image_path'];
$ImageName = $_POST['image_name'];
$Fullname = $_POST['fullname'];
$CNIC = $_POST['cnic'];
$Mobile = $_POST['mobile'];
$Address = $_POST['address'];
$District = $_POST['district'];
$Gender = $_POST['gender'];
$Education = $_POST['education'];
$Ward = $_POST['ward'];
$Ps = $_POST['ps'];
$Uc = $_POST['uc'];
$Bjf = $_POST['bjf'];
$By = $_POST['by'];
$Dt = $_POST['dt'];
$Email = $_POST['email'];
$GetOldIdSQL ="SELECT id FROM information ORDER BY id ASC";
$Query = mysqli_query($conn,$GetOldIdSQL);
while($row = mysqli_fetch_array($Query)){
$DefaultId = $row['id'];
}
$ImagePath = "images/$DefaultId.png";
$ServerURL = "laserlightskincare.com/$ImagePath";
//$InsertSQL = "insert into information (image_path,image_name,Fullname,CNIC,mobile,Address,District,ps,uc,ward,Gender,education,Doj,bjf,boy) values ('$ServerURL','$ImageName','$Fullname','$Cnic','$Mobile','$Address','$District','$PS','$UC','Ward','$Gender','Education','$Doj','$bjf','$boj','$boy')";
$InsertSQL = "insert into information (image_path,image_name,Fullname,CNIC,mobile,Address,District,Gender,education,ward,ps,uc,bjf,boy,Doj,email) values ('$ServerURL','$ImageName','$Fullname','$CNIC','$Mobile','$Address','$District','$Gender','$Education','$Ward','$Ps','$Uc','$Bjf','$By','$Dt','$Email')";
if(mysqli_query($conn, $InsertSQL)){
file_put_contents($ImagePath,base64_decode($ImageData));
echo "You have successfully registered";
}
mysqli_close($conn);
}else{
echo "Not Uploaded";
}
?>
First store your cnic value in an array using select statement and for() loop.
Then using the if() condition compare the cnic value in your db with the cnic value inserted. If the value is found then print that the cnic is used once else insert the data using your insert query.
Hope this helps you.
NOTE :
You should use some more appropriate value then the cnic value to check if the data is there in the db or not. I would suggest you compare the email addresses or mobile numbers of the users as they are unique for each user who signs up entering their email address and mobile number and it cannot be used again for the signup process.
Before the insert query; make a select query and check if the result is empty or not,
Another solution is to make a unique index for cnic information table so you can not insert a new record

PHP SQL update failed

In database login replace x with y in column z where username=$usr.
That's what I'm trying to create (at least I hope you understand what I mean).
My code, right now is:
<?php
session_start();
$servernaam = "server";
$susr = "user";
$spswd = "password";
$sdbnaam = "database name";
$usr = $_SESSION['usr'];
$qa = "1";
$conn = mysqli_connect($servernaam, $susr, $spswd, $sdbnaam);
$sql = "UPDATE login SET qa='$qa' WHERE username=$usr";
header("Location: Page_1.php");
?>
Question:
In the database, nothing changes. The cell I want to change stays at it's previous value.
Thanks in advance!
After asking someone who had a lot of knowlage of php and sql I've got the awnser!
This:
$sql = "UPDATE login SET qa='$qa' WHERE username=$usr";
should have been
This:
$sql = "UPDATE `login` SET `qa`='$qa' WHERE `username`='$usr'";
And I didn't add
This:
$result = $conn->query($sql);
wich actually runs the sql script.

how to update multiple data using php

i am a newbie in here and i have a problem that me myself cannot find the exact solution... here it is... i need to build a system that will update all the staff information. through this system, a staff in human resource department will enter all the staffs information. i have been create this code to update the staffs information but it seems not function with what i really want.... i just want to update by rows however, it turns to update all rows in the database...
<?php
session_start();
include ("includes/database.php");
include ("includes/security.php");
include ("includes/config.php");
$nama=$_SESSION["nama"];
$pwd=$_SESSION["status"];
$nama=$_POST["st_nama"];
$siri1=$_POST["st_siri"];
$siri2=$_POST["st_siri2"];
$siri3=$_POST["st_siri3"];
$jawatan=$_POST["st_jawatan"];
$gred=$_POST["st_gred"];
$gredh=$_POST["st_gredh"];
$gelaran=$_POST["st_gelaran"];
$elaun=$_POST["st_elaun"];
$id=$_GET["id"];
$dataPengguna2= mysql_query("SELECT * FROM tbl_rekod where id='$id'");
mysql_query("UPDATE tbl_rekod set st_nama='$nama', st_siri='$siri1', st_siri2='$siri2', st_siri3='$siri3', st_jawatan='$jawatan', st_gred='$gred', st_gredh='$gredh', st_gelaran='$gelaran', st_elaun='$elaun' WHERE id='$id'") or die (mysql_error());
$status = "REKOD BERJAYA DIKEMASKINI!<br/><a href = 'stafflogin.php'><strong>KEMBALI KE LAMAN UTAMA</strong></a>";
?>
This will help fix your sql injection issue, and may also fix update 1 vs multiple rows issue. This method uses the PDO library in PHP. You can see more info on using PDO on the PHP site. It replaces the mysql_ set of commands which are no longer included in the PHP releases.
// Below replaces the mysql_connect() so it requires db credentials filled in
try {
$host = 'hostname';
$db = 'databasename';
$user = 'username';
$pass = 'password';
$con = new PDO("mysql:host=$host;dbname=$db",$user,$pass, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
}
// This replaces the die("error message") potion of a mysql_connect() set-up
catch (Exception $e) {
$_errors['connect']['message'] = $e->getMessage();
$_errors['connect']['error_code'] = $e->getCode();
}
$nama = $_SESSION["nama"];
$pwd = $_SESSION["status"];
$nama = $_POST["st_nama"];
$siri1 = $_POST["st_siri"];
$siri2 = $_POST["st_siri2"];
$siri3 = $_POST["st_siri3"];
$jawatan = $_POST["st_jawatan"];
$gred = $_POST["st_gred"];
$gredh = $_POST["st_gredh"];
$gelaran = $_POST["st_gelaran"];
$elaun = $_POST["st_elaun"];
$id = $_GET["id"];
// You should do just a preliminary check that the id is a numeric value
// No sense in continuing if someone tries to foil the natural
// order of your code
if(is_numeric($id)) {
// The next 3 lines would be equivalent to the mysql_query("statement here")
// as well as a more robust version of mysql_real_escape_string(). It does more,
// but for sake of explanation it does that and more.
$dataPengguna2 = $con->prepare("SELECT * FROM tbl_rekod where id=:id");
// Binding paramaters basically sanitizes the value being inserted into your query
$dataPengguna2->bindParam(':id',$id);
$dataPengguna2->execute();
// There is no indication of what you are doing with the select above
// Set up the update statement
$query = $con->prepare("UPDATE tbl_rekod set st_nama=:st_nama, st_siri=:st_siri, st_siri2=:st_siri2, st_siri3=:st_siri3, st_jawatan=:st_jawatan, st_gred=:st_gred, st_gredh=:st_gredh, st_gelaran=:st_gelaran, st_elaun=:st_elaun WHERE id=:id");
// Bind all the values to sanitize against injection
// You could do a function that loops through an array of values,
// but this is one way to do it manually
$query->bindParam(':st_nama',$nama);
$query->bindParam(':st_siri',$siri1);
$query->bindParam(':st_siri2',$siri2);
$query->bindParam(':st_siri3',$siri3);
$query->bindParam(':st_jawatan',$jawatan);
$query->bindParam(':st_gred',$gred);
$query->bindParam(':st_gredh',$gredh);
$query->bindParam(':st_gelaran',$gelaran);
$query->bindParam(':st_elaun',$elaun);
$query->bindParam(':id',$id);
$query->execute();
// Print out error info. There may be something of value here
// that may help you figure out why it's trying to update all your rows
// instead of just the one.
print_r($query->errorInfo());
$status = "REKOD BERJAYA DIKEMASKINI!<br/><a href = 'stafflogin.php'><strong>KEMBALI KE LAMAN UTAMA</strong></a>";
} ?>

PHP MYSQL verify user from table and set SESSION 'username'

I have a forum page and want a simple login for user with usernames from a predefined mysql user table. I use a login.php form file link from the forum, a get $_POST username, then use a login_handle.php file that calls a function to connect to the DB, query the users array, and try to validate that the $_POST username is in the queried list array.
The function is below, and then the call in login_handle.php I'm getting various errors and don't know if this is at all a good approach. I also want to start a session during the form and verification that can grab the $_POST username as a $_SESSION username and apply to subsequent forum pages.
function isUsername($username){ //Test if proper Username from array.
$query = "SELECT username FROM users";
$result = mysql_query($query);
$usernames = mysql_fetch_assoc($result);
$isUname = true;
if(!in_array("username", $usernames)) {
echo "Please enter valid user name.<br>";
$isUname = false;
} //Search for proper username in username array.
return $isUname;
}
------------------handler call-----------
$username = $_POST["username"];
$password = $_POST["password"];
if(isUsername($username)==true){ // Check if username is valid.
//$Uname = $_SESSION['username'];
//echo "Username = " . $Uname;
echo 'go to forum';
}
First, mysql is deprecated. Please use mysqli.
Second, why don't you use something like...
function isUsername($username){
$query = "SELECT username FROM users WHERE username == '" . $username . "'";
Third: did you search and research?
These kind of question can be easily find everywhere.
As simple as it is , you need to query the specific username from $_POST , not the whole usertable.
I think requesting the number of rows ( number of apparition is a good way to get if user is in database or not , you can make it greater (>=) instead of one user condition (==)).
function isUsername($username){ //Test if proper Username from array.
$query = "SELECT username FROM users where username='$username'";
$result = mysql_query($query);
$rows = mysql_num_rows($result);
$isUname = true;
if($rows==1) {
$isUname = true;
}else{
echo "Please enter valid user name.<br>";
$isUname = false;
}
return $isUname;
}
I used nearly the same function when I manually assigned a txt array to a variable $username to compare. Now that I am using a user table I merely want to assign the an array of the queried users (thought mysql_fetch_assoc($result) creates the same type of assoc. array) to $username instead of the hard copied elements where it worked with before. Is the array produced with the query different than the $usernames=array("jes34","pes22","jis44","jll124"); that prevents me from doing this?
function isUsername($username){ //Test if proper Username from array.
$usernames=array("jes34","pes22","jis44","jll124");
$isUname = true;
if(!in_array($_POST["username"], $usernames)) {
echo "Please enter valid user name.<br>";
$isUname = false;
} //Search for proper username in username array.
return $isUname;
}
-----function call---
if(isUsername($username)==true){ do something }

How do I authenticate a user in PHP / MySQL?

So recently I learned how to properly add a username and password to a database.
My database is usersys, and the table storing user information is called userdb. The table has two columns - username (primary), password.
The registration form works great, enters the users input into the database correctly and also checks to see whether the user's username is already in the database or not.
With that said, I am asking if anyone could help me create a login script. So far, this is what I have:
$username = $_POST['username'];
$password = $_POST['password'];
$displayname = $_POST['username'];
$displayname = strtolower($displayname);
$displayname = ucfirst($displayname);
echo "Your username: " . $displayname . "<br />";
mysql_connect("localhost", "root", "******") or die(mysql_error());
echo "Connected to MySQL<br />";
mysql_select_db("usersys") or die(mysql_error());
echo "Connected to Database <br />";
$lcusername = strtolower($username);
$esclcusername = mysql_real_escape_string($lcusername);
$escpassword = mysql_real_escape_string($password);
$result = mysql_query("SELECT * FROM userdb WHERE username='$esclcusername' AND password='$escpassword'") or die(mysql_error());
$row = mysql_fetch_array( $result );
$validateUser = $row['username'];
$validatePass = $row['password'];
The POST data is from the previous log in page. I want this script to check the table (userdb) and find the row for the username that the user entered from the previous form and verify that the password entered matches the username's password set in that row, in userdb table.
I also want some type of way to check whether or not if the username entered exists, to tell the user that the username entered does not exists if it can not be found in the table.
This is not a direct answer to this question but a GOOD value-add.
You should use MYSQL SHA1 function to encrypt the password before storing into the database.
$user = $_POST['userid'];
$pwd = $_POST['password'];
$insert_sql = "INSERT into USER(userid, password) VALUES($user, SHA1($pwd))";
$select_sql = "SELECT * FROM USER WHERE userid=$user AND password=SHA1($pwd))";
You can use sessions. Sessions are global variables that when set, stay with the user while he is browsing through the site.
Since you are learning PHP, try out this tutorial on the official website.
But what you would do in theory is when the username and password match, you set a session variable
$_SESSION["auth"] = true;
$_SESSION["user_id"] = $row["user_id"];
And then do a check to see if the user is authenticated.
One way to do it (DISCLAIMER: not necessarily best-practice):
$result = mysql_query("SELECT id FROM userdb WHERE username='$esclcusername' AND password='$escpassword'") or die(mysql_error());
$row = mysql_fetch_array( $result );
$id = (int)$row['id'];
if($id > 0) {
//log in the user
session_start();
$_SESSION['userId'] = $id;
$_SESSION['username'] = $displayname;
}
... and on pages that require authentication:
session_start();
if(!isset($_SESSION['userId'])) {
die('You need to be logged in!!!');
} else {
echo 'Welcome ' . $_SESSION['username'];
}
Read more about PHP sessions.
I like to use both $_SESSION and MYSQL Checks with any login POST. This should help get a few things started.
$username = mysql_real_escape_string($_POST[username]);
$password = strip_tags($_POST[password]);
$password = sha1($password);
if(isset($username) && isset($password) && !empty($username) && !empty($password))
{
$sql = mysql_query("SELECT * FROM users_column WHERE username = '$username' AND password = '$password'");
//Check the number of users against database
//with the given criteria. We're looking for 1 so
//adding > 0 (greater than zero does the trick).
$num_rows = mysql_num_rows($sql);
if($num_rows > 0){
//Lets grab and create a variable from the DB to register
//the user's session with.
$gid = mysql_query("SELECT * FROM users_column WHERE username = '$username' AND password = '$password'");
$row = mysql_fetch_assoc($gid);
$uid = $row[userid];
// This is where we register the session.
$_SESSION[valid_user] = $uid;
//Send the user to the member page. The userid is what the
//session include runs against.
header('Location: memberpage.php?userid='.$userid);
}
//If it doesn't check out -- throw an error.
else
{
echo 'Invalid Login Information';
}
}
NOTE: You would need to start the page file with session_start() and create a separate Session Check include stating with session_start() and then your progressions e.g. if($_SESSION[valid_user] != $userid) do something.
You could use a select statement to retreive from MySQL the password for the specified username. If you have an empty result set, then you do not have the username in the table.
If you need the user to be authenticated in more than one php page, then one choice whould be using sessions (http://www.php.net/manual/en/function.session-start.php).
Also, I think you should think about security, i.e. preventing SQL injection:
$variable = mysql_real_escape_string($_POST['variable'])
and avoiding to "die" (treating errors and returning user-friendly messages from the script).
I would also think about not storing passwords in your database. One way hashes with MD5 or SHA1 are a way of adding a layer of security at the db level.
See http://php.net/md5 or http://php.net/sha1 for further information.
I agree with the idea if using SESSION variables while authenticating the user.
The easy way to authenticate the user is as follows
//connect the mysql_db
$mysql_connect()
$mysql_select_db()
//reading from mysql table
$res="SELECT * FROM table WHERE name=$username AND password=$password";
$val=mysql_query($res);
//authentication
$count=mysql_num_rows($val);
if($count==1)
//authenticate the user
else
through an error

Categories