Inserting username into table - PHP - php

I'm trying to make a simple auction website. I need to keep track of the user that adds items to the auction. I've figured out how to store the user's account id and I thought storing the username would be similar, but I am unable to work it out. No matter what I've tried, the username is never stored in my items table.
This is my additemprocess.php page.
<?php session_start(); ?>
<html>
<head></head>
<body>
<?php
require_once("dbconnect.inc");
$_SESSION['username']=$_POST['username'];
$item=$_POST['item'];
$description=$_POST['description'];
$accountid=$_SESSION['accountid'];
$sql= "INSERT INTO biditems (username, accountid, biditem, biddesc) VALUES
('{$_SESSION['username']}', '$accountid', '$item', '$description')";
$result=mysql_query($sql) or die("Error in adding item: " .mysql_error());
$mess="Item successfully added!";
echo $mess;
?>
And here is the page that should list the items, showing the username of the user that added the item.
<?php
session_start();
require_once("dbconnect.inc");
require_once("checkstatus.inc");
$sql=" select * from biditems";
$result=mysql_query($sql);
echo "Items for Auction";
while($row=mysql_fetch_array($result)) {
$itemid=$row['itemid'];
$item=$row['biditem'];
$auctionby=$row['username'];
$description=$row['biddesc'];
echo "<p>$itemid $item $auctionby $description</p>";
}
?>
Here is my code to add an item.
<?php
session_start();
require_once("dbconnect.inc");
?>
<form id="additem" name="additem" method="post" action="additemprocess.php">
Item<br>
<input type="text" name="item" id="item"/><br>
Description<br>
<textarea name="description" id="description"></textarea><br>
<input type="submit" name="submit" id="submit" value="submit"/>
</form>

You are currently using $_SESSION['username']=$_POST['username']; but you need to treat this username like the accountid. It should have been stored when you login in a session, then recalled when you enter the bid data in its database.
So for example:
On login :
$_SESSION['username']=$_POST['username'];
And on storing the bid:
$username = $_SESSION['username'];
or alternatively get the username from the users table using the accountid then add it to the query that way like:
$username = $row['username'];
Additionally, if you tried this but had trouble sharing this data between pages using sessions, then make sure you are including session_start(); on the top of each page where you are going to use sessions.

The problem is at: $_SESSION['username']=$_POST['username'];, you're setting a session to a post which doesn't even exist..? Set the $_SESSION['username']; in the process of logging in.
So on the spot where you are setting the $_SESSION['accountid'] equal to the ID of the currently logged in account using something like: $_SESSION['accountid'] = $row['id'];.
Right under there you'll add $_SESSION['username'] = $row['username'];.
Then just delete the $_SESSION['username'] = $_POST['username']; at your adding item process.
ANOTHER NOTICE: Do not use MySQL anymore since it's deprecated in versions of PHP5 or higher due safety reasons. Try using MySQLi (MySQL improved or PDO): php.net/manual/en/mysqlinfo.api.choosing.php

Related

How to restrict update or insert more than once by navigating back to referring page in php?

