PHP if else condition on validation [closed] - php

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am trying to create an activation page that will GET the API & ACT codes from the url.
Then I am trying to query the DB on those codes to check if they're valid.
If they are not valid, I would like to echo an error stating echo "<strong><font color=red>Your Activation Code has Expired, or Your Activation Code is not Valid!</font></strong>";
If it is valid, then I would like to update with the 2nd SQL Query - "UPDATE users SET status='1', date_activated='$Activation_Date', Activation='' WHERE Activation='$Activation' AND API='$API' AND status='0'"
If there is NO API&ACT code in the URL, I would like to echo "CONTENT"
<?
require 'admin/config.php';
require 'Connection.php';
error_reporting(E_ALL);
$API = $_REQUEST['api'];
$Activation = $_REQUEST['act'];
$sql= mysql_query("SELECT * WHERE Activation='$Activation'");
if ($sql = 0) { echo"ERROR";}
else {
$Activation_Date = date('m-j-y - h-iA');
$sql = mysql_query("UPDATE users
SET status='1', date_activated='$Activation_Date', Activation=''
WHERE Activation='$Activation' AND API='$API' AND status='0'");
if($sql == 0){
echo "<strong><font color=red>Your Activation Code has Expired, or Your Activation Code is not Valid!</font></strong>";
} elseif ($sql > 0) {
echo "content";
}
}
?>

What you need to check for, is if a row exists.
To check if it exists and base yourself on the following model:
$sql = mysql_query("SELECT * WHERE Activation='$Activation'");
if(mysql_num_rows($sql) > 0){
//do something here or show error because relation already exists
}
else{
//relation already do not exists. so you can insert the record here
}
Then, to check if your UPDATE was truly successful, use mysql_affected_rows():
Sidenote: This function may require that you pass a db connection variable to it.
$sql = mysql_query("UPDATE users .... ");
if(mysql_affected_rows() > 0){
// do something
}
else {
// do something else
}
Check for errors against your PHP and MySQL:
Add error reporting to the top of your file(s) right after your opening PHP tag
for example <?php error_reporting(E_ALL); ini_set('display_errors', 1); then the rest of your code, to see if it yields anything.
Also add or die(mysql_error()) to mysql_query().
If you get errors about deprecation notices, then you will need to switch over to either mysqli_ or PDO.
You can consult one of my answers here https://stackoverflow.com/a/22253579/1415724 to check if a row exists.
It uses a few methods, including a prepared statement which is something you should be using because you are open to an SQL injection.
Sidenote: The connection API that you are using is unknown. Make sure that you are using the same one as your query being mysql_. If it's mysqli_ or PDO, those different APIs do not intermix. You must use the same one from connecting to querying.
Also, just a quick note about if ($sql = 0). The single equal sign "assigns" instead of "comparing" such as == or ===.
You stated in comments:
"IF the Activation code is active (the md5 has will be there)"
I hope you're not using that for password storage. If so, don't. That function is no longer safe to use to store passwords with.
Use one of the following:
CRYPT_BLOWFISH
crypt()
bcrypt()
scrypt()
On OPENWALL
PBKDF2
PBKDF2 on PHP.net
PHP 5.5's password_hash() function.
Compatibility pack (if PHP < 5.5) https://github.com/ircmaxell/password_compat/
Other links:
PBKDF2 For PHP
Seeing <? make sure that short tags are enabled. If not, change that to <?php.
HTML stickler.
<font color=red> the <font> tag is deprecated/obsole and isn't supported by HTML5.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/font
It's best to use inline CSS if you are sending anything via Email.
I.e.: <p style="color:red;">Hello world</p>
Here are a few references:
http://www.tizag.com/cssT/inline.php
Inline <style> tags vs. inline css properties
http://webdesign.about.com/od/beginningcss/qt/tipcssinlinesty.htm

Remarks
Checking mandatory parameters:You can test if parameters are set like this:
isset(variable_name).
In the SELECT query there is missing the FROM clause which states the table to select from.I assume it is "user" like in the UPDATE query.
After a SELECT query, the cursor should be freed again, when it is no longer in use: mysql_free_result($sql);
(Error) Tests
The result of a query is ===false if the query could not be executed corectly.
After having SELECTed records, the function mysql_num_rows() shows the number or records retrieved.
After having UPDATed a table, the function mysql_affected_rows() gives the number of affected records.
Code snippet
// Get parameters and check if mandatory parameters are set
$API = isset($_REQUEST['api']) ? $_REQUEST['api'] : false;
$Activation = isset($_REQUEST['act']) ? $_REQUEST['act'] : false;
if ( ($API===false) || ($Activation===false)) {
$which = ($API === false ) ? '"api"' : '';
$which .= ($Activation === false) ? ((empty($which) ? '' : ', ') . '"act"') : '';
echo "ERROR: Parameter(s) missing: $which";
return;
}
// Select activation record
$sql= mysql_query("SELECT * FROM users WHERE Activation='$Activation'");
if ($sql===false) {
echo "SQL ERROR: " . mysql_error();
return;
} else {
$nrows = mysql_num_rows();
mysql_free_result($sql);
if ($nrows < 1) {
// No matching record found
echo "ERROR: No activation record found";
return;
} else {
// Update users record
$Activation_Date = date('m-j-y - h-iA');
$sql = mysql_query("UPDATE users
SET status='1', date_activated='$Activation_Date', Activation=''
WHERE Activation='$Activation' AND API='$API' AND status='0'");
if ($sql===false) {
echo "SQL ERROR: " . mysql_error();
} elseif(mysql_affected_rows() < 1) {
// No matching record found for updating
echo '<span style="color:red; font-weight:bold;">Your Activation Code has Expired, or Your Activation Code is not Valid!</span>';
} else {
echo "content";
}
}
}

Here is what I ended up with.
This is a Tweak from #hherger's answer....
// Report all errors
error_reporting(E_ALL);
// Get parameters and check if mandatory parameters are set // Get parameters and check if mandatory parameters are set
$API = isset($_REQUEST['api']) ? $_REQUEST['api'] : false;
$Activation = isset($_REQUEST['act']) ? $_REQUEST['act'] : false;
if ( ($API===false) || ($Activation===false)) {
}
// Select activation record
$sql= mysql_query("SELECT * FROM users WHERE Activation='$Activation'");
if ($sql===false) {
echo "SQL ERROR: " . mysql_error();
return;
} else {
$nrows = mysql_num_rows($sql);
mysql_free_result($sql);
if ($nrows < 1) {
// No matching record found
echo "REDIRECT USER TO HOME PAGE";
return;
} else {
// Update users record
$Activation_Date = date('m-j-y - h-iA');
$sql = mysql_query("UPDATE users
SET status='1', date_activated='$Activation_Date', Activation=''
WHERE pinAPP_Activation='$Activation' AND API='$API' AND status='0'");
if ($sql===false) {
echo "SQL ERROR: " . mysql_error();
} elseif(mysql_affected_rows() < 1) {
// No matching record found for updating
echo '<span style="color:red; font-weight:bold;">Your Activation Code has Expired, or Your Activation Code is not Valid!</span>';
} else {
echo "ECHO SUCCESS DISPLAY!";
}
}
}

Related

mysqli multi query separation

I know you can run multiple queries with mysqli_multi_query but I have a problem :
For a registration page I want to perform 2 checks and then an insert :
Check1 = Does username exist?
Check2 = Email already been used?
If both checks are negative then do the insert query.
But how can I sepperate the errors ?
when a username exists it has to return 'Username already exists'
if email is already been used it has to return 'Email already in use'
Here is my code:
$sql = "check username query; ";
$sql .= "check email query; ";
$sql .= "Insert query";
if (mysqli_multi_query($conn,$sql)) {
do
{
if ($result=mysqli_store_result($conn)) {
while ($row=mysqli_fetch_row($result)) {
if (mysqli_num_rows($result) > 0) {
//DO STUFF
//Here do i need to return if the username or email exists or not.
};
mysqli_free_result($result);
};
} else {
echo 'Query fout!';
};
while (mysqli_next_result($con));
};
mysqli_close($con);
You do not write a ; after an if statement or a loop. Furthermore, your do {} while(); loop is not in the correct format.
Correct Format:
$sql = "check username query; ";
$sql .= "check email query; ";
$sql .= "Insert query";
if (mysqli_multi_query($conn,$sql)) {
do {
if ($result = mysqli_store_result($conn)) {
while ($row = mysqli_fetch_row($result)) {
if (mysqli_num_rows($result) > 0) {
//DO STUFF
//return if the username or email exists
}
mysqli_free_result($result);
}
}
else {
echo 'Query fout!';
}
} while (mysqli_next_result($con));
mysqli_close($con);
}
mysqli_multi_query() is not the tool to use for this.
That mysql[i] requires you to jump through hoops to execute more than one DML operation per call provides a lot of protection against sql injection (but it still falls a long way of a full solution for such attacks). There is no need to implement these as a multi-statement-query.
There is a performance and scalability benefit to limiting the number of round trips to the database - but you can do this:
SELECT SUM(IF('$username'=user.username, 1, 0)) AS usernames,
SUM(IF('$email'=user.email, 1, 0)) as emails
FROM users
WHERE username='$username' OR email='$email'
to get the results in a single query.
It would be even more efficient to not bother with a SELECT, but instead add a unique index to each of the attributes in the database then handle a duplicate record error if the INSERT fails although this does not make for such a nice user experience. OTOH it does prevent enumeration attacks against the database.

How can i check if a single mysql field is empty in php

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

If statement is not working correctly

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?

Duplicate check before adding into database

I have a code which kinda works, but not really i can't figure out why, what im trying to do is check inside the database if the URL is already there, if it is let the user know, if its not the go ahead and add it.
The code also makes sure that the field is not empty. However it seems like it checks to see if the url is already there, but if its not adding to the database anymore. Also the duplicate check seems like sometimes it works sometimes it doesn't so its kinda buggy. Any pointers would be great. Thank you.
if(isset($_GET['site_url']) ){
$url= $_GET['site_url'];
$dupe = mysql_query("SELECT * FROM $tbl_name WHERE URL='$url'");
$num_rows = mysql_num_rows($dupe);
if ($num_rows) {
echo 'Error! Already on our database!';
}
else {
$insertSite_sql = "INSERT INTO $tbl_name (URL) VALUES('$url')";
echo $url;
echo ' added to the database!';
}
}
else {
echo 'Error! Please fill all fileds!';
}
Instead of checking on the PHP side, you should make the field in MySQL UNIQUE. This way there is uniqueness checking on the database level (which will probably be much more efficient).
ALTER TABLE tbl ADD UNIQUE(URL);
Take note here that when a duplicate is INSERTed MySQL will complain. You should listen for errors returned by MySQL. With your current functions you should check if mysql_query() returns false and examine mysql_error(). However, you should really be using PDO. That way you can do:
try {
$db = new PDO('mysql:host=localhost;db=dbname', $user, $pass);
$stmt = $db->query('INSERT INTO tbl (URL) VALUES (:url)');
$stmt->execute(array(':url' => $url));
} catch (PDOException $e) {
if($e->getCode() == 1169) { //This is the code for a duplicate
// Handle duplicate
echo 'Error! Already in our database!';
}
}
Also, it is very important that you have a PRIMARY KEY in your table. You should really add one. There are a lot of reasons for it. You could do that with:
ALTER TABLE tbl ADD Id INT;
ALTER TABLE tbl ADD PRIMARY KEY(Id);
You should take PhpMyCoder's advice on the UNIQUE field type.
Also, you're not printing any errors.
Make sure you have or die (mysql_error()); at the end of your mysql_* function(s) to print errors.
You also shouldn't even be using mysql_* functions. Take a look at PDO or MySQLi instead.
You're also not executing the insert query...
Try this code:
if(isset($_GET['site_url']) ){
$url= $_GET['site_url'];
$dupe = mysql_query("SELECT * FROM $tbl_name WHERE URL='$url'") or die (mysql_error());
$num_rows = mysql_num_rows($dupe);
if ($num_rows > 0) {
echo 'Error! Already on our database!';
}
else {
$insertSite_sql = "INSERT INTO $tbl_name (URL) VALUES('$url')";
mysql_query($insertSite_sql) or die (mysql_error());
echo $url;
echo ' added to the database!';
}
}
else {
echo 'Error! Please fill all fileds!';
}
As PhpMyCoder said, you should add a unique index to the table.
To add to his answer, here is how you can do what you want to do with only one query.
After you add the unique index, if you try to "INSERT INTO" and it result in a duplicate, MySQL will produce an error.
You can use mysql_errno() to find out if there was a duplicate entry and tell the user.
e.g.
$sql = "INSERT INTO $tbl_name (URL) VALUES('$url')";
$result = mysql_query($sql);
if($result === false) {
if(mysql_errno() == $duplicate_key_error) {
echo 'Error! Already in our database!';
} else {
echo 'An error has occurred. MySQL said: ' . mysql_error();
}
}
mysql_error() will return the mysql error in plain english.
mysql_errno() returns just the numeric error code. So set $duplicate_key_error to whatever the code is (I don't know it off the top of my head) and you are all set.
Also note that you don't want to print any specific system errors to users in production. You don't want hackers to get all kinds of information about your server. You would only be printing MySQL errors in testing or in non-public programs.
ALSO! Important, the mysql functions are deprecated. If you go to any of their pages ( e.g. http://php.net/manual/en/function.mysql-errno.php) you will see recommendations for better alternatives. You would probably want to use PDO.
Anyone who wants to edit my answer to change mysql to PDO or add the PDO version, go ahead.

Account activation PHP

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) { ... }

Categories