Simple logon script - php

I'm trying to do a simple logon script. That is, accept form content through a POST action. Check the database for a matching record. Pull other information from that row such as Full Name.
The code I have is;
if ( !isset($_POST['loginsubmit']) ) {
//Show login form
?>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<p>
Account ID:
<input name="AccountID" type="text" />
</p>
<p>
Username:
<input name="userEmail" type="text" />
</p>
<p>Password:
<input name="userPassword" type="password" />
<p>
<input name="loginsubmit" type="submit" value="Submit" />
</p>
</form>
<?php
}
else {
//Form has been submitted, check for logon details
$sql = "SELECT * FROM users WHERE 'accountID'=". $_POST['AccountID']. " AND 'userEmail'=". $_POST['userEmail'] . " AND 'userPassword'=". $_POST['userPassword']. " LIMIT 1";
$result = mysql_query($sql);
$count = mysql_num_rows($result);
if ($count == 1){
echo"Correct Username/Password";
}
else {
echo "Wrong Username or Password";
}
}
I have two issues. Firstly with the above code, I keep getting the following error.
Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in ...
Second, how do I get the other details fields out of the databse. I presume
$result=mysql_query($sql);
contains an array for the MySQL row, so could I do something like;
echo $result['fullName'];

First sanitize the fields to prevent SQL injection.
$sanitize_fields = array('AccountID','userEmail','userPassword');
foreach( $sanitize_fields as $k => $v )
{
if( isset( $_POST[ $v ] ) )
$_POST[ $v ] = mysql_real_escape_string( $_POST[ $v ] );
}
Then quote the string fields in your query. Initially there was an error in your query. That's why you were getting a boolean value of false.
$sql = "SELECT * FROM users WHERE accountID='". $_POST['AccountID']. "' AND userEmail='". $_POST['userEmail'] . "' AND userPassword='". $_POST['userPassword']. "' LIMIT 1";
I suggest you do the following after running the query to see the error generated by MySQL, if there is one.
$result = mysql_query($sql) or die('Query failed: ' . mysql_error());
The MySQL extension is being phased out and there are newer better extensions such as MySQLi and PDO, have a look at those.

In your SQL statement:
$sql = "SELECT * FROM users WHERE 'accountID'=". $_POST['AccountID']. " AND 'userEmail'=". $_POST['userEmail'] . " AND 'userPassword'=". $_POST['userPassword']. " LIMIT 1";
if in the table, the userEmail and userPassword are strings, please add single qoutes:
$sql = "SELECT * FROM users WHERE accountID=". $_POST['AccountID']. " AND userEmail='". $_POST['userEmail'] . "' AND userPassword='". $_POST['userPassword']. "' LIMIT 1";
To get the results:
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result))
{
if(mysql_num_rows($result) > 0)
echo $row['COLUMN_NAME'];
}
}
Your codes are very insecure:
Please use MySQLi or PDO to interact with the database
Escape all input data before sending to the database

Try this:
else {
//Form has been submitted, check for logon details
$conn = mysql_connect("db-host-here","db-user-here","db-pass-here");
$sql = "SELECT * FROM users WHERE accountID=". mysql_real_escape_string($_POST['AccountID']). " AND userEmail='". $_POST['userEmail']=mysql_real_escape_string($_POST['userEmail']); . "' AND userPassword='". $_POST['userPassword']=mysql_real_escape_string($_POST['userPassword']);. "' LIMIT 1";
$result = mysql_query($sql,$conn);
$count = mysql_num_rows($result);
if($count == 1){
echo"Correct Username/Password";
}
else {
echo "Wrong Username or Password";
}
}
// Get other information:
$dbInfo = mysql_fetch_assoc(); //If more than one row can be selected, use a while loop.
//Now play with $dbInfo:
echo $dbInfo['some_other_column'];
You have single quotes in your query where you don't need them, and you're missing them where you do. Try the code above.
Replace db-host-here,db-user-here and db-password-here with the correct database information.
I have done some escaping in your code, to prevent injection attacks. But you should really look into using prepared statements.