I am developing a web application where I want to restrict update or insert more than once by navigating back to referring page. Let me present you three model files in the order of flow so that I can raise the zone where I am stuck.
register.html
<html>
...
<form id="form1" name="form1" method="post" action="process.php">
<label for="textfield">Name</label>
<input type="text" name="name" id="name" />
<input type="submit" name="Submit" value="Submit" />
</form>
...
</html>
process.php
<?php
echo "Welcome ".$_GET['para'];
?>
success.php
<?php
if(isset($_POST['Submit']))
{
$name = $_POST['name'];
// some database update here ...
echo "<a href='success.php?para=$name'>Done. Click to go next</a>";
unset($_POST['Submit']);
}else{
echo "Error in submission";
}
?>
The above three files are very simple. Here the update part has nothing to do when the user hits the back button after landing on page success.php because of unset($_POST['Submit']);. But when the user goes back further by hitting the back button again it reaches register.html and can again come up with the $_POST['Submit'] set and may do the update part which is sometimes vulnerable. I know there is Post/Redirect/Get to solve this issue, but I want some other alternatives so that the part gatekeepering the update part may be made so efficient that it would not allow the same anymore by clicking the back button.
If you are getting duplicate records inserted.
You may try INSERT IGNORE
ADD UNIQUE INDEX to your table to prevent this happening
you may choose any one of INSERT IGNORE and REPLACE according to the duplicate-handling behavior
Refer https://dev.mysql.com/doc/refman/5.5/en/insert-on-duplicate.html
Lastly you may like simple php with mysqli_num_rows()
$sql = "SELECT id FROM table-name WHERE column-name1 = ? AND column-name2 = ? ;
$mq = mysqli_query($sql);
if (mysqli_num_rows($mq) < 1) {
$sql = "UPDATE table-name SET (colum-names) VALUES (...)";
mysqli_query($sql);
else {
echo "Record already updated";
}
}

Using login data to make operations in other pages

I have a homework which is creating a web page which user can share photos or texts in their profile. But I am stuck at using login information to do it.
Here is my login.html:
<form method="post" action="login.php">
<br><label for="username">Username:</label></br>
<input type="text" id="username" name="username">
<br><label for="password">Password:</label></br>
<input type="password" id="password" name="password">
<div id="lower">
<br><input type="submit" value="Login"></br>
<p>
Not yet registered?
Click here to register
</p>
</div><!--/ lower-->
</form>
and here is my login.php:
?php
$con=mysqli_connect("localhost","root","","webpage");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$username = $_POST['username'];
$password = $_POST['password'];
$sql=mysqli_query($con,"SELECT * FROM user WHERE username='$username' and password='$password'");
if (!mysqli_fetch_assoc($sql)) {
die("You entered wrong username/password.");}
while ($sql){
$sql2="SELECT * FROM user WHERE username='$username' and approval = 1";
$res = mysqli_query($con,$sql2);
if (!$res) {
echo "Your account isn't approved yet. Please wait for approval. Thanks :)";}
else echo 'You have succesfully logged in.';
header('Location: http://localhost/project2/redirect.html');
}
mysqli_close($conn);
?>
From here, I am stuck. I don't know what to do to use the username that the user has entered. What am I suppose to do?
Thanks.
You can set the username in session which can be used till the session is cleared..ie till the user logs out or close the browser
A session is a way to store information (in variables) to be used
across multiple pages.
Unlike a cookie, the information is not stored on the users computer.
By default, session variables last until the user closes the browser.
Thus, Session variables hold information about one single user, and are available to all pages in one application.
A session is started with the session_start() function.
Session variables are set with the PHP global variable: $_SESSION.
To Set Session variables
<?php
// Start the session
session_start();
$username = $_POST['username'];
// Set session variables
$_SESSION["uname"] =$username;
?>
To Get Session variable's value
<?php
session_start();
$username =$_SESSION["uname"];
?>
To Destroy the Session
<?php
// remove all session variables
session_unset();
// destroy the session
session_destroy();
?>
Cookies! Yum!
http://www.w3schools.com/js/js_cookies.asp
Do some research here, try it out, and come back if you still can't get it.

Script to update users value in data base not working – issue with sessions?

