I have this function:
public function addToFavoriteList($eventId, $userId)
{
$sql = "INSERT INTO favorites (eventi_id, user_id) VALUES ($eventId, $userId)";
$resultSet = $this->db->execute($sql);
if (!$resultSet) {
return array('error' => 'event exsist in favorites');
}
return array('error' => '');
}
and i want to check if the event alredy exist in db so i can show and error message for the user.
I write something like that but it doesen't work.
if (isset($_POST['addToFavourite'])) {
$eventId = htmlspecialchars(trim($_POST['id']));
$addToFavoriteOutcome = $eventMgr->addToFavoriteList($eventId, $userId);
if (isset($addToFavoriteOutcome)) {
$errorMessage = $addToFavoriteOutcome['error'];
}
}
Try changing this:
if (isset($addToFavoriteOutcome)) {
$errorMessage = $addToFavoriteOutcome['error'];
}
to this
if ($addToFavoriteOutcome) {
$errorMessage = $addToFavoriteOutcome['error'];
}
Related
I have a registration page and I want to validate it. I have this code:
$msg = "";
$msg_3 = "";
if(isset($_POST['submit'])) {
$First_Name = ((isset($_POST['First_Name']))?sanitize($_POST['First_Name']):'');
$Last_Name = ((isset($_POST['Last_Name']))?sanitize($_POST['Last_Name']):'');
$email = ((isset($_POST['email']))?sanitize($_POST['email']):'');
$confirm_email = ((isset($_POST['confirm_email']))?sanitize($_POST['confirm_email']):'');
$mobile_number = ((isset($_POST['mobile_number']))?sanitize($_POST['mobile_number']):'');
$password = ((isset($_POST['password']))?sanitize($_POST['password']):'');
$confirm_password = ((isset($_POST['confirm_password']))?sanitize($_POST['confirm_password']):'');
$gender = ((isset($_POST['gender']))?sanitize($_POST['gender']):'');
$day = ((isset($_POST['day']))?sanitize($_POST['day']):'');
$month = ((isset($_POST['month']))?sanitize($_POST['month']):'');
$year = ((isset($_POST['year']))?sanitize($_POST['year']):'');
$insurance = ((isset($_POST['insurance']))?sanitize($_POST['insurance']):'');
$agree = ((isset($_POST['agree']))?sanitize($_POST['agree']):'');
$sql = "SELECT email, mobile_number FROM customers WHERE email ='$email' OR mobile_number ='$mobile_number'";
$result = $db->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
if ($email == $row['email']) {
$msg = "<span class='text-danger'>The email address you've entered is already associated with another account.
<br>Please sign in or enter a different email address. Please try again.</span>";
} if ($mobile_number == $row['mobile_number']) {
$msg_3 = "<span class='text-danger'>The mobile phone number you've entered is already associated with another account.
<br>Please sign in or enter a different number. Please try <br>again.</span>";
}
}
} else {
// Insert into database and send email
}
Now how could I validate each field if it is empty and print different messages under each field in this nested if and while. I'm getting confused.
If you will use same names in db as in form you could use something like this:
$keys = ['gender', 'email', 'mobile_number']; //etc
$errors = [];
while ($row = $result->fetch_assoc()) {
array_walk($keys, function ($key) {
if (empty($row[$key])) {
$errors[] = "$key is required"
}
if (isset($_POST[$key]) && $_POST[$key] == $row[$key]) {
$errors[] = "please enter $key"
}
})
}
if you need to have more customized messages you might map keys to error text like:
$keys = ['gender' => ['equal' => 'your error message', 'empty' => 'empty msg'], 'email' => ['equal' => 'email validation error', 'empty' => 'error msg 2']]; //etc
$errors = [];
while ($row = $result->fetch_assoc()) {
array_walk($keys, function ($errorMsg, $key) {
if (isset($_POST[$key]) && $_POST[$key] == $row[$key]) {
$errors[$key] = $errorMsg['equal'];
}
if (empty($row[$key])) {
$errors[$key] = $errorMsq['empty'];
}
})
}
Do not repeat
Prevent SQL Injection
You can do something like this.
<?php
if(isset($_POST['submit'])) {
$errors = [];
function getPost($postIndex, $errorMessage = '') {
global $errors;
if (!empty( $_POST[$postIndex] )) {
$value = $_POST[$postIndex];
return $value;;
} else {
$errors[$postIndex] = $errorMessage;
return null;
}
}
function validateString($s) {
return htmlspecialchars(trim($s));
}
getPost('First_Name', 'Firstname Cannot Be Empty');
getPost('Last_Name', 'Lastname cannot be empty');
$email = getPost('email', 'Your Error Message');
getPost('confirm_email', 'Your Error Message');
$mobile_number = getPost('mobile_number', 'Your Error Message');
getPost('password', 'Your Error Message');
getPost('confirm_password', 'Your Error Message');
getPost('gender', 'Your Error Message');
getPost('day', 'Your Error Message');
getPost('month', 'Your Error Message');
getPost('year', 'Your Error Message');
getPost('insurance', 'Your Error Message');
getPost('agree', 'Your Error Message');
$stmt = $mysqli -> prepare('SELECT email, mobile_number FROM customers WHERE email =? OR mobile_number =?');
if (
$stmt &&
$stmt -> bind_param('ss', $email, $mobile_number) &&
$stmt -> execute() &&
$stmt -> store_result() &&
$stmt -> bind_result($dbEmail, $dbMobileNumber) &&
$stmt -> fetch()
) {
if ($email == $dbEmail) {
// email equal error message
} if ($mobile_number == $row['mobile_number']) {
// mobile number equal error message
}
}
if (count($errors)) {
echo "You have an error";
}
// or get the post index in your HTML form and show the error message there
// <?php isset($errors['firstName']) ? echo $errors['firstname'] : null;
}
Im trying display a message when you have nothing to delete in the database instead of showing a error that says you have a null value
public function destroy($customer_id)
{
$customer_response = [];
$errormsg = "";
$customer = Customer::find($customer_id);
$result = $customer->delete();
try{
//retrieve page
if ($result){
$customer_response['result'] = true;
$customer_response['message'] = "Customer Successfully Deleted!";
}else{
$customer_response['result'] = false;
$customer_response['message'] = "Customer was not Deleted, Try Again!";
}
return json_encode($customer_response, JSON_PRETTY_PRINT);
}catch(\Exception $exception){
dd($exception);
$errormsg = 'No Customer to de!' . $exception->getCode();
}
return Response::json(['errormsg'=>$errormsg]);
}
the try/catch method is not working compared to my previous store function that is working
Read up further on findOrFail. You can catch the exception it throws when it fails to find.
try {
$customer = Customer::findOrFail($customer_id);
} catch(\Exception $exception){
dd($exception);
$errormsg = 'No Customer to de!' . $exception->getCode();
return Response::json(['errormsg'=>$errormsg]);
}
$result = $customer->delete();
if ($result) {
$customer_response['result'] = true;
$customer_response['message'] = "Customer Successfully Deleted!";
} else {
$customer_response['result'] = false;
$customer_response['message'] = "Customer was not Deleted, Try Again!";
}
return json_encode($customer_response, JSON_PRETTY_PRINT);
Whenever I add a new place/description in my UI, it will save automatically to my database. My problem is that I can still add a place eventhough it's already existing. All I want is that it won't save/update a new description/place if it's already exist.
Any advice would be much appreciated.
Thanks.
This is my my EditPlaces:
public function executeEditPlaces(sfWebRequest $request)
{
try{
$id = pg_escape_string(strip_tags($request->getParameter("id")));
// $id = $request->getParameter("id");
$query = "select description from country.regions where id = ('$id')";
// die($query);
$result=$this->conn->fetchAll($query);
if(count($result)>0){
$v = $result[0];
$data['data'] = array('description' => $this->formatString($v['description']));
}
$data['success']=true;
$data['msg']=$msg;
die(json_encode($data));
}
catch(exception $e)
{
$data['success']=false;
$data['msg']=$e->getMessage();
die(json_encode($data));
}
}
This is my UpdatePlaces:
public function executeUpdatePlaces(sfWebRequest $request)
{
try{
$by = $_SESSION['employee_id'];
$now = date("Y-m-d H:I:s");
$id = $request->getParameter("id");
$description = pg_escape_string(strip_tags($request->getParameter("description")));
$description = trim($description);
if(strlen($description) == 0)
{
die('cannot be empty');
}
else
{
$query = "update country.regions set description=('$description'),modified_by=('$by'),date_modified=('$now') where id=('$id')";
$msg = "Existing Region Successfully Updated.";
$this->conn->execute($query);
$data['success']=true;
$data['msg']=$msg;
die(json_encode($data));
}
}
catch(exception $e)
{
$data['success']=false;
$data['msg']=$e->getMessage();
die(json_encode($data));
}
}
There is two way:
You can alter your table so the column is unique
ALTER IGNORE TABLE country.regions ADD UNIQUE (description);
Check if your description/place already exist using a select
$query = "select description from country.regions";
$result=$this->conn->fetchAll($query);
if(count($result)>0){
print 'already exist'
} else {
//insert code
}
Please check if $description of duplicated entries are really the same.
You may introduce UNIQUE constraint to SQL schema for the columns that must be unique - it will introduce security in the lower layer.
Please check if description is of type bytea. If yes, pg_escape_bytea should be used instead of pg_escape_string.
I have an admin area where they can delete multiple users at a time. This is part of the code that handles the deletion. Basically it goes through the user ids and deletes each one that was marked checked.
if ($_POST['doDelete'] == 'Delete') {
if (!empty($_POST['u'])) {
foreach ($_POST['u'] as $uid) {
$id = escape($uid);
$delete = Nemesis::query("DELETE FROM users WHERE id = '{$id}' AND id <> '{$_SESSION[user_id]}'");
if (!$delete) {
$msg->add('e', QUERY_ERROR);
redirect('users.php');
exit();
}
}
}
/* we need a way to iterate over users deleted */
$msg = new Messages();
$msg->add('s', QUERY_DELETE_SUCCESS);
redirect('users.php');
exit();
}
function get_user_name_from_id($user_id)
{
if ($_SESSION['user_level'] == ADMIN_LEVEL) {
$viewUserMod = 1;
} else {
$config = Nemesis::select("usr_view_cm", "config");
$row_config = $config->fetch_assoc();
$viewUserMod = $row_config['usr_view_cm'];
}
if (is_numeric($user_id) && $viewUserMod == 1) {
$sql = Nemesis::select("full_name", "users", "id = {$user_id}");
if ($sql->num_rows > 0) {
$user_name = $sql->fetch_assoc();
return $user_name['full_name'];
} else {
// user name cannot be matched with db, either error, or most likely user was deleted
return 'User ' . $user_id;
}
} else {
return $user_id;
}
}
Where it says QUERY_DELETE_SUCCESS I would like to output something like "Deleted Bob, Jack, Tim" .etc I have a function that uses the users id and gets their names. The issue is that once the iteration is complete. Obviously those users no longer exist in the database and I cannot get their names. Is there a way of running this function during the loop, and building a string or array. That can be outputted in place of the message?
You should just be able to do this:
if ($_POST['doDelete'] == 'Delete') {
$deleted = array();
if (!empty($_POST['u'])) {
foreach ($_POST['u'] as $uid) {
$id = escape($uid);
$username = get_user_name_from_id($uid);
$delete = Nemesis::query("DELETE FROM users WHERE id = '{$id}' AND id <> '{$_SESSION[user_id]}'");
if (!$delete) {
$msg->add('e', QUERY_ERROR);
redirect('users.php');
exit();
}
$deleted[] = $username // push name to array after deletion is successful
}
}
/* The $deleted array now holds the names of the deleted users.
* Do with it what you want.
*/
$names = implode(",", $deleted)
$msg = new Messages();
$msg->add('s', QUERY_DELETE_SUCCESS . " Deleted: $names");
redirect('users.php');
exit();
}
There are several improvements that can be made here, including efficiency (combining many small single queries into a few larger ones) and error handling (don't redirect on the first error - instead redirect after all processing is complete to a page with a list of successes and errors), but this is the basic idea.
Here is a quick change that will do all of the operations, even if one of them errors:
if ($_POST['doDelete'] == 'Delete') {
$deleted = array();
$errored = array();
if (!empty($_POST['u'])) {
foreach ($_POST['u'] as $uid) {
$id = escape($uid);
$username = get_user_name_from_id($uid);
$delete = Nemesis::query("DELETE FROM users WHERE id = '{$id}' AND id <> '{$_SESSION[user_id]}'");
if (!$delete) {
$errored[] = $username;
} else {
$deleted[] = $username // push name to array after deletion is successful
}
}
}
/* The $deleted array now holds the names of the deleted users.
* The $errored array now holds the names of users who were not deleted due to errors.
* Do with them what you want.
*/
$msg = new Messages();
$names_deleted = implode(",", $deleted)
$msg->add('s', QUERY_DELETE_SUCCESS . " Deleted: $names_deleted");
if (count($errored) > 0) {
$names_errored = implode(",", $errored)
$msg->add('e', QUERY_ERROR . " Did not delete: $names_errored");
}
redirect('users.php');
exit();
}
You could add the names to an array as you are looping over the uids with something like this:
$names = array();
if (!empty($_POST['u'])) {
foreach ($_POST['u'] as $uid) {
$names[] = get_user_name_from_id($uid);
$id = escape($uid);
$delete = Nemesis::query("DELETE FROM users WHERE id = '{$id}' AND id <> '{$_SESSION[user_id]}'");
if (!$delete) {
$msg->add('e', QUERY_ERROR);
redirect('users.php');
exit();
}
}
}
Then when you want to output the confirmation message, you could turn that array into a comma separated string with something like this:
$names = implode(', ',$names);
$message = "Deleted $names";
I have a function that tells me if an email is in or not in the database. What I would like to know if it is found how could I also pass the variables like id,name etc along with it for the particular email that has been found in the DB.
function candidateInsert()
{
if($this->checkEmail($email))
{
echo 'found in db';
echo $email['id'];
}else{
echo 'error';
}
}
function checkEmail($email)
{
$email = $POST('Email');
if($email)
{
$candemail ="SELECT * FROM {table} WHERE email=?",$email"";
if(isset($candemail['email']))
{
return TRUE;
} else {
return FALSE;
}
}
}
if you want to echo something of the mail, you need to return the values from CheckMail() function, as like this:
function candidateInsert() {
$newmail = $this->checkEmail($email);
if($newmail != FALSE ) {
echo 'found in db';
echo $newmail['id'];
}else{
echo 'error';
}
}
function checkEmail($email)
{
$email = $POST('Email');
if($email)
{
$candemail ="SELECT * FROM {table} WHERE email=?",$email"";
$result = result($candemail ) // Don't know which sql functions u use
if(isset($result['email'])) {
return $result;
} else {
return FALSE;
}
}
}
I will assume that aside from boolean value, you also want to return the id and name. In this case, pass parameters by reference:
function candidateInsert()
{
$id = "";
$name;
if($this->checkEmail($email, $id, $name))
{
echo 'found in db';
echo $id;
echo $name;
}else{
echo 'error';
}
}
function checkEmail($email, &$id, &$name)
{
$email = $POST('Email');
if($email)
{
$candemail ="SELECT * FROM {table} WHERE email=?",$email"";
if(isset($candemail['email']))
{
$id = $candemail['id'];
$name = $candemail['name'];
return TRUE;
} else {
return FALSE;
}
}
}
By adding & at the beginning of the parameter, you can edit the content of the variables you pass as argument.