The problem here is that Your query fails to select any row therefore a boolean FALSE is returned from mysql_query call.
You should repair Your query and always check if the $result = mysql_query($query); returns false or not, like so:
// ...
$result = mysql_query($query);
if($result !== false) {
$count = mysql_num_rows($result);
// ...
}
But I recommend using PDO or at least mysqli http://php.net/mysqli.

Related

Query for condition 'ALL' with Variable?

I get confused for post variable to sql query,
here is sample of my report.php code
<form action="report.php">
<select id="status" name="status">
<option value="MARRIED">married</option>
<option value="SINGLE">Single</option>
<option value="ALL">ALL</option>
</select>
<input type="submit" value="Seach">
</form>
<?php
$status= $_GET['status'];
// Create DB connection
$sql = "SELECT * FROM member WHERE status ='$status'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<B>id: </B>" . $row["user_id"]. " -- <b>Date Record:</b> " . $row["created"]. " -- <b>Last Seen</b> " . $row["last_seen"]. " -- <b>Status: </b> "
}
} else {
echo "0 results";
}
$conn->close();
?>
How do i Query If "ALL" condition is Selected?
I dont know the PHP so this is not the exact code but concept should be like this
if( $status == 'ALL' )
$sql = "SELECT * FROM member";
else
$sql = "SELECT * FROM member WHERE status ='$status'";
It would be very wise in this case to store the $status variable in POST instead, since the SQL query depends on what value is stored in the URL, and is thus exposed to the user.
Another thing, since you are dealing with legacy code here is to make extra sure that you filter the user input and SQL query as much as possible. The thing with using older and obsolete functionality is that you will still be vulnerable to XSS and SQL injection attacks regardless of the precautions you take so it is highly recommended you go with either the MySQLi or PDO (PHP Data Objects) extension instead as these offer more stable and advanced functionality.
$status = htmlspecialchars($_GET['status'], ENT_QUOTES);
$where = '';
if ($status != 'ALL') {
$where = 'WHERE status = "$status"';
}
$sql = mysql_real_escape_string('SELECT * FROM member ' . $where);
$results = mysql_query($sql);
In PHP file
<?php
$status= $_GET['status'];
if($status == 'ALL'){
$where = '';
}else{
$where = 'status = '".$status."' ';
}
// Create DB connection
$sql = "SELECT * FROM member WHERE ".$where." ";
?>

