I'm having the problem of mySQL not recognizing the session user when I select data from a table. Can someone please point me in the correct position on what I need to do to fix this?
$sql1="SELECT * FROM `Bookings` WHERE `username`={$_SESSION['user']}";
This is what my code looks like, but it never fetches the data and just remains blank.
First you should check if $_SESSION['user'] is initialized or has any value.
Second, it is better to assign the session user to a variable, so as to avoid some ugly issues related to escaping quotes, in the future. Don't just directly dump your session within your mysql statement.
$user_session = $_SESSION['user'];
$sql1="SELECT * FROM `Bookings` WHERE `username`= $user_session";
#Edit:
as #Dann pointed out, it's must better and safer to user prepared statement, with either the mysqli/pdo API. Here is a simple example in PDO.
First you have to connect to your database:
try {
$db = new \PDO("mysql:host=localhost;dbname=xx;charset=utf8", "xx", "xx", [
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]);
} catch(\PDOException $e){
echo "Error connecting to mysql: ". $e->getMessage();
}
Then simply fetch the booking as seen below.
$user_session = $_SESSION['user'];
try{
$stmt = $db->prepare("SELECT * FROM Bookings WHERE username = ?");
$result = $stmt->execute([$user_session]);
if($result){
// show booking
}
} catch(\PDOException $e){
echo "Counld not get user bookings. error: " . $e->getMessage();
}
Now your query is safer from mysql injection attacks, and connection errors will only throw exceptions, instead of showing potentially harmful errors.
You can use
$user=$_SESSION['user'];
$sql1="SELECT * FROM Bookings WHERE username= '$user'";
Hopefully This will solve your problem
Related
I am trying to build an override feature so users can manually remove a MySQL table row if they have the correct rights to do so. The user is prompted to input the same credentials used for program login as well as the uniqueID for the row that needs to be removed. Upon hitting the 'Submit' function, I run a series of if statements/ MySQL SELECT statements to check credentials, user rights and finally row Deletion with the result output as an alert.
However, my alert shows up blank and the row is not removed so I know there is a problem with my if statements. Upon testing, I believe the problem is when I try to use the previous query's results to run the next if statement logic.
How do I properly determine if the MySQL query returned a row using prepared statements?
All help is appreciated! Thank you!
My CODE:
if ((isset($_POST['overrideUsername'])) and (isset($_POST['overridePassword'])) and (isset($_POST['overrideUniqueID']))) {
$overridePasswordInput = $_POST['overridePassword'];
$overrideUsername = $_POST['overrideUsername'];
$overridePassword = ENCODE(($overridePasswordInput).(ENCRYPTION_SEED));
$roleID = '154';
$overrideUniqueID = $_POST['overrideUniqueID'];
//connect to the database
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if(mysqli_connect_errno() ) {
printf('Could not connect: ' . mysqli_connect_error());
exit();
}
$conn->select_db($dbname);
if(! $conn->select_db($dbname) ) {
echo 'Could not select database. '.'<BR>';
}
$sql1 = "SELECT users.id FROM users WHERE (users.login = ?) AND (users.password = ?)";
$stmt1 = $conn->prepare($sql1);
$stmt1->bind_param('ss', $overrideUsername, $overridePassword);
$stmt1->execute();
$stmt1->bind_result($userID);
//$result1 = $stmt1->get_result();
if ($stmt1->fetch()) {
$sql2 = "SELECT * FROM rolestousers WHERE (rolestousers.userid = ?) AND (rolestousers.roleid = ?)";
$stmt2 = $conn->prepare($sql2);
$stmt2->bind_param('ss', $userID, $roleID);
$stmt2->execute();
$stmt2->store_result();
if ($stmt2->fetch()) {
$sql3 = "DELETE * FROM locator_time_track_out WHERE locator_time_track_out.uniqueid = ?";
$stmt3 = $conn->prepare($sql2);
$stmt3->bind_param('s', $overrideUniqueID);
$stmt3->execute();
$stmt3->store_result();
if ($stmt3->fetch()) {
echo 'Override Successful! Please scan the unit again to close it out.';
} else {
echo 'Could Not Delete Record from the table.';
}//End $sql3 if.
} else {
echo 'User does not have override permission. Please contact the IT Department.';
}//End $sql2 if.
} else {
echo 'Your login information is incorrect. Please try again. If the issue persists, contact the IT Department.';
}//End $sql1 if.
//Free the result variable.
$stmt1->free();
$stmt2->free();
$stmt3->free();
$stmt1->close();
//Close the Database connection.
$conn->close();
}//End If statement
NOTE: I am definitely sure my DB connection information is correct. The issue resides after I connect into the database. I have also tested the code using only the first if statement and get the blank alert so I'm not making it past the first if statement.
EDIT:: My php Script was definitely failing, but even earlier than expected, at the following code:
$overridePassword = ENCODE(($overridePasswordInput).(ENCRYPTION_SEED));
So my issue is that I need to properly compare the password and encryption seed information. However, the previous programmer used the following line to do the same process (which is obviously unsafe):
$querystatement = "SELECT id, firstname, lastname, email, phone, department, employeenumber, admin, usertype FROM users WHERE login=\"".mysql_real_escape_string($user)."\" AND password=ENCODE(\"".mysql_real_escape_string($pass)."\",\"".mysql_real_escape_string(ENCRYPTION_SEED)."\")";
$queryresult = $this->db->query($querystatement);
I will need to fix this issue before I can even test the functionality of the if logic using prepared statements.
Your are passing wrong variable for delete query
$stmt3 = $conn->prepare($sql3);
Please refer [ http://www.plus2net.com/php_tutorial/pdo-delete.php ]
I'm trying to check if a user exists on the database using a form front end.
If the user is there don't add to the database.
The code isn't working when adding a user it gives me the user has been added even the user exists.
Here my code:
<?php
$connection = mysql_connect("localhost", "dbuser", "dbpasswd"); // Establishing Connection with Server
$db = mysql_select_db("ldap", $connection); // Selecting Database from Server
if(isset($_POST['submit'])){ // Fetching variables of the form which travels in URL
$netid = $_POST['netid'];
$univid = $_POST['univid'];
if($netid !=''||$univid !=''){
//Insert Query of SQL
$query = mysql_query("SELECT FROM user ( UserName, temppass WHERE UserName=$netid");
if(mysql_num_rows($sql)>=1)
{
echo"NetID $netid already exists";
}
else
{
//insert query goes here
$query = mysql_query("insert into user( UserName, temppass ) values ('$netid', '$univid')");
}
echo "<br/><br/><span>User Registered successfully...!!</span>";
}
else{
echo "<p>Registration Failed <br/> Some Fields are Blank....!!</p>";
}
}
mysql_close($connection); // Closing Connection with Server
?>
You could do something like:
$query = mysql_query("SELECT COUNT(UserName) as total FROM user;");
Then
$result = mysql_fetch_assoc($query);
The count of users will be in $result['total']. As an aside the mysql_* methods are inferior to prepared statements (google it).
Your select query has many errors with it.
SELECT FROM user ( UserName, temppass WHERE UserName=$netid
First issue you aren't selecting anything. Second issue I don't know what ( UserName, temppass is, maybe the columns you want to select? Third issue is that Username is presumably a string, not an integer, so that value should be in quotes. Once you quote that though you will open yourself to SQL injections.
Here is a valid version of your current query.
SELECT UserName, temppass FROM user WHERE UserName='$netid'
Here's the doc on mysql's select: http://dev.mysql.com/doc/refman/5.7/en/select.html
Here are some links to read up on about SQL injections:
How can I prevent SQL injection in PHP?http://php.net/manual/en/security.database.sql-injection.php
You also shouldn't be using the mysql_ functions they are deprecated and insecure now. Why shouldn't I use mysql_* functions in PHP?
Additional issues:
if(mysql_num_rows($sql)>=1)
The $sql isn't defined.
I don't know what $_POST['netid'] is but that sounds like an id, not a username.
You shouldn't store passwords in plain text.
You should enable error reporting and/or monitor your error logs.
So I'm new to php and mysql and over the past few days have created a log in system using php and mysql. I am trying to make a function where a user can change their password with the following query:
$query2 = mysql_query("SELECT password FROM adminusr WHERE id =$idToChange");
$result = mysql_query($query2) or die($idToChange.mysql_error());
With SELECT statements you only select rows. To change them you need UPDATE. Consider using PDO because mysql_* functions are deprecated. Also try to hash your passwords and don't store them in plain text.
You need something like this:
$query2 = mysql_query("UPDATE adminusr SET password = '$new_password' WHERE id = '$idToChange'");
Using PDO
//Make the connection using PDO
try {
$conn = new PDO("mysql:host=$hostname;dbname=mysql", $username, $password);
echo "PDO connection object created";
}
catch(PDOException $e) {
echo $e->getMessage();
}
//Make your query
$sql = 'UPDATE adminusr SET password = :new_password WHERE id = :id';
$stmt = $conn->prepare($sql);
$stmt->execute(array(':new_password'=>$new_password, ':id'=>$idToChange));
EDIT answering to comment
Then you need to have also username and password fields at your form. So, you need four fields: username, oldPassword, newPassword, confirmNewPassword. Before the update statement you need to select the user having credentials username, oldPassword. If you find only one then you have to check if newPassword and confirmNewPassword match. If match then proceed to update. Otherwise print some error message.
I have a users table where I want to update the scores each time a user finishes the game. Unityscript part is working fine but after I post the score to the database it appears doubled or tripled. I post the score as int and also the table column is of int format. My PHP looks like this:
try {
$db = new PDO("mysql:host=$host;dbname=$dbname", $db_user, $db_pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$data = array(
':username' => $_POST['username'],
':score' => $_POST['score']);
$statement = $db -> prepare ("UPDATE users SET score = score + :score
WHERE username = :username");
$statement->execute($data);
}
catch(PDOException $e) {
echo $e->getMessage();
}
Any help or advice is appreciated.
You are using prepared statements, but you are still allowing injection by directly implementing the $score variable. Do the same thing with score that you did with username.
What do you mean by double or triple? Do you mean that the number is two or three times bigger? If so, try using a SELECT statement to fetch the score and do the math in PHP. Then, UPDATE the users table.
Doing this will allow you to better understand what you are doing wrong. Have you tried echoing the value of score within your try and catch to see if the value repeats? The code may be running more than once.
$statement = $db -> prepare ("UPDATE users SET score = :score
WHERE username = :username");
use this, i think it will work
another day another question...
I need to write PHP script to update mySQL database.
For example: updating profile page when user want to change their first name, last name or etc.
Here is my php script so far, it doesn't work. Please help!
<?php
# $db = new MySQLi('localhost','root','','myDB');
if(mysqli_connect_errno()) {
echo 'Connection to database failed:'.mysqli_connect_error();
exit();
}
if (isset($_GET['id'])) {
$id = $db->real_escape_string($_GET['id']);
$First_Name2 = $_POST['First_Name2'];
$query = "UPDATE people SET $First_Name2 = First_Name WHERE `Id` = '$id'";
$result = $db->query($query);
if(! $result)
{
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully\n";
$db->close();
}
?>
THank you.
Your sql is wrong. Apart from the gaping wide open SQL injection attack vulnerability, you're generating bad sql.
e.g. consider submitting "Fred" as the first name:
$First_Name2 = "Fred";
$query = "UPDATE people SET Fred = First_name WHERE ....";
now you're telling the db to update a field name "Fred" to the value in the "First_Name" field. Your values must be quoted, and reversed:
$query = "UPDATE people SET First_name = '$First_Name2' ...";
You are also mixing the mysqli and mysql DB libraries like a drunk staggering down the street. PHP's db libraries and function/method calls are NOT interchangeable like that.
In short, this code is pure cargo-cult programming.