So I am messing around with PHP and MySQL, I currently have a database with:
id | username | password
within it, I was wondering if there would be a way of checking if the username entered is the same as the password on the same row/ID (the ID is auto incrementing)
<form action="login.php" method="get">
login >
<input name="log_username" type="text" />
<input name="log_password" type="password" />
<input id="submit" type="submit" />
</form>
I know its possible, but I - myself as a rookie with SQL and PHP cannot figure out ^^'
Thanks in Advance
EDIT:
For those interested this is my current register code (works brilliantly)
<?php
$con=mysqli_connect(###########);
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO users (username, password)
VALUES ('$_POST[reg_username]','$_POST[reg_password]')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
SELECT * FROM users WHERE username = :username AND password = :password
Where password is the encrypted version of the password they submitted, because you're totally going to re-write this to encrypt passwords, and use prepared statements to remove your SQL injection vulnerability.
Creating a user login system is such a common thing that there are literally thousands of tutorials you could find on this topic, I suggest you do some basic research.
if ((isset($_GET['log_username']) && $_GET['log_username'] != "") && (isset($_GET['log_password']) && $_GET['log_password'] != "")
{
$link = mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("database", $link);
$query = "SELECT * FROM users WHERE username = " . $_GET['log_username'] . " AND password = " . $_GET['log_password'];
$result = mysql_query($query);
if (mysql_num_rows($result) < 1)
echo("No record found");
}
This is the simplest way, but I suggest you to use PDO because mysql_query is deprecated.
Although you have requested a PHP solution, in real-world terms this might be better solved with some javascript/jQuery, because presenting the error to the user will not require a page refresh. For your peace of mind, this is what it would look like:
jsFiddle Demo
HTML:
<form id="myForm" action="login.php" method="get">
login >
<input id="log_username" name="log_username" type="text" />
<input id="log_password" name="log_password" type="password" />
<input id="mySubmit" type="submit" />
</form>
jQuery:
$('#mySubmit').click(function(e) {
e.preventDefault();
var un = $('#log_username').val();
var pw = $('#log_password').val();
if ( un == pw ) {
alert('Sorry, username/password cannot be identical');
}else{
$('#myForm').submit();
}
});
Notes:
The above code uses jQuery, so you must reference the jQuery library, usually in the <head> tags, like this:
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
Note the use of e.preventDefault, which means: Don't do what a submit button would normally do (in other words, don't submit). We control the submission ourselves, manually.
This is how we use javascript/jQuery to manually submit: $('#myForm').submit();
Note that ID attributes were added to all elements that I needed to reference. Although it is possible to format jQuery to reference elements with or without IDs, this makes it much easier and there is no downside to doing so (although you must follow the rule that all elements must use unique IDs)
Also note that one should not use the word submit for an ID name for a submit button. Doing so may cause problems later.
Related
(so to begin I'm a high school student so not the greatest with the lingo so try your best to guide rather than tell if you can) When using insert to put data into my database from the website it appears to work but nothing appears in the database but no error codes.
I am using Mysqli, PHP, and Wampserver to run a local server and the website will not send data to the Database.
<?php
include 'connect.php';
include 'header.php';
?>
Sign Up<br>
<form method="post" action="">
Username: <input type="text" name="user_name"><br>
password: <input type="password" name="user_pass"><br>
password <Check: input type="password" name="user_pass_check"><br>
Email: <input type="text" name="user_email"><br>
<input type="submit" value="Register">
</form>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$sql = "INSERT INTO users(user_name, user_pass, user_email) VALUES('".mysqli_real_escape_string($con, $_POST['user_name'])."', '".sha1($_POST['user_pass'])."', '".mysqli_real_escape_string($con, $_POST['user_email'])."', NOW(), 0)";
$result = mysqli_query($con, $sql);
if (!$result) {
echo 'Something went wrong';
echo mysqli_error($con);
} else {
echo "you have successfully registered. you can now <a href='signin.php'>sign in</a> and start posting";
}
}
}
include 'footer.php'?>
In my file used for connection
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$dbname = 'seqevents';
$con = new mysqli($host, $user, $pass, $dbname) or die("cannot connect");
session_start();
if (!isset($_SESSION['user_level'])) {
$_SESSION['user_level'] = 0;
}
I receive no error messages and nothing happens on the website it just reloads and gets rid of any input within the text boxes.
First the (likely) problem, then some other important pointers:
When you insert, you insert set 3 columns (user_name,user_pass,user_email) and then load 5 values into it (NOW() and 0) are extra, it has no clue where to place those values.
DO NOT USE MD5. If you're thinking "yeah, but my site isnt very interesting, why cares" read this line again. DO NOT USE MD5. Or sha1:
Never store passwords in clear text or using MD5/SHA1! Only store password hashes. Use PHP's password_hash() and password_verify() . If you're running a PHP version lower than 5.5 (which I really hope you aren't), you can use the password_compat library to get the same functionality. – Dharman
Use prepared statements. mysqli_real_escape_string is a good first step, but not adequite. Prepared statements secure the query for you. Bit more complex, a lot more secure.
I suggest removing $_SERVER['REQUEST_METHOD'] === 'POST'. What if you have two forms on your page? You're stuck. Instead, give your submit button a name like submitRegForm. Then you can do if( isset($_POST['submitRegForm']) )
DO NOT USE MD5 OR SHA1
<html>
<head>
</head>
<body>
<form action="login_process.php" method="post">
SID: <input type="text" name="sid">
<br />
Password: <input type="text" name="pw">
<br />
<input type="submit" value="Login">
</form>
</body>
</html>
login_process.php FILE
<html>
<head>
</head>
<body>
<?php
include ("connection.php");
$sid = $_POST['sid'];
$pw = $_POST['pw'];
setcookie("username", "$sid". time()+86400);
$result = mysqli_query($con, "SELECT SID FROM student_table WHERE SID='$sid' and password='$pw'") or die('Query failed');
if(!$result){
echo "Failed";
} else {
echo "success". $_COOKIE['username'];
$_SESSION['username'] = $sid;
}
?>
</body>
</html>
I have data in my student_table. But no matter what input i give it says success. even if i click login button without any input it still says success. please help.
You should use quotes when you assign values in sql queries .
SELECT
SID
FROM
student_table
WHERE
SID = '$sid' and password = '$pw'
Also look forward Prepared Statements to protect yourself from sql injections.You should also add the code below to fetch selected row :
while ($row = mysqli_fetch_array($result)) {
$_SESSION['username'] = $row['SID'];
}
Start learning basic debugging:
When a query fails bad, just do this:
Instead of running it (mysql_query, or mysqli_query or whatever you have), ECHO it:
echo "SELECT SID FROM student_table WHERE SID='$sid' and password='$pw'";
After you submit the form, you will be shown the query that runs, go to phpmyadmin or whatever you use and run the query manually. See if there are errors and also see easier what's going on. Advisable when you do work like this, FIRST try the queries in phpmyadmin then apply them in the code, after you are confident they are ok.
This is not really an answer but more about how to find out what is going wrong when you code does not work as you expect.
First, always put you SQL into a variable by itself. Why, so you can 'var_dump' it and see what is happening. So, try this:
$sql = "SELECT SID FROM student_table WHERE SID=$sid and password=$pw";
var_dump($sql, 'my_query'); // you will see what PHP created.
then try the answer provided:
$sql = "SELECT
SID
FROM
student_table
WHERE
SID = '$sid' and password = '$pw'";
At least you will see what is likely to be incorrect.
var_dump($sql, 'the answer_query'); // you will see what PHP created.
$result = mysqli_query($con, $sql) or die('Query failed');
The outer quote marks must be " (double quote) not " ' " (single quote) both of which are perfectly valid PHP. the former allows variables to be replaced in strings.
The latter will treat eveything as a literal string.
So the vote page is at Click here
the Username should go into the text box, and after you vote on both servers, it should send the Username to the database.
<form name="vote" class="short style" method="post" target="_blank">
<input name="username" type="text" size="30" maxlength="30" placeholder="Username"><button id="nextbutton" type="button" onClick="next();">Next</button>
<div style="display: none;" id="button" class="button"><button type="submit" onClick="changeAction('http://www.rune-server.org/toplist.php?do=vote&sid=8289&name=');")>Rune-Server</button><button type="submit" onClick="changeAction('http://www.runelocus.com/toplist/index.php?action=vote&id=30838&id2=');")>RuneLocus</button></div>
</form><br>
im not sure what to add, i think i need to do something with the next button.. but please help! another thing is its a html... should it be php?
but the mysql is working fine and is sending to the client.
its just getting the username to be sent to the database,
heres check vote
if (!$con) {
die("Could not connect to database: " . mysql_error());
}
mysql_select_db("a5999082_oxidepk", $con);
$username = mysql_escape_string($_GET['username']);
if (isset($_GET['username'])) {
$result = mysql_query("SELECT * FROM `votes` where username = '$username'") or die(mysql_error());
$row = mysql_fetch_array($result);
if($row['username'] == $username) {
mysql_query("DELETE FROM `votes` where username = '$username'");
echo "true";
} else {
echo "false";
}
}
mysql_close($con);
and then heres the Call back
<?php
$rspscoding = gethostbyname("http://www.oxidepkz.net63.net");
if($_SERVER['REMOTE_ADDR'] == $rspscoding) {
$con = mysql_connect("mysql1.000webhost.com", "a5999082_oxidepk", "password");
if (!$con) {
die("Could not connect to database: " . mysql_error());
}
mysql_select_db("a5999082_oxidepk", $con);
$username = mysql_escape_string($_GET['username']);
if (isset($_GET['username'])) {
mysql_query("INSERT INTO `votes` (username) VALUES ('$username')") or die(mysql_error());
}
mysql_close($con);
}
?>
also not sure what gethostbyname should be... thanks!
So... several comments
First, you're not sanitizing your data, which leaves you open to SQL injection.
Second, you posted your database credentials in your code example. Anyone reading this can see them and access your database. Editing won't fix that (will still be in history) so I would HIGHLY recommend you change your database credentials. Next time you might want to remove those before posting.
Third, you need to stop using mysql and switch to mysqli
Why shouldn't I use mysql_* functions in PHP?
Fourth, you're using (in a confusing way)
$rspscoding = gethostbyname("http://www.oxidepkz.net63.net");
if($_SERVER['REMOTE_ADDR'] == $rspscoding) { }
That will never succeed because $_SERVER['REMOTE_ADDR'] contains the IP of the user, not the host name (and your user won't be posting from your server either, which is what I assume $rspscoding is). Check out the PHP $_SERVER reference.
I made a small database(1 table) in phpMyAdmin. One of the fields I want to check is "Name".
I want to verify through PHP if a name that user types in a form exists in the database. In the html a list of names from DB appears, but the user might type wrong the name in the form.
The problem is the answer whether it exists or not varies.
I have 2 PHP files:
Connection.php and welcome.php
Connection
<html>
<head>
<title>Project</title>
</head>
<body>
<?php
mysql_connect("localhost","root","");
mysql_select_db("e-card");
$sql=mysql_query("SELECT * FROM person");
$dbname="name";
#$formula_adr="formula_adr";
#$adress="adr";
$line=mysql_fetch_assoc($sql);
echo'Choose a name to whom you send e-card:<br/><br/>';
echo $line[$dbname].'<br/>';
while($line=mysql_fetch_assoc($sql))
echo $line[$dbname].'<br/>';
?>
<form action="welcome.php" method="POST">
Nume: <input type="text" name="fname" />
<input type="submit" value="Verify existance in DB"/>
</form>
</body>
</html>
And welcome:
<?php
mysql_connect("localhost","root","");
mysql_select_db("e-card");
$sql=mysql_query("SELECT * FROM persoana");
$dbname="name";
$formula_adr="formula_adr";
$adresa="adr";
$linie=mysql_fetch_assoc($sql);
if ($_SERVER['REQUEST_METHOD']=='POST' and isset($_POST['fname']))
{
$name = $_POST['fname'];
while($line=mysql_fetch_assoc($sql))
{
if(strcmp($name,$line[$dbname]))
{
echo 'Found';
}
else
{
echo 'This name doesn't exist in DB';
}
}
}
?>
THANK YOU IN ADVANCE ^_-
<?php
mysql_connect(HOST, USERNAME, PASSWORD);
mysql_select_db(DB_NAME);
if($_POST) {
$name = $_POST['fname'];
// check if name exists in db
$sql = "SELECT name FROM person WHERE name=' . mysql_real_escape_string($name) . '";
$query = mysql_query($sql);
if(mysql_num_rows($query) > 0) {
// user exists
} else {
// user does not exist
}
}
The above script will work and will also protect your script against SQL injection by using the built-in mysql_real_escape_string method. I would also recommend against using a wildcard (*) selector when verifying data in this manner as it's a waste of resources to query any additional information that is unused.
Don't get all data from the table to compare for a name.
Do it this way:
$sql=mysql_query("SELECT * FROM persoana where name like '$name%'");
You will get result only if you have a match
I would follow these steps high level steps.
1 - use javascript to initially check on client side that something was entered BEFORE calling the DB. You can use a filter in your javascript to check that form field.
2 - If you verify that something *useful was entered - pass the form field value to another page or object that will parse the value and then query the table.
3 - Use the parsed value against the db table column that contains your data. If records are found, return them.
Use a SQL injection technique to prevent malicious intend by users who may type something evil into your form field.
I just start coding in PHP,
i wrote my first php + mysql program for inserting data through web form. it works fine, but whenever i refresh the page, it automatically saves null record to my database.
i know the solution in .NET is ispostback, but not in php?
can somebody give me some idea in PHP.
Code is here:
<body>
<form action="mySQLTest.php" method="post">
First Name :<input type="text" name ="txtFirstName"/> <br/>
Last Name: <input type="text" name ="txtLastName"/> <br/>
Age : <input type="text" name= "txtAge" /> <br/>
<input type="submit"/>
</form>
<?php
$con = mysql_connect("localhost","root","");
if(!$con)
{
die('Could not Connect:' .mysql_error());
}
mysql_select_db("test", $con);
if($_REQUEST[])
{
$sql1 = "Insert into info(FirstName, LastName, Age) Values('$_POST[txtFirstName]','$_POST[txtLastName]','$_POST[txtAge]')";
}
if(!mysql_query($sql1, $con))
{
die('Error: '.mysql_error());
}
else
{
echo "1 Record Added";
}
mysql_close($con)
?>
</body>
Have you tried if ($_SERVER['REQUEST_METHOD']=='POST')
updated answer:
if ($_SERVER['REQUEST_METHOD']=='POST') {
[insert...]
header('Location: added_record.php');
}
When you use the POST-method, it's better (imho) to use $_POST rather than $_REQUEST. To check whether you have data, you could use isset($_POST['txtFirstName']);. If you need all data, it's best to do this for all input fields, resulting in
if(isset($_POST['txtFirstName']) && isset($_POST['txtLastName']) && isset($_POST['txtAge'])) {
// do stuff
}
If you want to know if there was any field submitted using post, you could use if(!empty($_POST)) {.
On a side note: I know you are just starting PHP, it could be quite dangerous to use user-generated code in queries. When you are building stuff online, for everyone to reach, please read a bit about SQL injection. This will also prevent your code from breaking when someone enters an apostrophe (').