How do i prevent creating the same user with the same info? - javascript

How do I check if the user already created the same LRN ?
and when I press the save button twice it creates two user with the same info
how do I prevent it ?
jQuery('#save_voter').submit(function(e){
e.preventDefault();
var FirstName = jQuery('.FirstName').val();
var LastName = jQuery('.LastName').val();
var Section = jQuery('.Section').val();
var Year = jQuery('.Year').val();
var LRN = jQuery('.LRN').val();
var Password = jQuery('.Password').val();
e.preventDefault();
if (FirstName && LastName && Section && Year && LRN && Password){
var formData = jQuery(this).serialize();
jQuery.ajax({
type: 'POST',
url: 'save_student.php',
data: formData,
success: function(msg){
showNotification({
message: "Student Successfully Added",
type: "success",
autoClose: true,
duration: 5
});

By creating a unique constraint on the username field. It seems that in your case the LRN field is the username field. Make it unique by
ALTER TABLE users ADD UNIQUE INDEX uname on users (LRN);
Then you can try something like this to tell the end user that the username is duplicated.
try{
$res =$connection->query(your user insert);
}catch(Exception $e){
echo 'Sorry already exists';
}

You need to do 3 steps :
Check manually First Name and Last Name already exists or not in PHP file
In resultset contains more than 0 records, then return false which means record already exists.
In JQuery, if its getting false, then show an error message that record already exists.
Further, as #kongkang said in comments that the field LRN is as username.
then still you need to do 3 steps :
Make that field as unique in database table
Add if condition on insertion query (PHP File) that if return false it means record already exists
in Jquery, if returning value is false, then show error message.

Add a unique index to your database for a unique field.I hope LRN is there for you. Then
MYSQL:
ALTER TABLE users ADD UNIQUE (LRN)
SQL SERVER:
ALTER TABLE [users] ADD CONSTRAINT UC_LRN UNIQUE ([LRN]);
When you try to insert duplicate LRN database error will come automatically for Codeigniter. Without it you have to check manually.

Related

Why does select with case and union return an empty array with node and sqlite

I've got a problem with a sqlite query on node. The query with SqliteStudio is working, but with Node.js I get an empty array.
Here's the query:
const query =`
SELECT 'telephone' AS type,telephone AS data,CASE
WHEN telephone = (
SELECT data FROM customers_verified_contact_infos
WHERE type='telephone' AND data=j.telephone AND customer_id = ?
) THEN 'true'
ELSE 'false'
END AS verified
FROM customers j WHERE customer_id = ? AND telephone IS NOT NULL
UNION
SELECT 'email' AS type,email AS data,CASE
WHEN email = (
SELECT data FROM customers_verified_contact_infos
WHERE type='email' AND data=email AND customer_id = ?
) THEN 'true'
ELSE 'false'
END AS verified
FROM customers WHERE customer_id = ? AND email IS NOT NULL
UNION
SELECT 'fax' AS type,fax AS data,CASE
WHEN fax = (
SELECT data FROM customers_verified_contact_infos
WHERE type='fax' AND data=fax AND customer_id = ?
) THEN 'true'
ELSE 'false'
END AS verified
FROM customers WHERE customer_id = ? AND fax IS NOT NULL
UNION
SELECT type,data, 'true' AS verified
FROM customers_verified_contact_infos WHERE customer_id = ?
`;
I request two tables:
customers, with some customer information
customers_verified_contact_infos, with list contact information verified
Contact information can be in both or just one table.
The result is a list of rows with data, the type of data, and if it's been verified or not.
Now, the Node.js request:
db.all(query,[customer_id], (err, data) => {
console.log(data);
});
The data is an empty array and err = null.
With SqliteStudio, with the same query and customer, I get:
I tried SELECT by SELECT, and with case I didn't get a result. I don't find anything on internet which can help me.
If someone can help or give me advice, I'd appreciate it.
Thanks
The query has 7 ? placeholders, but the array [customer_id] only has one element. You need to repeat it for every placeholder.
db.all(query, Array(7).fill(customer_id), (err, data) => {
console.log(data);
});

How to get last insert id from mysql database in php?

I want to get last insert id from my table cart in my else statement after the insert. But I am not getting the id.
Please check my code and suggest what am I doing wrong:
// Check to see if the cart COOKIE exists
if ($cart_id != '') {
// Here I want to update but not getting $cart_id, so everytime insert query fire in else statement
}else{
$items_json = json_encode($item);
$cart_expire = date("Y-m-d H:i:s",strtotime("+30 days"));
$db->query("INSERT INTO cart (items,expire_date) VALUES ('{$items_json}','{$cart_expire}') ");
$cart_id = $db->insert_id; // Here is the problem
setcookie(CART_COOKIE,$cart_id,CART_COOKIE_EXPIRE,'/',$domain,false);
}
Your suggestions would be welcome.
Instead of:
$db->query("INSERT INTO cart (items,expire_date) VALUES ('{$items_json}','{$cart_expire}') ");
$cart_id = $db->insert_id; // Here is the problem
Use this, directly from the documentation:
$query = "INSERT INTO cart (items,expire_date) VALUES ('{$items_json}','{$cart_expire}') ";
mysqli_query($db, $query);
$cart_id = mysqli_insert_id($db);
Get the identity column value AFTER the insert:
create table student (
id int primary key not null auto_increment,
name varchar(20)
);
insert into student (name) values ('John');
select ##identity; -- returns 1
insert into student (name) values ('Peter');
select ##identity; -- returns 2
Or get the next auto incremental value before insert:
$query = $db->query("SHOW TABLE STATUS LIKE 'cart'");
$next = $query->fetch(PDO::FETCH_ASSOC);
echo $next['Auto_increment'];

Not able to perform operation with mongoose on db collection with few conditions

I'm Using Mongoose for Mongo db. I want to perform some operations. Not able to get the results.
I have a collection USERS with schema like:
{username: 'user1', id: 1, lastName: 'ln1' }
{username: 'user2', id: 0, lastName: 'ln2' }
Id can be 0,1,2 or 3
I want to enter a new object with these conditons:
If username exists and id is 1 then Update the details.
If username doesnot exist then create a new entry no need to check for id.
If username exists and id is 0,2 or 3 (other than 1) then do nothing (do not update or enter the user in collection ) and keep the value that this user as it failed to enter in the db.
Please help.
I have used promise library but you can also use callbacks
Assumption : You want to work on User model
User.findOne({username:"USERNAME"}).exec()
.then((result)=>{
if(result){
if(result.id == 1){
//update result object and then save it
result.lastName="abc";
result.save(); // it will update your result
}else{
console.log('failed to enter in the db.')
}
}else{
User(userObject).save(); // it will create new entry
}
})

Not able to get objectId in query.containedIn query with parse?

I am using parse.com as my back end.
I am using containedIn query to retrieve multiple user rows from parse "User" table.
My problem is that I am not able to get user's object Id in the success block
following is my code:
r_userIdList= ['PzpdRdKTVZ','PoJdRdKTVU','fvdRdKTVX'];
var query = new Parse.Query("_User");
query.containedIn("objectId", r_userIdList); // returns multiple rows
query.find({
success: function(r_uobject) {
var userObjId ,fName,lName,full_Name="Unknown User";
for(var i =0; i<r_uobject.length;i++){
var r_obj = r_uobject[i];
uID = r_obj.get('objectId');//not working
var u = uID.id;//not working
fName = r_obj.get('firstName');
lName = r_obj.get('lastName');
full_Name = firstName+' '+lastName;
r_userIdList[u].fullName = full_Name; //not working
}
}
});
Once I enter in the success block, I am unable to identify that which user's data has been retrieved.
Actually I need user's ObjectId because I have array called r_userIdList in which I need to store the firstName and LastName of user as Object.
IDs can usually be accessed with .id - in your case r_obj.id. Your uID.id won't work as uID is itself going to be undefined.
You also need to check that you are getting any results back at all: does r_userIdList have a length?

CRM: Javascript to Set Multiple Email Addresses when Replying to an Email

On CRM 2013 I'm trying to insert multiple participants into the email "to" field when users click on "Reply All". However I need to remove certain email addresses from the To line. So I created an array to loop and get all the email addresses except the one that needs to be removed.
However the problem here is that it only works if there is only one participant left after removing the unwanted participants. If there are two or more participants the script will not populate any participants at all.
Is there a way to populate multiple email participants? Or is there a better approach than what I'm trying to do here?
Here's my code:
var toParty = Xrm.Page.getAttribute("to").getValue();
var partyListArray = new Array();
for (var indxAttendees = 0; indxAttendees < toParty.length; indxAttendees++) {
// using oData to get participant email address
var email = getParticipantEmail(
toParty[indxAttendees].entityType,
toParty[indxAttendees].id
);
if (email != "test#test.com") {
partyListArray[indxAttendees] = new Object();
partyListArray[indxAttendees].id = toParty[indxAttendees].id;
partyListArray[indxAttendees].name = toParty[indxAttendees].name;
partyListArray[indxAttendees].entityType = toParty[indxAttendees].entityType;
}
}
Xrm.Page.getAttribute("to").setValue(null);
Xrm.Page.getAttribute("to").setValue(partyListArray);
Instead of creating a whole new array, you can delete what you want from the array itself. Try this:
var emails = [{email: "add1#domain.com"}, {email: "add2#domain.com"}, {email: "address#toBe.Removed"}, {email: "add3#domain.com"}, {email: "add4#domain.com"}];
var removeIndex = emails.map(function(item) { return item.email; }).indexOf("address#toBe.Removed");
removeIndex > -1 && emails.splice(removeIndex, 1);

Categories

Resources