I’m pretty much a complete beginner when it comes to PHP and have been having some problems with my script to update the current users values in the database – when the script fires it doesn’t update the value in the database as intended at all.
Some background info:
Database name: “user”
Table “users” with columns User ID , Username , Password , Emailaddress , Offer.
Site that I’m working on allows users to complete a number of offers and then get rewarded upon completion. The offer column has the default value of “1”. Upon login the user is redirected according to the value in the offer column. (So on first login user is redirected to example.com/offer1 , after offer 1 is completed this value is updated so on next login user is redirected to offer 2 – in essence storing the users progress) This login process works fine , its just updating the value which is my problem.
This is the script which is played after an offer is completed (in this case after offer 3 is completed) – aim to connect to database and then update that users “offer” so when they next login they will be directed to the correct offer – thus storing their progress:
~Could this actually not be a problem with the Script its self but in regards to sessions not starting/continuing correctly upon login – or maybe an issue with the script not using the session data correctly?~
<?php
session_start();
$con = mysqli_connect("localhost","name","password","user");
$select = mysqli_fetch_assoc(mysqli_query($con,"SELECT offer FROM user WHERE Username = '".$_SESSION['username']."'"));
$plus = $select['offer']++;
mysqli_query($con,"UPDATE users SET offer=3".$plus."where user_id = $id" );
header("location: http://example.com/offer4".$plus);
?>
The mysqli_query($con,"UPDATE users SET offer=3".$plus."where user_id = $id" ); isn't working at all, could the issue be here?
In case it helps , this is a previous version I was using which did work in updating the values but does so for all users in the database rather than just the one user who is logged in. So lets say Jim has completed this offer , his Offer value will be updates to 3 but so will all the other users will have their offer value set to 3 when only Jim’s should be.
<?php
session_start();
$con = mysqli_connect("localhost","username","pass","user");
$select = mysqli_fetch_assoc(mysqli_query($con,"SELECT offer FROM users WHERE Username = '".$_SESSION['username']."'"));
$plus = $select['offer']++;
mysqli_query($con,"UPDATE users SET offer=3".$plus);
header("location: http://example.com/offer4".$plus);
?>
Just for reference here is my login script – this works correctly in redirecting user upon login to value in their Offer column (could my problem be to do with sessions not starting correctly?)
<?php include "base.php"; ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Login</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<div id="main">
<?php
if(!empty($_POST['username']) && !empty($_POST['password']))
{
$username = mysql_real_escape_string($_POST['username']);
$password = md5(mysql_real_escape_string($_POST['password']));
$checklogin = mysql_query("SELECT * FROM users WHERE Username = '".$username."' AND Password = '".$password."'");
if(mysql_num_rows($checklogin) == 1)
{
$row = mysql_fetch_array($checklogin);
$email = $row['EmailAddress'];
$_SESSION['Username'] = $username;
$_SESSION['EmailAddress'] = $email;
$_SESSION['LoggedIn'] = 1;
echo "<h1>Success</h1>";
echo "<p>We are now redirecting you to the member area.</p>";
echo '<meta http-equiv="refresh" content="0;URL=\'http://example.com/offer'.$row['offer'].'\'" />';
}
else
{
echo "<h1>Error</h1>";
echo "<p>Sorry, your account could not be found. Please click here to try again.</p>";
}
}
else
{
?>
<h1>Member Login</h1>
<p>Thanks for visiting! Please either login below, or click here to register.</p>
<form method="post" action="index.php" name="loginform" id="loginform">
<fieldset>
<label for="username">Username:</label><input type="text" name="username" id="username" /><br />
<label for="password">Password:</label><input type="password" name="password" id="password" /><br />
<input type="submit" name="login" id="login" value="Login" />
</fieldset>
</form>
<?php
}
?>
</div>
</body>
</html>
Lastly, heres base.php
<?php
session_start();
$dbhost = "localhost"; // this will ususally be 'localhost', but can sometimes differ
$dbname = "user"; // the name of the database that you are going to use for this project
$dbuser = "name"; // the username that you created, or were given, to access your database
$dbpass = "password"; // the password that you created, or were given, to access your database
mysql_connect($dbhost, $dbuser, $dbpass) or die("MySQL Error: " . mysql_error());
mysql_select_db($dbname) or die("MySQL Error: " . mysql_error());
?>
Thank you very much for your time and have a good evening ; very much appreciate all the previous replies here that have been so helpful.
Try this:
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
session_start();
if(!empty($_SESSION['Username'])) {
$con = mysqli_connect("localhost","username","pass","user");
$username = mysqli_real_escape_string($con, $_SESSION['Username']);
$result = mysqli_query($con, "UPDATE users SET Offer = Offer + 1 WHERE Username = '{$username}'");
while ($row = mysqli_fetch_assoc($result)) {
$offer = $row['Offer'];
}
header("Location: http://example.com/offer".$offer);
} else {
echo "You are not logged in.";
}
mysqli_real_escape_string will escape dangerous characters from the username. You can use an UPDATE to increment a cell's value by an amount (in this case 1).
Another thing to note: In the PHP on the page with the HTML, you are using mysql extension functions instead of mysqli. The mysql extension is deprecated. Either way, your code is inconsistent in the use of mysql and mysqli. For a list of equivalent mysqli functions, check the PHP manual.
You said your database was called user and your table users. In your first query statement, you selected offer from a table called user not users. You can use mysqli_error() to display errors, which you would have received.
Regarding your second mysqli_query statement:
mysqli_query($con,"UPDATE users SET offer=3".$plus."where user_id = $id" );
There is no $id anywhere else in your code. Also you need a space before your where, otherwise if $plus == 13, the statement reads SET offer=313where user_id....
According to your code ($select['offer']++), you retrieve the previous offer value, increment it by 1 and then set the offer value in the database to this incremented value with a 3 added on to the beginning.
If offer == 31, then after going through your code, the new offer == 332.
EDIT: Something else I just noticed. I think you are misunderstanding the ++ operator. When used after an operand, it is called the post-increment operator. When used before, it is called the pre-increment operator. The reason for this is because in the case of the post-increment operator, the value of the operand (in your case $select['offer']) is assigned to $plus before it is incremented. What this means, in the context of your code, is that you are never actually incrementing the offer value.
I think the problem is with this line:
mysqli_query($con,"UPDATE users SET offer=3".$plus."where user_id = $id" );
Where is $id coming from? In the line above, you used username.
Your SQL is "UPDATE users SET offer=3".$plus."where user_id = $id". In PHP with $plus variable equal, e.g. "54" this becomes "UPDATE users SET offer=354where user_id = $id". So, a space is missing before where.
If this is not the case, learn to use mysqli error logging: http://php.net//manual/ru/mysqli.error.php.

