I'd like to check if value entered in the php form already exist in MySQL database, and show message if same value is found, and ofc different message if no duplicate was found.
I used this code:
$result = $conn->query("SELECT id FROM tb_cform WHERE u_email = '".$_POST['u_email']."'");
if($result->num_rows == 0) {
echo'Mail address was not forund in database!';
} else {
die("Mail address already exist in the database!");
}
However, i keep getting the "else" part of the statement whatever email I enter, so I always get "Mail address already exist in the database!" message.
Any help please?
Oh, got it, I placed the whole code at the wrong place in file, it was placed after I actually run a query for adding the email in the database, and therefore check always returned that mail is found, my mistake, sorry!
Related
I have the following piece of code that keeps returning error, meaning that it enters the if branch, even though there are no duplicates.
//Check for duplicates
List<Account> accounts = new List<Account>();
accounts.add(acc);
if(Datacloud.FindDuplicates.findDuplicates(accounts).size() != 0){
//Manage error
}
Why does it find duplicates even though ther are non duplicates in the database? Maybe it finds the record that's being tested itself?
Thank you!
i want to handle the probable errors of mysql db. in my case, i have users table that has 7 columns. column email and username values should be unique and i set that for them. but in my sign up form, when users enter and submit their account infos, their entered username and email can be in the database. so in this case, mysql throws an error. for example in my database there is a row with test#test.com email and saman138 username. if a user enters test#test.com for email and saman138 for username, mysql throws an error like this:
Duplicate entry 'saman138' for key 'users.username_UNIQUE'
But the main problem is that i cant display the right error to user. I actually dont know how to do that in the best with the highest performance. For example how can i recognize that the users entered password is duplicated in the database and display the right error to user? I can send two extra queries to get the row that has the entered email or password and then send an error with this message:
your entered username and email already exists in database. Please
enter an other email and username.
this is my codes to insert users infos in to the users table:
import bcrypt from "bcrypt";
import { SignUpInfos } from "../interfaces/Interfaces";
import { mysql } from "../utils/DB";
const signUpUser = async (datas: SignUpInfos) => {
const hashedPassword = await bcrypt.hash(datas["user-password"], 10);
const results = await new Promise((resolve, reject) => {
mysql.query(
"INSERT INTO users ( fullname, email, username, password ) VALUES ( ?, ?, ?, ? )",
[
datas["user-fullname"],
datas["user-email"],
datas["user-username"],
hashedPassword,
],
(err, result) => {
if (err) reject(err);
else resolve(result);
}
);
});
return results;
};
export { signUpUser };
so what is the best way to return the right error message if there was an error? is there any best way to do that or i should send to extra queries? thanks for help :)
As according to the MVC pattern, input validation is typically done before the request gets to the database (in your javascript code), not relying on database errors to inform you that something is wrong.
For example:
First you might check that a username is a valid username through business rules in the javascript; checking that the username doesnt have spaces or something.
Then you might search the database to see if there are any users with a given name, return the number and then use that to tell the user that a name is already taken. Only once this search returns that there are no other similar usernames in the database should you actually let them submit the new account.
But, that is not to say you should abandon the database rules altogether because they are important to ensuring someone doesnt do something dodgy like mess with your database (as an extreme) by bypassing the javascript code somehow and adding duplicate accounts -- that would be tragic.
Where does input validation belong in an MVC application?
"with the highest performance" -- "premature optimization". The login process, even when accounting for error cases, takes only milliseconds. There is no need to optimize this.
Also, since the usual case is "no errors" it is best to assume there will be no errors, then let some lower-level process (such as the databse INSERT) catch the error. If, instead, you checked for errors first, you would usually be wasting your time.
Anyway, the test and the insert must be done atomically, or else someone else can sneak in between your test and your insert and, say, grab the user_name. That is, the two must be combined into an "atomic" action. And the db, with UNIQUE constraints, does that nicely for you.
Last year I made a laravel site with an events table where I needed three fields to be unique for any event (place, date and time). I wasn't able to set up a validation request to do this so I added an unique index for these three fields directly through phpmyadmin and catching the exception that could happen if a duplicated event was inserted.
So basically my store() method has a try/catch like this:
try {
$event = new Event;
$event->place = $request->input('place');
$event->date = $request->input('date');
$event->time = $request->input('time');
$event->save();
return view(...);
} catch (\Illuminate\Database\QueryException $e) {
// Exception if place-date-time is duplicated
if($e->getCode() === '23000') {
return view('event.create')
->withErrors("Selected date and time is not available");
}
}
Well, now I had to change the app so events could be soft deleted and I simply added the 'deleted_at' field to the unique index, thinking it would be so easy... This approach doesn't work anymore so I've been reading here and there about this problem and the only thing I get is I should do it through a validation request with unique, but honestly I just don't get the syntax for this validation rule with three fields that can't be equal while a fourth one, deleted_at, being null.
My app checks for the available places, dates and times and doesn't let the user choose any not available event but no matter how many times I've told them there's always someone who uses the browser back button and saves the event again :(
Any help will be much appreciated. Thank you!
This is not a good approach to solve the problem.
You can do follow things to solve this problem
Before insert into database get a specific row if exist from database
and store into a variable.
Then check the data is already stored into the database or not.
If data is already there create custom validation message using Message Bag Like below.
$ifExist = $event
->wherePlace(request->input('place'))
->whereDate(request->input('date'))
->whereTime(request->input('time'))
->exist();
if ($ifExist) return 'already exist';
It might help you.
#narayanshama91 have pointed the right way.
You said you would like to use the unique rule to validate the input but the problem is that last week there was a post in Laravel Blog warning users of a possible SQL Injection via the unique rule if the input is provided by the user.
I would highly advise you to NOT USE this rule in this case since you depend on users input.
The correct approach in your case would be #narayanshama91 answer.
$ifExist = $event
->wherePlace(request->input('place'))
->whereDate(request->input('date'))
->whereTime(request->input('time'))
->exist();
if ($ifExist) {
return 'already exist';
}
Maybe the title is not that clear but assume this situation:
I have a form to update a specific row of a table. When I submit the form an UPDATE query is performed.
I count the number of affected rows to determine if the query went right or not.
$row->execute();
$count = $row->rowCount();
if($count==0){
http_response_code(500);
}else{
http_response_code(200);
}
This works well if the user submit the form by changing any data. If the form is left unchanged the query will affect 0 results and my code will return 500.
But the point is that the query was properly executed.
So my question is: is there a way mysql will tell me that 0 row where affected because nothing changed in the data instead of any other case (eg. wrong value in a field or so on?). So that my if can become something like this:
if($count==0||$no_field_changed==false){
Gordon already gave you the answer in his comment,
You should check the error conditions to see if the query succeeded
but just to make it obvious I will expand upon it for you.
$status = $row->execute();
if ( ! $status ) {
// the query errored
$arr = $row->errorInfo();
error_log(print_r($arr,1), 3, 'db_error.log'));
http_response_code(500);
exit;
}
// So if we get here the query ran successfully
if($row->rowCount() == 0){
// Nothing was changed by our query this time but it ran successfully
http_response_code(200);
}else{
// Something was changed by our query
http_response_code(200);
}
I have a small app where users create things that are assigned to them.
There are multiple users but all the things are in the same table.
I show the things belonging to a user by retrieving all the things with that user's id but nothing would prevent a user to see another user's things by manually typing the thing's ID in the URL.
Also when a user wants to create a new thing, I have a validation rule set to unique but obviously if someone else has a thing with the same name, that's not going to work.
Is there a way in my Eloquent Model to specify that all interactions should only be allowed for things belonging to the logged in user?
This would mean that when a user tries to go to /thing/edit and that he doesn't own that thing he would get an error message.
The best way to do this would be to check that a "thing" belongs to a user in the controller for the "thing".
For example, in the controller, you could do this:
// Assumes that the controller receives $thing_id from the route.
$thing = Things::find($thing_id); // Or how ever you retrieve the requested thing.
// Assumes that you have a 'user_id' column in your "things" table.
if( $thing->user_id == Auth::user()->id ) {
//Thing belongs to the user, display thing.
} else {
// Thing does not belong to the current user, display error.
}
The same could also be accomplished using relational tables.
// Get the thing based on current user, and a thing id
// from somewhere, possibly passed through route.
// This assumes that the controller receives $thing_id from the route.
$thing = Users::find(Auth::user()->id)->things()->where('id', '=', $thing_id)->first();
if( $thing ) {
// Display Thing
} else {
// Display access denied error.
}
The 3rd Option:
// Same as the second option, but with firstOrFail().
$thing = Users::find(Auth::user()->id)->things()->where('id', '=', $thing_id)->firstOrFail();
// No if statement is needed, as the app will throw a 404 error
// (or exception if errors are on)
Correct me if I am wrong, I am still a novice with laravel myself. But I believe this is what you are looking to do. I can't help all that much more without seeing the code for your "thing", the "thing" route, or the "thing" controller or how your "thing" model is setup using eloquent (if you use eloquent).
I think the functionality you're looking for can be achieved using Authority (this package is based off of the rails CanCan gem by Ryan Bates): https://github.com/machuga/authority-l4.
First, you'll need to define your authority rules (see the examples in the docs) and then you can add filters to specific routes that have an id in them (edit, show, destroy) and inside the filter you can check your authority permissions to determine if the current user should be able to access the resource in question.