Form not displaying in PHP [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 3 years ago.
So I have a page using PHP and a MySQL query. What I'm wanting to do is create basically an "edit" page that takes data from my database and uses it to show the values in various inputs. The user can then change the data in the input which will then update the corresponding MySQL table row. However, for whatever reason the page is NOT displaying the form, but rolling over to the else statement. I can verify the $_SESSION['weaponName'] is working, because it will echo the correct thing. Any ideas on why the form will not show up for me?
edit.php
<?php
session_start();
$con=mysqli_connect("localhost","username","password","db_name");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$weaponName = $_SESSION['weaponName'];
$query = mysqli_query($con, "SELECT * FROM weapons limit 1");
if(mysqli_num_rows($query)>=1){
while($row = mysqli_fetch_array($query)) {
$creator= $row['creator'];
$weaponCategory= $row['weaponCategory'];
$weaponSubCategory= $row['weaponSubCategory'];
$costAmount= $row['costAmount'];
$costType= $row['costType'];
$damageS= $row['damageS'];
$damageM= $row['damageM'];
$critical= $row['critical'];
$rangeIncrement= $row['rangeIncrement'];
$weight= $row['weight'];
$weaponType= $row['weaponType'];
$masterwork= $row['masterwork'];
$attributes= $row['attributes'];
$specialAbilities= $row['specialAbilities'];
$additionalInfo= $row['additionalInfo'];
}
?>
<form action="weaponEditUpdate.php" method="post">
<input type="hidden" name="weaponName" value="<?php echo $weaponName;?>">
Weapon Name: <input type="text" name="weaponName" value="<?php echo $weaponName;?>">
<br>
Weapon Category: <select name="weaponCategory">
<?php while ($row = mysqli_fetch_array($query)) {
echo "<option value='" . $row['weaponCategory'] ."'>" . $row['weaponCategory'] ."</option>";
} ?>
</select>
<input type="Submit" value="Change">
</form>
<?php
}else{
echo 'No entry found. Go back';
}
?>
As requested by OP (from comment conversations)
Instead of
if(mysqli_num_rows($query)>=1){
use
if(mysqli_num_rows($query) >0){
You're mixing functions
mysqli_connect("localhost","username","password","db_name");
Won't work with
mysql_query("SELECT * FROM weapons limit 1");
Try
$query = mysqli_query($con, "SELECT * FROM weapons limit 1");
And then
if($query->num_rows >= 1)
change this
$query = mysql_query("SELECT * FROM weapons limit 1");
to
$query = mysqli_query("SELECT * FROM weapons limit 1");
BUT omg all your code is mysql while you connected by mysqli !! .
You connect with mysqli, which is fine. THEN, you attempt to run queries via mysql. Those are two separate extensions. You can't mix them as they won't "communicate" with one another. Stick to mysqli.

Search Form Ability To Ignore Blank Fields

I have made a HTML search form which creates a query to a MySql database based on the contents of a form. What I would love to do is ignore the search parameter if the user leaves that specific form field empty. There are lots of answers online, especially on this website, but I can't get any of them to work.
I have stripped down my code as much as possible to paste into here:
The HTML input:
<form action="deletesearchresults.php" method="GET">
<p><b>First Part Of Postcode</b>
<input type="text" name="searchpostcode"></b> </p>
<p><b>Category</b>
<input type="text" name="searchfaroukcat"></b>
<input type="submit" value="Search">
</p>
</form>
The PHP results display:
<?php
mysql_connect("myip", "my_username", "my_password") or die("Error connecting to database: ".mysql_error());
mysql_select_db("my_db") or die(mysql_error());
$sql = mysql_query("SELECT * FROM
GoogleBusinessData
INNER JOIN TblPostcodeInfo ON GoogleBusinessData.BusPostalCode = TblPostcodeInfo.PostcodeFull WHERE PostcodeFirstPart = '$_GET[searchpostcode]' and FaroukCat = '$_GET[searchfaroukcat]' LIMIT 0,20");
while($ser = mysql_fetch_array($sql)) {
echo "<p>" . $ser['BusName'] . "</p>";
echo "<p>" . $ser['PostcodePostalTown'] . "</p>";
echo "<p>" . $ser['PostcodeArea'] . "</p>";
echo "<p>" . $ser['FaroukCat'] . "</p>";
echo "<p> --- </p>";
}
?>
This works great until I leave one field blank, in which case it returns no results as it thinks I am asking for results where that field is empty or null, which I don't wat. I want all of the results where that form field is empty.
I tried combining a like % [myfeild] % etc but I only want the results to display exactly what is on the field and not just the ones that contain what is in the field, for example searching for the postcode "TR1" would return results for TR1, TR10, TR11 etc.
I believe I may need an array but after 3 days of trying, I just don't know how to get this done.
Any help would be amazing.
edit: Also, I will be adding up to ten fields to this form eventually and not just the two in this example so please bear this in mind with any suggestions you may have.
try using isset()
example
if(isset($_GET[searchpostcode]) && isset($_GET[searchfaroukcat])){
$fields = "WHERE PostcodeFirstPart = '$_GET[searchpostcode]' and FaroukCat = '$_GET[searchfaroukcat]'";
}elseif(isset($_GET[searchpostcode]) && !isset($_GET[searchfaroukcat])){
$fields = "WHERE PostcodeFirstPart = '$_GET[searchpostcode]'";
}elseif(!isset($_GET[searchpostcode]) && isset($_GET[searchfaroukcat])){
$fields = "WHERE FaroukCat = '$_GET[searchfaroukcat]'";
}else{
$fields = "";
}
$sql = "SELECT * FROM
GoogleBusinessData $fields
INNER JOIN TblPostcodeInfo ON GoogleBusinessData.BusPostalCode = TblPostcodeInfo.PostcodeFull LIMIT 0,20";
You do however need to escape your $_GET variables however i would highly recommend using PDO/mysqli prepared statements http://php.net/manual/en/book.pdo.php or http://php.net/manual/en/book.mysqli.php
or try a foreach loop
foreach($_GET as $keys=>$value){
$values .= $keys."='".$value."' and";
}
$values = rtrim($values, " and");
if(trim($values) != "" || trim($values) != NULL){
$query = "WHERE ".$values;
}else{
$values = "";
}
$sql = "SELECT * FROM `test`".$values;

Form get's resent on refresh

Form get's resent on refresh, I had read about header("Location:my_page.php") unset($_POST), but I'm not sure where to place it.
This is our script, it works as need it, but it keeps re-sending on page refresh (Chrome browser alerts over and over), can some one fix the code and explain to my like 2 years old child.
<form action='thi_very_same_page.php' method='post'>
Search for Christian Movies <input type='text' name='query' id='text' />
<input type='submit' name='submit' id='search' value='Search' />
</form>
<?php
if (isset($_POST['submit']))
{
mysql_connect("localhost", "root", "toor") or die("Error connecting to database: " . mysql_error());
mysql_select_db("db_name") or die(mysql_error());
$query = $_POST['query'];
$min_length = 2;
if (strlen($query) >= $min_length)
{
$query = htmlspecialchars($query);
$query = mysql_real_escape_string($query);
echo "";
$result = mysql_query("SELECT *, DATE_FORMAT(lasteditdate, '%m-%d-%Y') AS lasteditdate FROM movies WHERE (`moviename` LIKE '%" . $query . "%') OR (`year` LIKE '%" . $query . "%')") or die(mysql_error());
if (mysql_num_rows($result) > 0)
{
while ($results = mysql_fetch_array($result))
{
echo "";
}
}
else
{
echo "";
}
}
else
{
echo "";
}
}
If you mean that the form data gets submitted again upon refresh, check this method
http://www.andypemberton.com/engineering/the-post-redirect-get-pattern/
You set your header to header('HTTP/1.1 303 See Other');
Data wont be cached, so when page refreshes the form data wont get submitted again!
The problem is you are using the post method to submit the form values so when ever you tries to refresh the browser asks you whether to send the form information or not it is the default behavior of the browser to tackle the posted information, the alternate solution for your problem is you can use the get method like in form attribute method='get' what it does it will append all the information of form in the URL which we call the query string and in PHP code you are accessing the form values in $_POST but when using get method the form values will now appear in the $_GET method these methods are called request method and are PHP's global variables, Now when you try to refresh it will not ask you to resend information because the information now resides in the URL
<form action='thi_very_same_page.php' method='get'>
Search for Christian Movies <input type='text' name='query' id='text' />
<input type='submit' name='submit' id='search' value='Search' />
</form>
<?php
if (isset($_GET['submit']))
{
mysql_connect("localhost", "root", "toor") or die("Error connecting to database: " . mysql_error());
mysql_select_db("db_name") or die(mysql_error());
$query = $_GET['query'];
$min_length = 2;
if (strlen($query) >= $min_length)
{
$query = htmlspecialchars($query);
$query = mysql_real_escape_string($query);
echo "";
$result = mysql_query("SELECT *, DATE_FORMAT(lasteditdate, '%m-%d-%Y') AS lasteditdate FROM movies WHERE (`moviename` LIKE '%" . $query . "%') OR (`year` LIKE '%" . $query . "%')") or die(mysql_error());
if (mysql_num_rows($result) > 0)
{
while ($results = mysql_fetch_array($result))
{
echo "";
}
}
else
{
echo "";
}
}
else
{
echo "";
}
} ?>
Hope this is enough to explain you about the form submission one thing I will suggest you to deeply look at below
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

PHP Mysql Data Insert

I'm learning PHP from reading the php manual and studying different tutorials. I hit a snag with the mysql_query. I'm trying to insert user data into a database from a form using PHP. The mysql_query should return false because the username doesn't exist in the database yet but according to the result I am getting it is returning true and nothing is being entered into the database. Am I using mysql_query wrong or is using !result incorrect?
$sql = "SELECT * FROM users WHERE username='".$_POST["name"]."'";
$result = mysql_query($sql)
if (!$result) {
$sql = "INSERT INTO USERS (username, email, password) VALUES
('".$_POST["name"]."', '".$_POST["email"]."', '".$passwords[0]."')";
$result = mysql_query($sql);
if ($result) {
echo "It's entered!";
} else {
echo "There's been a problem: " . mysql_error();
}
} else {
echo "There's already a user with that name: <br />";
$sqlAll = "SELECT * FROM users";
$resultsAll = mysql_query($sqlAll);
$row = mysql_fetch_array($resultsAll);
while ($row) {
echo $row["username"]." -- ".$row["email"]."<br />";
$row = mysql_fetch_array($result);
}
}
Jason, you're checking to see if the query has failed or not - not whether it has returned the value 'false' or 'true'. You need to call mysql_fetch_row or similar, then compare the result.
Alternatively you could use the following:
if (mysql_num_rows($result) == 0) {
/* User doesn't exist */
} else {
/* User exists */
}
This will detect if any users have been chosen by your query and - if they have - your user exists already.
Also, you should learn about input sanitisation and SQL Injection. It's a very critical security issue and your script is vulnerable to it. More info here.
A select query which has no result rows STILL returns a result handle. msyql_query() will ONLY return a 'false' value if the query fails due to a syntax error, constraint violation, etc...
Your code should be
$sql = "...";
$result = mysql_query($sql);
if ($result === false) {
die("QUery failed: " . mysql_error());
}
if (mysql_num_rows($result) == 0) {
... user does not exist ...
}
And please please please read up about SQL injection vulnerabilities. Your code has holes wide enough for a truck to drive through.
In this case, $result will be a resource. You should check the number of results with mysql_num_rows().
Never, really, NEVER, use $_POST or any direct user input in a query. Always escape the input, BEFORE using it in a query, with mysql_real_escape_string(), or you'll have opened a serious security issue with SQL Injection.
Ex:
$safe_name = mysql_real_escape_string($_POST["name"]);
$sql = "SELECT * FROM users WHERE username='$safe_name'";
It's not exact.
mysql_query() will also fail and return FALSE if the user does not
have permission to access the table(s) referenced by the query.
In your case you have the permission but the user doesn't exist. So it will return true but the result set returned is empty.
mysql_query will return an empty set if the query returns no data. The query will however not fail.
i solve my problem :
like this
<?php
$username = $_POST['username'];
include('config.php');
$result = mysqli_query($con,"SELECT * FROM persons WHERE username='$username'");
while($row = mysqli_fetch_array($result)){
echo $row['username'];
echo "</br>";
echo "</br>";
echo "<p><b>Secret Question</b></p>";
echo $row['secret'];
}
?>
</br>
</br>
<form action="forgetaction.php" method="POST">
<p><b>Answer is :</b><p>
<input type="hidden" name="username" value="<?php echo $username; ?>">
<input type="text" name="answer">
</br>
</br>
<input type="Submit" value="Submit">
</form>
and forget action.php like this :
<?php
include('config.php');
$username = $_POST['username'];
echo $username;
$result = mysqli_query($con,"SELECT * FROM persons WHERE username='$username'");
$row = mysqli_fetch_array($result);
if($row['answer'] == $_POST['answer']) {
echo $row['password'];
} else {
echo 'wrong!';
}
?>
thank you all for help .

Categories