Retrieve all record and insert to another table form another db

I have troubles about php & mysql. I've to retrieve all records from DB1's table and then I have to insert them again to DB2's table.
<?php
require_once 'includes/config.php';
include 'includes/header.php';
if(isset($_POST['go'])){
$query = mysql_query("SELECT id,username,password FROM $db_database1.account")
or die(mysql_error());
echo "Record ".mysql_num_rows($query)." retrieve";
while($result_row = mysql_fetch_array($query, MYSQL_ASSOC)){
$account_ID = $result_row['id'];
$username = $result_row['username'];
$password = $result_row['password'];
$query = mysql_query("INSERT INTO $db_database2.account(uid,username,password) VALUES('$account_ID','$username','$password')")
or die(mysql_error());
$selectId = mysql_insert_id();
}
}
mysql_close($conn);
?>
<div class="wrapper">
<div class="content">
<form method="post" action="<?PHP $_SERVER['PHP_SELF'];?>">
<input type="submit" name="go" value="Go" />
</form>
</div>
<?php include 'includes/footer.php';?>
According to this code just one record was inserted. How can I insert all retrieved records?
To insert records into another table you need one single query, run from mysql console without PHP:
INSERT INTO db_database2.account SELECT id,username,password FROM db_database1.account
Notes on your code
you have to escape strings you are adding to the query
for some reason you are inserting into the same database
asking for the mysql_insert_id() makes no sense as you are apparently inserting a_i id already
there is no use for storing second mysql_query result into variable
yet this variable gets overwritten <- here is the reason your code runs once.
there is no use for echoing $_SERVER['PHP_SELF'] here. just leave form action blank.
yet you are actually leaving form action blank as you just forgot to echo this variable
I see no use for all the form and HTML here. Can't you just run this code without forms?
as it seems that whole mess is just to hash passwords, you need no extra tables then
just simple
UPDATE account SET password = md5(concat(id,username,password));
always have a database backup before such manipulations

