I use a mysql_affected_rows on a query but it seems to return false even though the query did execute so i'm a bit confused....
This is what i have:
$check = mysql_query("DELETE FROM $table
WHERE name = '".$darray[0]."' AND
password = '".$darray[1]."' AND uid = '$uid'
AND validation = '22'")
or die(mysql_error());
if(mysql_affected_rows($check)>0){
echo 1;
exit;
} else {
echo 'Less than one!';
exit;
}
Any idea why it says less than one - even though my query did actually delete the row ?
mysql_affected_rows() takes the link identifier (i.e., the connection resource), not the result.
mysql_affected_rows takes in a connection link, not a query. You can leave that parameter empty and it will refer to the last query executed on that connection.
Solved:
Error was that mysql_affected_rows() doesn't expect the query.
More info here: http://php.net/manual/es/function.mysql-affected-rows.php
$check = mysql_query("DELETE FROM $table
WHERE name = '".$darray[0]."' AND
password = '".$darray[1]."' AND uid = '$uid'
AND validation = '22'")
or die(mysql_error());
if(mysql_affected_rows() >0){
echo 1;
exit;
} else {
echo 'Less than one!';
exit;
}
Related
Working on a log in system, but i keep getting this error
//$User = 'kv96';
//$Pass = 'passkv';
//echo isValidLogin($User, $Pass);
function isValidLogin($username, $password) {
$query = mysqli_query($link,"SELECT * FROM Log_in WHERE Password = '$Pass' AND User_ID ='$User'"); //Finds the database and chooses the row
//$result = mysqli_query($query);
$row = mysqli_fetch_array($result); //Fetches the row
if($row['User_ID'] != null && $row['Password'] != null){return true;}
else{return false;}
function getUsernameRole($username) {
return "instructor";
}
mysqli_close($link);
?>
Can someone explain why this error is popping, i dont see why the query is failing?
I've noticed you commented out your $result yet you were using to fetch the database array. You should be using $query instead, or get rid of the 2 // before your $result.
Not only that, you forgot to parse $link through the parameters of your function. Therefore the query will not be successful.
Another problem, you used $pass and $user variables inside of your query, however, you have not passed them through the parameters of your function either. You must change $username to $user and so on..
I've also changed your while loop to a row count. This will save you from using unnecessary code and is way more practical; saves you doing a while loop and checking if values return null.
function isValidLogin($link, $user, $pass) { // parsing through the connection link and $user, $pass variables
$query = mysqli_query($link,"SELECT * FROM Log_in WHERE Password = '$Pass' AND User_ID ='$User'"); //Finds the database and chooses the row
$count = mysqli_num_rows($query);
if($count > 0){
return true;
} else {
return false;
}
}
A suggestion I would like to make (and HIGHLY recommend) is to use prepared statements to protect against SQL injection, however, you can find many posts on how to do that.
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
I have written a script in php to reset user's password, and how do I check if password is updated in a table?
For example, if a data in the tuple/column has been changed, then send email. Please check comments in the script.
$dbcc = mysqli_connect(HOST,NAME,PASSWORD,DATABASE) or die('Error can not connect to database');
$query = "SELECT uid,email FROM `corporate` WHERE (email='$chk_email')";
$result = mysqli_query($dbc, $query);
//found
if(#mysqli_num_rows($result) == 1)
{
$ROW = mysqli_fetch_array($result);
$sent_email = $ROW['email']; //get email
$id = $ROW['uid']; //get uid
$new_password = generatePassword(8);//generates 8 char long random password
$enc_password = md5($new_password); //encrypt
$statement = "UPDATE corpoorate SET password=".$enc_password." WHERE uid ='$id'";
$go = mysqli_query($dbcc,$statement) or die(mysqli_error());
mysqli_close($dbcc);
/*
* HOW DO I CHECK IF PASSWORD IS UPDATED IN THE DATABASE?
* IF IT IS, SEND EMAIL
* IF $go==true does not work!
**/
if($go==true){
$sendmessage = "We have generated a new password token for you.\n Your password is reset to ".$new_password." \n Please note that this password is not secure. Once you login, please reset your password.\n ";
mail($sent_email,'Password Reset',$sendmessage,'From: address#gmail.com');
}
header("Location : http://limozoor.com/login/signin.php");
exit();
}//if
mysqli_close($dbcc);
Why don't you use mysqli_affected_rows?
// remove: $go = mysqli_query($dbcc,$statement) or die(mysqli_error());
$qry =# mysqli_query($dbcc, $statement);
$aff =# mysqli_affected_rows($dbcc);
if ($qry === true && $aff > 0) {
mail(...);
}
From manual;
mysqli_query:
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.
mysqli_affected_rows:
An integer greater than zero indicates the number of rows affected or retrieved. Zero indicates that no records where updated for an UPDATE statement, no rows matched the WHERE clause in the query or that no query has yet been executed. -1 indicates that the query returned an error.
http://php.net/manual/en/mysqli.affected-rows.php
http://php.net/manual/en/mysqli.query.php
Because of your or die(mysqli_error());-condition the password will always be updated in the table if it reaches those lines of execution.
However, I am sceptic towards your if(#mysqli_num_rows($resultt) == 1) because if there is any error in your first SQL-query, you are supressing all error messages there (by using #), which makes me think that you never even try to execute the UPDATE statements.
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) { ... }
I have a textbox UserName and a Check Availability button next to it..... I have checked the availability by passing UserName textbox value..... But it doesn't seem to work....
Here is what i am doing?
echo $UserName = $_GET['CheckUsername'];
$_SESSION['state'] = $State;
$queryres = "SELECT dUser_name FROM tbl_login WHERE dUser_name='$UserName'";
$result = mysql_query($queryres,$cn) or die("Selection Query Failed !!!");
if($result==true) // this condition doesn't seem to work
{
echo "User Name Available";
}
else
{
echo "Sorry user name taken";
}
Please make sure you're escaping your inputs for MySQL. Passing data directly from $_GET, $_POST or any of the other superglobals is unsafe.
// Escape any quote characters in the input
$UserName = mysql_real_escape_string($_GET['CheckUsername'], $cn);
$_SESSION['state'] = $State;
$queryres = "SELECT dUser_name FROM tbl_login WHERE dUser_name='$UserName' LIMIT 1";
$result = mysql_query($queryres, $cn) or die("Selection Query Failed !!!");
if (mysql_num_rows($result) > 0) {
echo 'User name exists in the table.';
} else {
echo 'User name does not exist in the table.';
}
if ($result == false)
{
echo "not available";
}
else
{
echo "available";
}
The reason yours doesn't work is because the value of $result will not be true as it contains an array. You could do it by reversing the statement to check for false first.
You can also do it with mysql_num_rows
if (mysql_num_rows($queryres) > 0)
{
echo "User name taken";
}
from http://php.net/mysql_query :
Return Values
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.
So to start off with, your if statement will never evaluate to false, because you have the "or die" on the mysql_query (which is activate when mysql_query returns false).
But your if condition is wrong altogether, because you don't want to know if the query failed, but if any results were returned. For this you probably want to use mysql_num_rows.
As a small tip, since you only need to know if there's 1 matching username, add "LIMIT 1" to the end of your query. Then mysql will return as soon as it hits the first match, instead of searching th whole table for more results.
As an alternative method, you could use a COUNT() query, and check the number returned in the result set.
Although this question has already an adequate answer, I'll give you another option. Simply remove the "==true" in the IF condition and it will automatically test for the presence of a value instead of a boolean comparison.
if($result) // this condition will now work
{
echo "User Name Available";
}
else
{
echo "Sorry user name taken";
}
You can use this if you want to preserve the signature of your code.
After Executing the Query just mysql_num_rows($result) which will return you the Count of Rows is fetched.
$queryres = "SELECT dUser_name FROM tbl_login WHERE dUser_name='$UserName'";
$result = mysql_query($queryres,$cn) or die("Selection Query Failed !!!");
if (mysql_num_rows($result))
{
echo "Username available";
}
else
{
echo "Username not available";
}