This is my first topic so far in this great webpage
The problem is this:
I'm scripting an UCP (PHP & MySQL based). I want it to show the user's status like score, money, etc. (Yeah, it's for a game) but when I click on the login button nothing happens it just erases the content of the requested fields.
It was working properly before I made some changes (Checking if the username exists)
Here's the code:
if (isset($_POST['login']))
{
$hashedpass = hash('whirlpool', $password);
$query = "SELECT * FROM users WHERE Username = '$playername' AND Password = '$hashedpass'";
$result = mysql_query($query);
$num = mysql_num_rows($result);
mysql_close();
if($num != 0)
{
echo"Account doesn't exist!";
header("Location: ucp.html");
}
else
{
$name=mysql_result($result,$i,"UserName");
$money=mysql_result($result,$i,"Money");
$score=mysql_result($result,$i,"Score");
$wantedlevel=mysql_result($result,$i,"WantedLevel");
$adminlevel=mysql_result($result,$i,"AdminLevel");
echo "<b>$name</b><br>Money: $money<br>Score: $score<br>Wanted Level: $wantedlevel<br>Admin Level: $adminlevel<br><br>";
}
}
else if (isset($_POST['register']))
{
header("Location: register.html");
}
else
{
header("Location: index.html");
}
if($num != 0)
change to:
if($num == 0)
This simply won't work here nor does it make much logical sense:
$num = mysql_num_rows($result);
mysql_close();
if($num != 0)
{
echo"Account doesn't exist!";
header("Location: ucp.html");
}
First the logic is wrong, if $num is NOT equal to 0 then your query MUST have found at least one account. So you need to change your if statement to:
if($num == 0){ //if 0 rows were found - the account was not found thus it doesn't exist
echo "Account doesn't exist!";
}
Notice also i did not add header("location: ucp.html");. You cannot display output + relocate the user to another page. You either do one or the other, or you will get an error/warning.
Finally check your MYSQL is not causing an error by adding a check at the end with :
$result = mysql_query($query) or die(mysql_error());
Final tip, you should avoid using mysql_* and look into mysqli_* or PDO best explained here:
Why shouldn't I use mysql_* functions in PHP?
Related
After getting the user-info from my sql database I would like to check if some of the fields are empty and continue the script based on that. A simplified piece of code would look like this:
$userData = mysql_query("SELECT * FROM user WHERE user='".$user."' LIMIT 1");
if(mysql_num_rows($data) == 1){
$u_info = mysql_fetch_assoc($data);
if(empty($u_info['u_mobile'])){
echo 2;
exit();
} else {
echo 1;
exit();
}
} else {
echo 3;
exit();
}
The problem is the empty statement checking the recieved field. I've tried using empty(), isset(), not_null() and array_key_exists() with no luck and can't get around to what I'm doing wrong.
I also tried if($u_info['u_mobile']) == '' || $u_info['u_mobile']) == NULL) but that doesnæt work either.
Why is this, or how can I go about getting this information?
I need to collect the user-information and send them to fill out the information I don't have...
You're setting the query result to $userData but then you're using mysql_fetch_assoc($data); -- doh. You need to pass the variable that you set the query result to:
$u_info = mysql_fetch_assoc($userData);
It's OK, it is still 10AM EST so this can happen in the morning =)
I suggest that you turn on PHP error reporting. PHP would have alerted you that the array values were trying to access do not exist, saving you a lot of wasted frustration.
$userData = mysql_query("SELECT * FROM user WHERE user='".$user."' LIMIT 1");
if(mysql_num_rows($userData ) == 1){
$u_info = mysql_fetch_assoc($userData );
if(empty($u_info['u_mobile'])){
echo 2;
exit();
} else {
echo 1;
exit();
}
} else {
echo 3;
exit();
}
Please Run code..I think it will be compile better it was minor mistake
So i want to check if a post exists in the database but i have some problems with redirection.
This is my work so far:
echo '<br>';//the $row part tells the DB what post his looking on
echo 'View comments';
This is the show comment button that leads to the section where you see the comments for the post.
<?php
require_once ('checkp.php');
I have it to require the post checking script once.
<?php
include ('variables.php');
//connects to DB
$dbc=mysql_connect($host,$user,$pass);
if ($dbc) {
} else {
echo ('Failed to connect to MySql; '. mysql_error());
}
//selects db from MySQl
$sqldb=mysql_select_db('a2318052_blog');
$pid=$_GET['post_id'];
$query1="SELECT * FROM posts_b WHERE id='$pid'";
$sql=mysql_query($query);
if ($sql) {
} else {
echo "cant run query";
}
if (mysql_num_rows($sql) > 0) {
echo "that post does not exist!";
} else {
header ("location: comments.php?post_id='. $pid.'");
}
?>
And this is the script that checks for a empty result and then redirects back. I believe its something with the redirect here (header ("location: comments.php?post_id='. $pid.'");)
You mixed the quotes on the redirect:
"location: comments.php?post_id='. $pid.'"
should be
"location: comments.php?post_id=". $pid
The dot in php is used to concatenate strings. Bu there you are opening the string with " and closing it with '.
EDIT : Also as someone else already noticed you're using query instead of query1.
Also i suppose instead of:
if (mysql_num_rows($sql) > 0) {
echo "that post does not exist!";
you wanted something else:
if (mysql_num_rows($sql) == 0) {
echo "that post does not exist!";
You probably don't want single quotes around the post_id...
header ("location: comments.php?post_id=$pid");
first change pid
$pid = intval($_GET['post_id']); // for security
after that
if (mysql_num_rows($sql) == 0)
{
echo "that post does not exist!";
}
else
{
header("Location: comments.php?post_id=".$pid);
}
$query1="SELECT * FROM posts_b WHERE id='$pid'";
$sql=mysql_query($query);
You're using $query instead of $query1. That's probably the problem (along with the concatenation stuff other users have pointed out).
There's also a few other things, like I think you mixed up your if/else statement here:
if (mysql_num_rows($sql) > 0) {
echo "that post does not exist!";
} else {
header ("location: comments.php?post_id='. $pid.'");
}
Maybe you want the order to be reversed?
Also, you should look into avoiding SQL injection!
Sending a query with a $GET variable is pretty dangerous, as users can manipulate the URL and send malicious queries.
$pid=$_GET['post_id'];
Prepared statements are ideal, but for now, you could use mysql_real_escape_string around your $GET variable. It stops people from sending queries you really don't want done.
So I am having problems with my login script. I have a salted MD5 hash stored in my database, and well... When I use this statement followed by this code, it logs in whatever the password is.
I'm not sure if it's the syntax, or it's just the way I use it, but it logs in if the user exists even if the password is 'lalala' and the person types in 'chicken'.
$sql = ("select * from website where `Email`='$user' and `Password`='$pass'");
$query = mysql_query($sql);
if ($query) {
$data = mysql_fetch_array($query, MYSQL_ASSOC);
if (sizeof($data) > 0) {
$_SESSION['vuser'] = $_POST['vuser'];
header('Location: /');
die;
}
}
This is how it is run:
index.php --> Presses login (Sends POST data) --> login.php (This script) --> (If it logs in, it returns to /index.php, but if not, it will go to /login.php.
I have a test account on there called 'blah' with the salted MD5 hashed as 'lolcatz'. If I were to type in 'blah' in the username part, with the password as 'stackoverflow', it will go to 'index.php'
Any ideas?
try to print_r($data) to see what the mysql_fetch_array function returns. It could be that it returns FALSE, which will overpass your condition if (sizeof($data) > 0)
Your logic is incorrect. mysql_fetch_array() will return an array representing one SINGLE row of data from the query results, or a boolean FALSE in case of failure (query has no rows, or you're fetching from something OTHER than a query result).
You should be doing:
$result = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($result) > 0) {
... user exists ...
} else {
... user does not exist ...
}
Don't use this:
if ($query) {
$data = mysql_fetch_array($query, MYSQL_ASSOC);
if (sizeof($data) > 0) {
$_SESSION['vuser'] = $_POST['vuser'];
header('Location: /');
die;
}
}
What is the reason behind measuring the size of data? That is a poor way to validate.
Do this instead :
if ($query) {
if(mysql_num_rows($query)>0){
// In the above line, we check a user with that username and password exists
$_SESSION['vuser'] == $_POST['vuser'];
header('Location: /');
} else echo "Bad password";
} else echo "Connection error";
As a side note, please stop using mysql_* functions now or real soon. They are going to be removed in the next version of PHP, and are less secure. You can use the PHP PDO Class.
I am also assuming you are not storing the $username and $pass directly in the database. If you are, stop it now, and use hash functions to store the password. You can use md5 and/or sha1 hash methods.
As it is said, you can also use mysqli similar down below
$dbq=("SELECT * FROM users where username='$uname'");
$dbresult=mysqli_query($con,$dbq);
where $con is the connection query which you've to write in mysqli.
Now you can fetch the data similar down below.
$obj=$dbresult->fetch_object();
$dbmail=$obj->Email;
$dbuname=$obj->Password;
$sql = ("select * from website where `Email`='$user' and `Password`='$pass'");
$query = mysql_query($sql);
$row = mysql_fetch_array($query, MYSQL_ASSOC);
if ($row) {
$_SESSION['vuser'] = $_POST['vuser'];
header('Location:"go where ever you want to i dont care"');
}
else{ //some error message}
So basically what I have set up here is a very simple and generic log in. I have the entire code copy and pasted because maybe its important somehow. However-
$user = mysql_real_escape_string($_POST['User']);
$pass = mysql_real_escape_string(md5($_POST['Pass']));
$conn = mysql_connect("localhost", "root") or die(mysql_error());
(mysql_select_db('fireworks', $conn));
$ask = "SELECT * FROM name WHERE (User = '" . $user . "') and (Pass = '" . $pass . "');";
$result = mysql_query($ask);
The segment of code below is completely ignored! When I press log in (From the index page) It is suppose to run a series of checks. If the user decides to not put anything inside the user and password text boxes then it is suppose to return the string show below:
if (strlen($user) < 1){
if (strlen($pass) < 1){
print "<p class = 'Back'>Epic Fail</p>";
print "<p>You forgot to put in your Username or Password.</p>";
}
}
(^Up until here) But it doesn't. Instead its just a blank page. But everything else works fine. If I type in a fake user then it returns "YOU FAIL!" If I type a valid user it returns "WELCOME BACK."
if (strlen($user) >= 1){
if (mysql_num_rows($result) >= 1) {
while ($row = mysql_fetch_array($result))
{
print "<p class='Back'>Welcome back</p><p>" . $row['User'] . "</p>";
}
}else{
print "YOU FAIL!!!";
}
}
Any suggestions? EXTRA NOTES: The database is called fireworks the table is called name there are three columns in the name table. nameID, User, and Pass. (Idk how this is useful but sometimes it is.)
Your code:
if (strlen($user) < 1){
if (strlen($pass) < 1){
print "<p>You forgot to put in your Username or Password.</p>";
}
}
In actual fact, this won't check for $user or $pass being blank; it will only give the error message if both of them are blank.
Each test is okay on its own, but the way it's written, the test for $pass will only be run if the $user test has already given a true result.
What you need to to is write them together with an or condition, like so:
if (strlen($user) < 1 or strlen($pass) < 1){
....
}
Hope that helps.
try this:
if (strlen($user) < 1 || strlen($pass) < 1){ .... }
You're nesting the ifs, so the "Epic Fail" is only displayed when both the user name and password aren't entered.
You might want to change it to this:
if (strlen($user) < 1 || strlen($pass) < 1)
{
print "<p class = 'Back'>Notice</p>";
print "<p>You forgot to put in your Username or Password.</p>";
}
In the documentation of mysql_real_escape_string it says that it will attempt to connect to database for the character set. If you did not connect to database at all before the check it might very well be the case. You can check if error reporting to see if it returned E_WARNING level error.
Another thing is that you should avoid database calls when it is not needed. If thats the whole part of the important code, you should call both checks before you try to escape them and continue with database stuff. Also, empty() function might help you as well.
if(!empty($_POST['User']) || trim(strlen($_POST['User'])) < 1) {
// database stuff
}
I created this account registration activation script of my own, I have checked it over again and again to find errors, I don't see a particular error...
The domain would be like this:
http://domain.com/include/register.php?key=true&p=AfRWDCOWF0BO6KSb6UmNMf7d333gaBOB
Which comes from an email, when a user clicks it, they get redirected to this script:
if($_GET['key'] == true)
{
$key = $_GET['p'];
$sql = "SELECT * FROM users
WHERE user_key = '" . $key . "'";
$result = mysql_query($sql) or die(mysql_error());
if(mysql_affected_rows($result) > 0)
{
$sql = "UPDATE users
SET user_key = '', user_active = '1'
WHERE user_key = '" . $key . "'";
$result = mysql_query(sql) or die(mysql_error());
if($result)
{
$_SESSION['PROCESS'] = $lang['Account_activated'];
header("Location: ../index.php");
}
else
{
$_SESSION['ERROR'] = $lang['Key_error'];
header("Location: ../index.php");
}
}
else
{
$_SESSION['ERROR'] = $lang['Invalid_key'];
header("Location: ../index.php");
}
}
It doesn't even work at all, I looked in the database with the user with that key, it matches but it keeps coming up as an error which is extremely annoying me. The database is right, the table and column is right, nothing wrong with the database, it's the script that isn't working.
Help me out, guys.
Thanks :)
Change $_GET['key'] == true to $_GET['key'] == "true"
You do before this if, a successful mysql_connect(...) or mysql_pconnect(...) ?
Change mysql_affected_rows($result); to mysql_num_rows($result);. Affected you can use for DELETE or UPDATE SQL statements.
Before you second if was opened, add before you second mysql_result(...), mysql_free_result($result); to free memory allocated to previous result.
if($result) change to if(mysql_affected_rows($result));. You can do that here.
After the header(...); function call's add a return 0; or exit(0); depends on your complete code logic.
You are using $key variable in SQL statements, to get your code more secure on SQL Injection attacks get change $key = $_GET['p']; to $key = mysql_real_escape_string($_GET['p']);
I think your location in header() functions fails. In header() url address should be full like: http://www.example.com/somewhere/index.php
And check your $_GET['p'] variable exists!! If this not exist and if $_GET['key'] exists, you find all activated users. Then i think the setting user_key to '' is nessesary if you have user_activated marker.
you shouldnt be using:
if(mysql_affected_rows($result) > 0)
You should be using mysql_num_rows()
Your problem is:
$result = mysql_query($sql) or die(mysql_error());
"or" makes your statement boolean so $result gets a True instead of value returned by mysql_query()
echo 'Hello' or die('bye'); // outputs nothing, because result is True not 'Hello'
3 or die() == True; // true
3 or die() != 3; // true
OR is the same as || and it is operator of logical statement.
This will work:
$result = mysql_query($sql);
if(!$result) die(mysql_error());
The same mistake was made a few hours ago: link
Cases where OR can be used:
defined('FOO') or
define('FOO', 'BAR');
mysql_connect(...) or die(...);
mysql_select_db( .... ) or die(...);
mysql_query('UPDATE ...') or die(...);
if(FOO or BAR) { ... }