How to edit the user information by admin

I am developing my first simple website using PHP. Now, I am working in the admin page and I want to let him adding, deleting users and editing the personal information of the existed users. I did the adding and deleting. Now, I want to develop editing users. First of all, I want him to choose the user from drop list, then fetch the user information automatically after choosing him from the drop list, and after that editing his information. So how can I do that?
My code:
<?php
ob_start();
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="13524"; // Mysql password
$db_name="sharingi_db"; // Database name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script language="javascript">
function reload(form){
var val=form.username.options[form.username.options.selectedIndex].value;
self.location='editUser2.php?username=' + val ;
}
</script>
</head>
<body>
<div id="content_main" class="admin_student_height">
<!-- Here starts the first form -->
<form method="get">
<h3>Choose A User</h3> <br />
select name="username" onchange="reload(this.form)">
<option>
<?php
if(isset($_GET['username']))
echo "{$_GET['username']}";
else echo "Select one";
?>
</option>
<?php
if(isset($_GET['username'])){
$exceptcc = $_GET['username'];
$sql = "SELECT username FROM user WHERE user.username NOT IN
('$exceptcc')";
}
else
$sql = "SELECT username FROM user";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)){
echo "<option value={$row['username']}>{$row['username']}</option>";
}
?>
</select><br /><br />
<h3>User Information</h3> <br />
<?php
$thecc = $_GET['username'];
$sql = "SELECT Firstname FROM user WHERE Username=$thecc";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)){
echo "{$row['Firstname']}>{$row['Firstname']}}";
}
?>
<br /><br />
</form> <br />
</div>
</div>
</body>
I've been working on making a web-based ticketing system and ran into this same situation.
I solved the problem like this:
When the page is loaded, determine if they have admin rights or throw them off the page.
Do an SQL Query to get the List of users, to either display in a list or in a drop down box.
Once the User to edit has been selected, Do another Query and load each item into a field;
what I did was use the same form for adding new users but have php build the form and insert the current values for that user into the fields.
When this form is submitted, (and submitter verifed) I have the php script look at the submitted username and use that for the where clause in the sql update statement
If you want me to post up an example of what I did I can do that.
You are only echo'ing the user's information.
Instead, you need to put the information into a form, which will allow for editing.
<?php
if ($_POST['submit']) {
$username = $_POST['username'];
//if you want to update
mysql_query("UPDATE users SET username = '$username', password = '$password'");
//if you want to delete
mysql_query("DELETE FROM users WHERE username = '$username'");
}
?>
<?
//show all users
$user_query = mysql_query("SELECT * FROM users");
while($row = mysql_fetch_array($user_query)) {
echo $row['username'] . ' ' . $row['first_name'] . ' ' . $row['last_name'];
//and so on.. depending on your table fields
}
?>
<form method="POST">
Username: <input name="name" value="<?echo $row['username'?>"/>
<input type="submit" name="submit"/>
</form>
Load data into your form, and add action to it like "save_user.php
On that page save_user.php get data from $_POST, $_POST["firstName"] where firstName is name of your text field where you have loaded data from db
write query "update tbl_users set FirstName='$firstName', Email='$email" and execute this query, because you are starter this can be enough but remember query written like this can be used for SQL Injection that means you can write SQL query into text field "firstname" and do some stuff, like delete all data or gain passwords, emails etc.
When you get this then use parameters in your MySQL query in order to avoid SQL Injection. But you will manage it.
if you want to fetch the user information automatically from the drop list (without clicking submit button), you need to use AJAX. Here is the link to a very good example on how to use ajax with php and mysql http://www.w3schools.com/php/php_ajax_database.asp

Categories