This block of codes is supposed to retrieve data from my database using password already stored in the table. For some passwords, entered via a web form, it behaves properly. For others, it doesn't. I spent a good time trying to fix it, but could not.
<?php
include('connect.php');
$login = $_POST['login'];
$query = mysql_query("select * from secure_table where myPass = $login");
$row = mysql_fetch_array($query));
if( $_POST['login'] = $row['myPass'])
{
echo"<div align ='center'>";
echo "Your Details are:";
echo $row['surName'];
echo"<br/>";
echo $row['firstName'];
echo"<br/>";
echo $row['myDepartment'];
echo"</div>";
}
else{
echo "<div align = 'center'>;
<h2>Error in Password</h2>
</div>";
}
mysql_close($connection)
?>
and you need to change this line as well
if( $_POST['login'] = $row['myPass'])
To this
if( $_POST['login'] == $row['myPass'])
//use double equal for comparison. single equal is assignment operator.
$query = mysql_query("select * from secure_table where myPass = $login");
your query is wrong if $login is not and integer
change to this
$query = mysql_query("select * from secure_table where myPass = '$login'");
check this link
http://dev.mysql.com/doc/refman/5.0/en/identifier-qualifiers.html
you have extra ) remove this in this line
$row = mysql_fetch_array($query));
to this
$row = mysql_fetch_array($query);
as it written and The One and Only ChemistryBlob pointed it out remove the semicolumn ; in the
else statement from this line
echo"<div align = 'center'>;
one more think mysql_ function are depricited.
use mysqli_ Function or PDO
For mysqli_ function check this link http://php.net/manual/en/book.mysqli.php
FOR PDO check this link http://php.net/manual/en/book.pdo.php
Related
I made a login system and it works but I also have the user's session in the page after login.
How can I get user data from my database by referencing the user's session, and how can I update it when the user put what they going to change
<?php
session_start();
$query=mysql_query("SELECT username, email, password FROM user WHERE username = $_SESSION['username']");
while($row = mysql_fetch_array( $query )) {
echo .row['username'];
echo .row['email'];
echo .row ['password'];
?>
In new codes you should be using mysqli if your PHP version is high enough (if not... update...)
But here you go:
<?php
session_start();
$query = mysql_query("SELECT * FROM user WHERE username = {$_SESSION['username']}");
$row = mysql_fetch_assoc($query);
echo $row['username'];
echo $row['email'];
echo $row ['password'];
?>
Oh and the update:
<?php
$query = mysql_query("UPDATE user SET username={$_POST['username']}, email={$_POST['email']}, password={$_POST['password']} WHERE username={$_SESSION['username']}");
?>
And you should make a form for that..
The answer of Cris is almost perfect and well explained. But it is missing the quotes for the string in the statement.
As the col username will most likely be a varchar of any length.
$query = mysql_query("SELECT * FROM user WHERE username = '{$_SESSION['username']}'");
Current code:
<?php
session_start();
if ($_SESSION['username']) {
echo "Signed in as " . "$_SESSION[username]" . "<br />" . "<a href='logout.php'>Log out</a>";
//Get user info.
$results = mysql_query("SELECT * FROM users WHERE username=$_SESSION[username]");
while($row = mysql_fetch_array($results) {
$db_username = $row['username'];
echo $db_username;
}
}
else {
echo "Log in";
}
?>
Unfortunately I'm getting errors when returning the values that MySQL is supposed to be getting. Any idea why?
You forgot to use single quote around value in query
mysql_query("SELECT * FROM users WHERE username='{$_SESSION[username]}'");
^^ ^^
Also stop using mysql_* functions they are deprecated, Use MySQLi OR PDO.
Your query is wrong since it contains PHP variables not enclosed in single quotes or curly braces.
You can rewrite the query as follows:
With braces:
$results = mysql_query("SELECT * FROM users WHERE username={$_SESSION[username]}");`
Or with single quotes:
$results = mysql_query("SELECT * FROM users WHERE username='$_SESSION[username]'");
I have a html page that sends value pass to log.php :
<?php
$PHONE = $_POST['pass'];
mysql_connect('host.com', 'user', 'pass'); mysql_select_db('userdb');
$results = mysql_query(sprintf("SELECT FNAME,LNAME FROM `details` WHERE PASS='$PASS'",
mysql_real_escape_string($PASS))) or die(mysql_error()); while($row = mysql_fetch_assoc($results))
{ $rows[1] = $row; }
echo "Welcome ";
echo "$rows[1][FNAME]." ".$rows[1][LNAME]"
echo " you are logged in successfully"
?>
I get the result in log.php file in this form when value 'pass' is not being registered in database:
Welcome [//here user's first & last name if registered or remains blank] you are logged in successfully
I have table 'details' created
FNAME-First name
LNAME-Lastname
BIRTHDAY-Birthday
PHONE- user's no.
PASS- user's password.
My Question is , I want to just display ' You are not registered user' when pass value is not been registered in the database.Any help would be greatfull ?
Just check if you actually get a record or not using mysql_num_rows,
$results = mysql_query(sprintf("SELECT FNAME,LNAME FROM `details` WHERE PASS='$PASS'",
mysql_real_escape_string($PASS))) or die(mysql_error());
if(mysql_num_rows($results) > 0){
while($row = mysql_fetch_assoc($results))
{
$rows[1] = $row;
}
echo "Welcome ";
echo $rows[1]['FNAME']." ".$rows[1]['LNAME'];
echo "You are logged in successfully";
}
else{
//Redirect them back with error message
header("Location: http://www.example.com/index.php?err='You are not registered user'");
}
Note: 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.
You took value in $phone variable for password and in select query used PASS= $PASS so how can it run?
Change this then run like below:
$results = mysql_query(sprintf("SELECT FNAME,LNAME FROM `details` WHERE PASS='$PHONE'",
mysql_real_escape_string($PHONE))) or die(mysql_error());
if(empty($rows[1][FNAME])){
echo 'You are not registered user';
}
else{
echo "Welcome ";
echo "$rows[1][FNAME]." ".$rows[1][LNAME]";
echo " you are logged in successfully";
}
I'm trying to retrieve all data with the LIKE query from the users input and match it to the database, it works but only returns one record but I have many records in the table.
It returns the closest record it can find,
so say for example I have 2 records who's ItemDesc field contains the characters 'The', when I search for 'The' in my input box and click submit it returns the closest (earliest created) record when it is supposed to return both.
<?php
$username = "a3355896_guy";
$password = "++++++";
$hostname = "mysql5.000webhost.com";
$dbh = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
mysql_select_db("a3355896_book") or die("Unable to connect to database");
$ItemDesc = $_POST['ItemDesc'];
$query = "select * from StockItems where ItemDesc LIKE '%$ItemDesc%'";
$result=mysql_query($query);
$num=mysql_num_rows($result);
mysql_close();
?>
Sorry was supposed to included the retrieval:
<?php
if ($num>0)
{
echo "<center><table border=1><tr><th>Item Code</th><th>Item Desc</th>";
echo "<th>Item Stock Qty</th>";
echo "<th>Item Unit Price</th><th>Item Category</th></tr>";
$ItemCode = mysql_result($result,$i,"ItemCode");
$ItemDesc = mysql_result($result,$i,"ItemDesc");
$ItemStockQty = mysql_result($result,$i,"ItemStockQty");
$ItemUnitPrice = mysql_result($result,$i,"ItemUnitPrice");
$ItemCategory = mysql_result($result,$i,"ItemCategory");
echo "<tr><td>$ItemCode</td><td>$ItemDesc</td><td align=right>";
echo "$ItemStockQty</td>";
echo "<td align=right>$ItemUnitPrice</td>";
echo "<td>$ItemCategory</td></tr>";
echo "</table></center>";
}
else
{
echo "<form name='DeleteStock2'>";
echo "<p> Sorry, $ItemDesc does not exist!<p>";
echo "<input type='button' value='Leave' onclick='history.go(-1)'>";
}
?>
You aren't actually accessing your data here- you need to iterate over the result set.
$setLength = mysql_num_rows($result);
for($i = 0; $i < $setLength; $i++){
//Here, mysql_fetch_assoc automatically grabs the next result row on each iteration
$row = mysql_fetch_assoc($result);
//do stuff with "row"
}
Unless you ARE doing that and you just chose to not include it in your snippit. Let us know :)
--Edit--
First off, I apologize- out of old habit I suggested that you use mysql_fetch_assoc instead of the mysqli set of functions.
Try using the fetch_assoc or fetch_array functions, it could solve your issue. I've never used the method you used, I think it has been deprecated for a while.
Check it out here:
http://php.net/manual/en/mysqli-result.fetch-assoc.php
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 .