Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have already build a functioning login page which redirects the user the index.php file.
From previous help, I was able to get the wage and display it on the page depending on which user logs in. This is the table users in the database user_registration
user_id username password email wage
1 johnsmith jsmith99 jsmith#gmail.com 100
2 davidscott dscott95 davidscott#gmail.com 90
The part i am stuck on is creating a functioning form that the user can update their wage to the sql database.
Can someone please help me with the php code?
This is the form i already have in place:
<form id="change-wage" action="update.php" method="post">
<input type="text" id="new_wage" name="new_wage">
<input type="button" value="Save">
</form>
EDIT: this is the code, The aim of it is that the user can update the wage value in the table by filling in the textbox and pressing submit. any Ideas how i can acieve this?>
<?php //CHANGING THE WAGE
$username = '$_SESSION['MM_Username'];';
if (isset($_POST['submit'])){
$wage = $_POST['wage-new'];
//connect to server
mysql_connect ("localhost","root","") or die ("Could not connect");
mysql_select_db("user_registration") or die ("Could not connect to the database");
mysql_query ("UPDATE users SET wage='$wage' WHERE username = '$username'") or die ("Could not update");
}
?>
I wont give you the code unless you demonstrate as previous commentator said. However I will give you a an overview so you can work at it your self.
update.php
Check if your is logged in.
if TRUE, continue.
get the new wage from the form
$new_wage = $_POST['new_wage'];
Be sure to validate and clean the $new_wage variable.
Next stage assumes your using PDO
$params = array($new_wage, $logged_in_user_id);
$update = "UPDATE user_registration SET wage=? WHERE user_id=?";
$pdo->prepare($update);
$pdo->execute($params);
First of all if you are using session variables make sure you start the session -session_start();
$username = '$_SESSION['MM_Username'];';
should be
$username = $_SESSION['MM_Username']; (without single quotes)
$wage = $_POST['wage-new'];
should be
$wage = $_POST['new_wage']; as you named it in your html file
you are selecting database user_registation and I assume it should be user_registration
And last, think about switching to PDO or mysqli.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I'm making a website that uses SQL and PHP functionalities. How do I connect to a database?
I would advise you begin by looking here.
You need to ensure that you have created user credentials with the correct permissions to query the database before you try this. You can do this through the cPanel of your web server (I'm going to assume you are using a web hosted server for this question).
Once you have a working and tested connection to the database, you can then start looking at the mySQLi documentation here. Which will show you how to execute and retrieve results from a database query and how to handle the returned data with PHP.
I see you are seriously downvoted.
I learned it the hard way and I am still learning to post here.
Stack sites are supposed to be searched first. If your question is already answered then people downvote you.
The solution to your question:
In your mysql or phpmyadmin you can set whether you use a password or not. The best way to learn is to set mysql with a password in my opinion. If you will launch a website online finally, you have to take security measures anyway.
If you make contact to your mysql database with you have to set:
username, password, database and servername ( for instance localhost).
The most secure way is using the OOP / prepared method:
$servername ='localhost';
$username='yourname';
$password='12345';
$dbname='name_database';
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($stmt = $conn->prepare("SELECT idnum, col2, col FROM `your_table` WHERE idnum ='5' ")) {
$stmt->execute();
$res = $stmt->get_result();
$qrow = mysqli_num_rows($res);
while ($row = mysqli_fetch_assoc($res)) {
var_dump($qrows); // number of rows you have
$total = implode(" / " , $row);
var_dump($total);
$idnum = $row['idnum'];
var_dump($idnum);
}
The easiest way that I do with my site is make a file called db.php containing:
<?php
$host = 'localhost';
$user = 'root';
$pass = 'password';
$db = 'databasename';
$mysqli = new mysqli($host,$user,$pass,$db) or die($mysqli->error);
..then in the index.php file, at the top:
<?php
require_once('db.php')
?>
I have created and app with a working login and registration. When someone logs in and presses a button there username is sent to a Earn.php file that is connected to my database that has a points column in it. My problem lies with adding, lets say 5 points to the users specific account.
Example: Username sent to php file from app> then the php file takes that specific username and add 5 points to its point column in the database. Like 5+5=10
What I have now:
<?php
$con = mysqli_connect("localhost", "id177667_root", "***", "id177667_loginb");
$username = $_POST["username"];
?>
Sorry if this is a lot to ask for, I very knew at this! Any help is very much appreciated, thanks!
This has a simple solution. You can use update statement:
$q = "UPDATE TableName SET points = points + 5 WHERE username_column ='".$username."'";
$r = mysqli_query($con , $q) or die();
Let me know if there is anything else.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
how to block user after 3 login attempts ?
Here is my code :
session_start();
/************Connexion************/
if(isset($_POST['cnx'])){
require_once('../config.php');
$db = new DBSTOCK();
$cnx = $db->connect();
$user=$_POST['user'];
$pass=$_POST['pass'];
// To protect from MySQL injection for Security purpose
$user = strip_tags($user);
$pass = strip_tags($pass);
$user = stripslashes($user);
$pass = stripslashes($pass);
$user = mysqli_real_escape_string($cnx,$user);
$pass = mysqli_real_escape_string($cnx,$pass);
$q=mysqli_query($cnx,"select * from admin where user='".$user."'");
$row = mysqli_fetch_array($q); //or die(mysqli_error($con));
$pw = $row['pass'];//hashed password in database
$username = $row['user'];
if($user==$username && password_verify($pass, $pw)) {
$_SESSION["user"]=$user;
header("Location: ../view/accueil.php");
}
else{
header("Location: ../index.php?failed=0");
}}
/************Deconnexion************/
if(isset($_GET['decnx'])){
session_destroy();
session_unset();
header("Location: ../index.php");
}
any script suggestion i can add to my code so a user can be blocked for 10 minutes after 3 consecutive failed login attempts ?
Add the following two columns to your row:
last_attempt as a datetime
attempt_count as an int
In your login logic, check these two values, if it's 3 or more and within the time frame (ex: 10mins), then update last_attempt and increment attempt_count, this second part is not necessary but you might want to know this. If it's been more than 10mins, then set attempt_count back to 0 if they pass or 1 if they fail and update last_attempt again.
As a bonus, you now also know the last time the user logged in, which is useful when you want to find unused accounts.
There are so many ways to do that. If you want to block the device then you can create a cookie for 10 mins, and set a condition if username matched then it will not hit the database for log in.
Or if you want to block for any device for that user, then you have to maintain the user status, where three consecutive failure attempt will change user status and the time when it is blocked. But this time you have check whether the blocked time was 10 mins before or not for every login attempt.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
i need some little help .. i wanna fetch only new entry in my database without refresh my page..
ii have an php page which can display all record's of my database .. like someone entered new data in database i want to fetch only single entery .. don't fetch all entries of again .. i also read too many of articles about JSON ajax etc .. but no onehelps me about fetch only single entery . is here any way using xml or something's special to do this .. i don't have any idea how i can do it
thank you
A very general approach would be something like that:
On every page load run a script that checks every a certain time interval the database for new entries:
Javascript:
<script>
$(document).ready(function(){
setInterval(function(){
$.ajax({
type: 'POST',
url: 'ajaxfile.php'
}).success(function(response){
var response = $.parseJSON(response);
var username = response.username; //here we put hypothetical db column "username" in a variable
alert(username); //here we alert the "username" variable in order to verify the script. All other db columns can be called as: response.db_column_name
});
}, 10000); //interval time: 10000 milliseconds (10 seconds)
});
</script>
This script, combined with the following "ajaxfile.php" will display all database columns as: response.db_column
Before I give you my idea about the 'ajaxfile.php', please keep in mind that in order for this approach to work, you need to add an extra column to your db table (for example column: "seen" -that takes values 1 or 0 and having number 1 as default for every new row added). Since you didn't provide enough information, I will here assume that the database table is called "users" and -say- you want to monitor each new user registration in real time (with 10 seconds intervals).
PHP (ajaxfile.php)
<?php
//protect the file from un-authorized access
define('AJAX_REQUEST', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
if(!AJAX_REQUEST) {die();}
require("db_connect.php"); //a typical db connection function
$results = array(); //define the results variable
$query = mysql_query("SELECT * FROM users WHERE new_column = '1' ORDER BY id DESC LIMIT 1"); //here we query the db to fetch only the newest record -the one where column "seen" is "1"
while($res = mysql_fetch_assoc($query)){
$current_id = $res["id"];
mysql_query("UPDATE users SET new_column = '0' WHERE id = '$current_id' "); //update the record so it will appear as "seen" and will not be fetched again
$results[] = $res;
}
echo json_encode($results);
?>
In the above file, notice the first two lines which are there to protect the ajax file from direct "browser calls". It is quite a universal solution and can be used in all ajax files.
Finally, here is an example of the db_connect.php file:
<?php
define('DB_HOST', 'localhost'); // the database host
define('DB_PORT', '3306'); // the database port
define('DB_NAME', 'your_db_name'); // the database name
define('DB_USER', 'your_db_user'); // the database user
define('DB_PASSWORD', 'your_db_password'); // the database password
$conn = #mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die("Could not connect to the Database Server");
mysql_select_db(DB_NAME, $conn) or die("Could not find the Database");
?>
It is a very general approach indeed, but can cover a wide spectrum of applications with small modifications or additions.
I am sorry I could not be more specific -but your question was also a bit too "general"... Hope this helps you and others.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I have a very basic login-check page:
$host="localhost"; // Host name
$username="user"; // Mysql username
$password="pass"; // Mysql password
$db_name="db"; // Database name
$tbl_name="userdata"; // Table name
$lastLogDate=date("l, m/d/y, h:i:sa");
// 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");
$logdate=date("m/d/Y");
$logtime=date("H:i:s");
$logip=$_SERVER['REMOTE_ADDR'];
$nol=$_POST['nol'];
// username and password sent from form
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];
$origpass=$_POST['mypassword'];
$origpass=str_replace("'", '"', $origpass);
$from=$_POST['from'];
if ($from=="forum") {
$to="/forum";
}
if (isset($_POST['nol'])) {
$rd=$nol;
}
else {
$rd="/home";
}
$sql="SELECT * FROM userdata WHERE username collate latin1_general_cs='$myusername'";
$result=mysql_query($sql);
$result=mysql_fetch_array($result);
$password=$result['password'];
$_SESSION['mypassword']=$mypassword;
$salt = 'no';
$salted_password = $mypassword.$salt;
$mypassword = md5($salted_password);
if($mypassword==$password) {
$mypassword=$_POST['mypassword'];
$_SESSION['myusername']=$myusername;
$_SESSION['mypassword']=$_POST['mypassword'];
$sqlDate="UPDATE userdata SET lastLog='$lastLogDate' WHERE username='$myusername'";
$resultDate=mysql_query($sqlDate);
mysql_query("INSERT INTO login_log (date, time, username, password, ip, success) VALUES ('$logdate', '$logtime', '$myusername', '$origpass', '$logip', '1')");
header("location:$rd");
}
else {
mysql_query("INSERT INTO login_log (date, time, username, password, ip, success) VALUES ('$logdate', '$logtime', '$myusername', '$origpass', '$logip', '0')");
header("location:/login?msg=wrongUorP");
}
After submitting the form, the page is just blank. The error_log doesn't have any errors in it. I haven't touched it since yesterday, and it was doing something yesterday.
Another problem is that I have a user-only page redirect to /login?nol=/<page>, so for example if the page is http://www.example.com/random/page/text.txt, the redirect would be /login?nol=/random/page/text.txt. The page checks if the user is logged in with the following:
<?php
session_start();
if(!isset($_SESSION['myusername'])){
header("location:/login?nol=/random/page/text.txt");
}
?>
But whenever the user logs in, the user just gets redirected to /login?nol=/random/page/text.txt even though the $_SESSION['myusername'] (I think) is already set. (refer to code above). I recently updated to PHP 5.3 with cPanel, and I previously had session_register(). Did I change the session variables wrong?
Here is my receiving page:
session_start();
if(!isset($_SESSION['myusername'])){
//header("location:/login?nol=/home"); // commented out to test if it receives session variable
echo "<h1>hello</h1>"; //the page displayed this, so the script did NOT receive the variable.
}
Session
show where in your code you are doing session_start() (the up-top chunk). Not the smaller 2nd blue/gray chunk
Sql Injection
Jay gave a good reference to his fine site on proper database layers to use, and the proper ways to use them. Many more are written about here. I just injected my table with your
SELECT * FROM userdata WHERE username collate latin1_general_cs='$myusername';
For inserts, doing 2nd level injection timebombs would be easy.
Hash
Jay mentioned it too. See his site. I wrote this up. Get off MD5