Sorry I'm beginner in PHP MYSQL.
I want to ask how this will work. May I know how to fix this or what code will I add?
Scenario:
We have user type ADMIN and NORMAL USER,
I created edit.php to edit user accounts as an ADMIN incase of lost password etc. but I have problem was when I click Edit button in specific table.
See Picture Below, I logged in here as an Admin, employee.php.
So I choose the user testFN with the id of 22
The code I used here to fetch the id is here :
<td><a href="edit.php?id=<?php echo $row['user_id']; ?>" >Edit</a></td>
When I click the EDIT button it will open the page edit.php, with this url
So I the outcome is not equal to what I want, the information to the input boxes were from the user I'm using/logged in not from the user I chose to edit.
The code I used to EDIT.PHP is here:
<?php
session_start();
include_once 'dbconnect.php';
if(!isset($_SESSION['user']))
{ header("Location: edit.php"); }
$res=mysql_query("SELECT * FROM accounts WHERE user_id=".$_SESSION['user']);
$userRow=mysql_fetch_array($res);
if(isset($_GET['user'])) {
$id = $_GET['user'];
if(isset($_POST['submit'])) {
$pass = md5(mysql_real_escape_string($_POST['pass']));
$aFName = mysql_real_escape_string($_POST['aFName']);
$aLName = mysql_real_escape_string($_POST['aLName']);
$aMName = mysql_real_escape_string($_POST['aMName']);
$aContact = mysql_real_escape_string($_POST['aContact']);
$aAddress = mysql_real_escape_string($_POST['aAddress']);
$aGender = mysql_real_escape_string($_POST['aGender']);
$utype = mysql_real_escape_string($_POST['utype']);
$query3=mysql_query("UPDATE accounts SET pass='$pass', agentFName ='$aFName', agentLName = '$aLName',
agentMName = '$aMName', agentContact = '$aContact', agentAddress = '$aAddress',
agentGender = '$aGender', user_type = '$utype' ");
if($query3)
{ header("Location: home.php"); }
}//end of post sumbit
}//end of GET
?>
/** HTML IS HERE **/
Agent ID: <input type="text" id="agentCode" name="agentCode" required="required" value="<?php echo $userRow['user_id']; ?>" >
First Name: <input type="text" id="agentCode" name="aFName" required="required" value="<?php echo $userRow['agentFname']; ?>" >
Middle Name: <input type="text" id="agentCode" name="aMName" required="required" value="<?php echo $userRow['agentMname']; ?>" >
Last Name: <input type="text" id="agentCode" name="aLName" required="required" value="<?php echo $userRow['agentLname']; ?>" >
This is where you set the value for that text input:
value="<?php echo $userRow['user_id']; ?>"
Where does $userRow come from? This:
$userRow=mysql_fetch_array($res);
What query was used to fetch the data? This:
$res=mysql_query("SELECT * FROM accounts WHERE user_id=".$_SESSION['user']);
So... you're specifically fetching the data from the logged-in session user, rather than the one specified on the query string. Just use the query string value instead of the session value.
Important:
Using user-supplied values directly in SQL queries is called a SQL injection vulnerability. It's a very bad thing. You're going to want to use query parameters and prepared statements. This is a good place to start reading.
You're really going to want to check if the logged-in user is authorized to edit the specified user before allowing them to do so. Any user can manually add/change query string values or POST values or basically anything that comes from the client.
Related
I have a HTML form with a textbox where you enter a username, and a login button. When the user presses the login button, I want the database to be queried and if there is a match echo out a statement. The code I have is this:
<form class="login_box" method="POST">
<input id="input-boxes1" type="text" name="username" value="" placeholder="Username">
<input id="button-1" type="submit" name="login" value="Login">
</form>
// Checks if login button is pressed
if (isset($_POST['login'])) {
$enteredUser = $_POST['username'];
$sql = "SELECT * FROM user WHERE username='$enteredUser'";
if ($result = mysqli_query($link, $sql)) {
echo 'it works';
}
}
What I want it to do is echo out "it works" if there is a match. However it always echoes it out no matter what. The database is working as intended as I have added to it and selected from it in other files, and the database is correctly linked to this form as well.
Any help would be great, thanks!
Thank you to #El_Vanja and #droopsnoot for helping. I've managed to figure out the solution now. As they rightly pointed out, I had to see if the number of rows returned was 1 and then echo out the statement if so.
My amended code is as below:
if (isset($_POST['login'])) {
$enteredUser = $_POST['username'];
$sql = "SELECT * FROM user WHERE username='$enteredUser'";
$result = mysqli_query($link, $sql);
if (mysqli_num_rows($result) == 1) {
echo 'it works';
}
}
I have been looking for 3 weeks on the Internet for an answer to this question and cannot find anything that even comes close or in handy. I have a Database Table that i need to have checked. If a Users_ID is present in that table, I would like my code to display an update.php link in my form action="" tag and if the Users_ID is not present in that db table, then i would like to have an Insertdb.php page to be linked in the form instead of an update.php page. Here is what I have:
PHP Code:
<?php
session_start();
error_reporting(E_ALL);
include_once("dbconnect.php");
$users_id = $_SESSION['user_id'];
$sql = "SELECT * FROM dbtable WHERE uid=$users_id";
if($results = $con->query($sql)) {
while($display = $results->fetch_array(MYSQLI_ASSOC)) {
$uid = $display['uid'];
if($display['uid']==""){
$pagelink = "insertintodb.php";
}else{
$pagelink = "updatedb.php";
}
}
$results->close();
}
?>
And my HTML section looks like this:
HTML Code:
<form action="<?php echo $pagelink; ?>" method="POST">
<input type="text" value="" placeholder="Insert Value" name="something" />
<input type="submit" value="Submit Data" name="submit_data_to_db" />
</form>
How would I go about doing this? My current method Posted above is what I'm currently using, however its displaying only <form action="" method="POST"> when i check it against the pages view-source. Please help me anyway you can. Any and all help would be greatly appreciated. Thank you
you usually use num_rows method:
<?php
session_start();
error_reporting(E_ALL);
include_once("dbconnect.php");
$users_id = $_SESSION['user_id'];
$sql = "SELECT * FROM dbtable WHERE uid=$users_id";
if($results = $con->query($sql)) {
if($results->num_rows() > 0){
$pagelink = "insertintodb.php";
}else{
$pagelink = "updatedb.php";
}
}
$results->close();
}
?>
I see you use $con but I see nowhere you have declared it.
Can you confirm that actually exists? It is possible your script is halting its execution at that point.
Also a few things I would implement in there:
1. When you use variables that come from external sources (like your forms), or even other variables really, always care for SQL injection;
2. Your if & else can be reduced to just an if (when you find an ID). To all others case, you wish a default behaviour that is your else. So something like this:
$pageLink = "insertintodb.php";
if (!empty($display['uid'])) {
$pageLink = "updatedb.php"
}
I'm new to php.
I have this page:
<?php
function renderForm($id, $StaffFullName, $StaffJobPosition, $error)
{
?>
<!doctype html>
<html>
<head><title></title></head>
<body>
<?php
// if there are any errors, display them
if ($error != '')
{
echo '<div>'.$error.'</div>';
}
?>
<form action="" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<div>
<p>ID: <?php echo $id; ?></p>
Name: * <input type="text" name="StaffFullName" value="<?php echo $StaffFullName; ?>"/><br/>
Job Position: * <select name="JobPosition">
<?php
$query = "SELECT * FROM LUT_JOBPOS";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result)){
if ($StaffJobPosition == $row['JobposID'])
{
echo "<option value='{$row['JobposID']}' selected='selected'>{$row['JobposTitle']}</option>";
}
else {
echo "<option value='{$row['JobposID']}'>{$row['JobposTitle']}</option>";
}
}
$result->close();
?>
</select><br/>
<input type="submit" name="submit" value="Update">
<input type="button" onClick="parent.location='view.php'" value="Back">
</div>
</form>
</body>
</html>
<?php
}
// connect to the database
require_once('../../authenticate.php');
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// do some funky stuff
}
else
// if the form hasn't been submitted, get the data from the db and display the form
{
// get the 'id' value from the URL (if it exists), making sure that it is valid (checking that it is numeric/larger than 0)
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// query db
$id = $_GET['id'];
$query = "SELECT * FROM STAFF WHERE StaffID=$id";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_assoc($result);
$result->close();
// check that the 'id' matches up with a row in the database
if($row)
{
// get data
$StaffFullName = $row['StaffFullName'];
$StaffJobPosition = $row['StaffJobPosition'];
// show form
renderForm($id, $StaffFullName, $StaffJobPosition, '');
}
else
// if no match, display result
{
echo "No results!";
}
}
else
// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
{
echo 'Error!';
}
}
?>
So, what happens here is this:
When you open the page like edit.php?id=1, it fetches the data of the associated record from STAFF table and shows them on page for the user to edit them.
This part of the code works fine.
I also want the user to be able to select "Job Position" possible values from a drop down box. The drop down box should get its data from another table in database, LUT_JOBPOS.
This is the part of the code that doesn't work.
I was using mysql_query commands before on this page and it worked perfectly. However I was told to switch on mysqli_query instead.
Since I did the conversion I can't find how to run these two queries on the same script.
I messed a little bit with the require_once command and depending on where I call it I can run one query or another, but never both of them.
Looking at the logs of my web host the only thing I can see that may be relevant to my issue is:
"mod_fcgid: stderr: PHP Notice: Undefined variable: connection in /var/www/vhosts/myhostdomain.com/httpdocs/prod15/admin/staff/edit.php on line 24"
The connection variable comes from authenticate.php and it holds the connection parameters to the database. I'm sure it's set otherwise the first query (that gets the user data) wouldn't work.
I read somewhere that you can't run two sqli queries on the same script.
Then how I'm supposed to use a LUT table (lookup table)?
PS: I know that for showing the data I can use a UNION and that's what I do.
But when I edit the data I want the user to be able to select only from the possible values that exist on the LUT table (drop down select box)
Any help?
You have a lot of issues in your code. You really need to review it before use it in some real application, but for your specific problem, here is my guess.
You are calling the line $result = mysqli_query($connection, $query); in the line 24 and only after taht you call require_once('../../authenticate.php');.
As you said, the $connection var is defined in the authenticate.php, so in the line 24 is undefined.
Try to use require in the first line of your php script.
I am new to php coding and the SOF community so please bear with me. I have a functioning sign up system (wired to a database) and somewhat functional login form but how may I be able to make both sessions of the forms display/use the first name of the associated account?
More clarification: Login with email and password, you go to the home page where the system addresses you by your first name. When you sign up, you are directed to another page with the system addressing you by your fist name.
I would assistance on the login part so here are the relevant codes:
Login form (on a header php; separate from my index and registration variables) :
<form action="index.php" method="POST">
<input type="email" name="email_login" size="50" placeholder="Email" /><br /><br /><br />
<input type="password" name="pass_login" size="50" placeholder="Password" /><br /><br /><br />
<input type="submit" name="login" id="login" value="LOG IN">
</form>
Login Code (on index.php with registration form/code and registration variables):
if(isset($_POST['email_login']) && isset($_POST['pass_login'])) {
$email_login = mysqli_escape_string($con, $_POST['email_login']);
$pass_login = mysqli_escape_string($con, $_POST['pass_login']);
$pass_login = md5($pass_login);
$logquery = "SELECT id FROM users WHERE email='$email_login' AND password='$pass_login' LIMIT 1";
$sqli = mysqli_query($con, $logquery);
$userCount = mysqli_num_rows($sqli); // Count number of rows returned
if ($userCount == 1) {
while( $row = mysqli_fetch_array($sql)) {
$id = $row["id"];
}
$_SESSION["email"] = $fname;
header("location: home.php");
exit();
}
Finally, the home.php; where I want registered users to be directed to upon successful login:
<?php session_start();
include ( "./inc/connect.inc.php");
echo $_SESSION["email"];
?>
Sorry if anything is considered as bloat. Thank you.
You need to start the session using session_start() anywhere you want to WRITE or READ session variable.
Simply add session_start() at the top of your index.php file.
Also make sure not output has been set before the session starts or you will get an error.
First you must start session on the top of every single page (before any other output) where you would read or write session variable adding
this =>session_start() and also in your code you set $_SESSION['email'] with a variable ($fname) which was not set (Maybe you forget to retrieve $fname from the the database) You can do it by editing your query
Update
Try this query
$logquery = "SELECT id, first_name FROM users WHERE email='$email_login' AND password='$pass_login' LIMIT 1";
Then
$sqli = mysqli_query($con, $logquery); $userCount = mysqli_num_rows($sqli); // Count number of rows returned
if ($userCount == 1) {
while( $row = mysqli_fetch_array($sql)) {
$id = $row["id"];
$_SESSION["first_name"] = $row["first_name"];
}
}
header("location: home.php"); exit();
Then in your home.php
<?php session_start();
include ( "./inc/connect.inc.php");
echo $_SESSION["first_name"]; ?>
I am trying to check if a user is the owner of a profile page so that i can display a text box for entering twitter similar posts.
The code
$id=mysql_query("SELECT id FROM users WHERE`username`='".$_GET['username']."'");
$ultimatum_form ='';
if(isset($_SESSION['id'])){
if($_SESSION['id']==$id){
$ultimatum_form = 'Write an ultimatum!(220 char max)<br/>
<form action="profile.php" method="post" enctype="multipart/form-data" name="ultimatum_form">
<textarea name="ultimatum_field" rows="3" style="width:97%;"></textarea>
</form>';
}
}
print "$ultimatum_form";
in my DB i have a table called "users", the table users has the columns "firs", "last", "username", "password", "email" and "id".
If i set $ultimatum_form outside of the session check it outputs the text-field and it works. The problem is that if i then go to another persons profile i can see the text-field and write posts for them.
You need to get data from the query:
$id=mysql_query("SELECT id FROM users WHERE`username`='".$_GET['username']."'");
$r = mysql_fetch_assoc($id);
$id = $r['id'];
then $id contains the row "id" value.
look into pdo/mysqli, mysql won't wrok in next php version.
here, better:
$id=mysql_query("SELECT id FROM users WHERE`username`='".$_GET['username']."'");
$r = mysql_fetch_assoc($id);
$id = $r['id'];
if(isset($_SESSION['id']))
{
if($_SESSION['id']==$id)
{
echo '
Write an ultimatum!(220 char max)<br/>
<form action="profile.php" method="post" enctype="multipart/form-data" name="ultimatum_form">
<textarea name="ultimatum_field" rows="3" style="width:97%;"></textarea>
</form>';
}
else
{
// Not users profile page
}
}
You can't exactly do what you're doing. You need to fetch the records.
$results = mysql_fetch_array(mysql_query("SELECT id FROM users WHERE`username`='".$_GET['username']."'"));
Then you can do:
if($_SESSION['id']==$results['id']){