How can I assign a variable to a query in codeigniter - php

For my project I need to check if some variables are empty and if they are then:
The user gets a custom view with a message on which variable is missing.
The developer/me must be able to see the query which was sent to check if there are no failure's in the query.
My question is how can I assign a variable (for example $checkQuery) to my query so that it has all the values and I can check it within the error log.
Query
function createUser($data){
$this->firstname = $data['firstname'];
$this->lastname = $data['surname1'].' '.$data['surname2'];
$this->address = $data['adres'];
$this->zipcode = $data['zipcode'];
$this->mail = $data['mail'];
$this->phonenumber = $data['phonenumber'];
$this->db->insert('User',$this);
//Check if the change was succesfull
return ($this->db->affected_rows() != 1) ? false : true;
}
Function for errorLog
function errorLog($var){ //Get the variable that you have passed from your helper
$mail = "Email was empty";
$firstname ="Firstname was empty";
if($var == 'mail') //Change the error function based on what has been passed
{
return log_message('error', $mail); //Here use the return type
}
if($var == 'firstname')
{
return log_message('error', $firstname); //Here use the return type
}
}
The view for the user is done which I've done with just a simple array but the only thing I see at the moment is just if firstname or email is was empty.
So is it possible to use a PHP variable in which I can assign the submitted values and can put these into my error log preferably using log_message

Related

Laravel - store database value to variable in controller

I'm trying to store a database value to a variable in a controller. But i'm getting this error "Object of class Illuminate\Support\Collection could not be converted to int", i know what it means but i don't know how to fix it.
What i want is that if user is banned, then change $banned to true and return it.
private function isBanned() {
$banned = false;
$getBanned = DB::table('Uzivatele')->select('banned')->where('id', Auth::id())->get();
if ($getBanned == 1) $banned = true;
return $banned;
}
if you want to set it directly you can do this way
$getBanned = DB::table('Uzivatele')->where('id', Auth::id())
->update(['banned' => true])->get();
if you want to check the user is banned or not then you can check like this.
private function isBanned() {
$banned = false;
$getBanned = DB::table('Uzivatele')->select('banned')->where('id', Auth::id())->first();
if ($getBanned->banned == 1) $banned = true;
return $banned;
}

Can't set error message in Code Igniter 3 when using callback function

I am writing a method that uses POST variables posted by AJAX to add a user to a certain course in the database, but I can't get the callback to work correctly:
public function enroll()
{
$package = array();
$this->load->library('form_validation');
$this->form_validation->set_rules('course', 'Vak', 'required|callback_not_enrolled');
$fields = array("course");
if ($this->form_validation->run($this) === FALSE) {
$errors = array();
$success = array();
foreach ($fields as $field) {
$error = form_error($field);
if ($error !== "") {
$errors[$field] = $error;
} else {
$success[$field] = True;
}
}
$package["field_errors"] = $errors;
$package["field_success"] = $success;
$package["success"] = False;
} else {
$package["database"] = $this->course_model->enroll_user($this->data["user"], $this->input->post("course"));
$package["success"] = True;
}
echo json_encode($package);
}
I wrote the callback not_enrolled to check if the user is not already enrolled to the database. Note that I can't use is_unique because I have to test the combined uniqueness of two fields (so just one or two separate ones don't do the trick) and the id of the user is not included in the form (because it's part of the Code Igniter session).
The callback function:
public function _not_enrolled($course)
{
$exists = ($this->user->is_enrolled($course, $this->data["user_id"]) != False);
if ($exists != False) {
$this->form_validation->set_message("not_enrolled", "Already enrolled");
return False;
} else {
return True;
}
}
And finally the method is_enrolled from the model:
public function is_enrolled($course, $user=False) {
if($user==False){
$user = $this->data["user_id"];
}
$this->db->select()->from("course_participant")->where("user_id", $user)->where("course_id", $course);
$query = $this->db->get();
return($query->num_rows()>0);
}
Through a call to var_dump($this->_not_enrolled($existing_course_id)); I know that both the callback function and the method from the model work, as it correctly returned true.
When I var_dump the $package array or validation_errors() I don't get any validation errors except that it says Unable to access an error message corresponding to your field name Vak(not_enrolled).
I tried removing the initial _ from the function name but that gives me a Server Status 500 error.
I have another setup exactly like this, albeit other database calls, with a callback using the same syntax. This method works perfectly.

How would I go about starting to convert this code into OOP PHP?

I'm trying to learn about Object Oriented Programming and I want to turn this code into such. I've got some knowledge so far from google and here and in particular http://code.tutsplus.com/tutorials/object-oriented-php-for-beginners--net-12762.
The way I understand it is I need classes that contain a certain set of instructions that can be used with universal objects outside of those classes.
My idea so far has been to set up a User class where names are stored (coming from a HTML/PHP form).
class User {
public $nameStore, $fName, $lName, $email;
public function __construct ($fName, $lName, $email) {
$this->$fN = $fName;
$this->$lN = $lName;
$this->$eN = $email;
}
Like the above^. But I'm still confused about where other instructions of my code should go. That's where I need the most help. From what I've read, it hasn't helped me get the full grasp of what I need to do. If someone could help get me started in the right direction on how to make my code into an OOP type I would greatly appreciate it. Thanks!
Below is my procedural code that I want to convert to OOP.
<?php
session_start();
$formNames = $_POST['names'];
$active = (isset($_POST['activate'])) ? $_POST['activate'] : false;
//checks if activate checkbox is being used
$email = '#grantle.com';
$fullnames = explode(", ", $_POST['names']);
if ($active == true) {
$active = '1';
//sets activate checkbox to '1' if it has been selected
}
/*----------------------Function to Insert User-------------------------*/
function newUser($firstName,$lastName,$emailUser,$active,$conn){
//a function to insert a user into a database is here
}
//newUser function enters names in database
/*-------------------------End Function to Insert User--------------------*/
/*-----------------------Function for Errors------------------------------*/
function errorCheck($formNames, $nameSplit, $fullname){
$isValid = false;
if (empty($fullname)) {
$_SESSION['error'][] = '<br><br> Error: Name Missing Here: '.$fullname.'<br><br>';
} elseif (empty($nameSplit[0])) {
$_SESSION['error'][] = '<br><br> Error: First Name Missing Here: '.$fullname.'<br><br>';
} elseif (empty($nameSplit[1])) {
$_SESSION['error'][] = '<br><br> Error: Last Name Missing Here: '.$fullname.'<br><br>';
} elseif (preg_match('/[^A-Za-z, ]/', $fullname)) {
$_SESSION['error'][] = '<br><br> Error: Illegal Character Found in: '.$fullname.'<br><br>';
} else {
$isValid = true;
}
return $isValid;
}
//errorCheck function tests for errors in names and stops them from being entered in the
//database if there are errors in the name. Allows good names to go through
/*-----------------------------End Function for Errors---------------------*/
/*--------------------------Function for Redirect--------------------------*/
function redirect($url){
$string = '<script type="text/javascript">';
$string .= 'window.location = "' .$url. '"';
$string .= '</script>';
echo $string;
}
//redirect function uses a javascript script to redirect user because headers have already been sent.
/*-----------------------------End Function for Redirect-----------------------*/
// Connect to database
I connect to the database here//
// Initialize empty error array
$_SESSION['error'] = array();
foreach ($fullnames as $fullname) {
$nameSplit = explode(" ", $fullname);
//I open the database here
//opens the database
if (errorCheck($formNames, $nameSplit, $fullname)) {
$firstName = $nameSplit[0];//sets first part of name to first name
$lastName = $nameSplit[1];//sets second part of name to last name
$emailUser = $nameSplit[0].$email;//sets first part and adds email extension
newUser($firstName,$lastName,$emailUser,$active,$conn);//do this BELOW only for names that have no errors
}//ends if of errorCheck
}//ends fullnames foreach
if (count($_SESSION['error']) == 0) {
redirect('viewAll.php');
} else {
redirect('form.php');
}
/*Redirects to viewAll page only once and as long as no errors have been found*/
Your
class User {
public $nameStore, $fName, $lName, $email;
public function __construct ($fName, $lName, $email) {
$this->$fN = $fName;
$this->$lN = $lName;
$this->$eN = $email;
}
I would break this up into more specific parts such as GET and SET for each value you are trying to store in the Class:
class User {
private $fName, $lName, $email;
public function set_firstname($fname){
$this->fName = $fname;
}
public function set_surname($lName){
$this->lName = $lName;
}
public function set_email($email){
$this->email = $email;
}
public function get_email(){
return $this->email;
}
public function get_fname(){
return $this->fName;
}
public function get_surname(){
return $this->lName;
}
Then when you create the class, you can add and return each value individually, rather than forcing yourself to do them all at once. This is more flexible. But you can also add the values at the creation of the class as well if you wish, using the __construct similar to what you had already:
public function __construct ($fName = null, $lName = null, $email = null) {
if(!empty($fName)){
$this->set_firstname($fName);
}
if(!empty($lName)){
$this->set_surname($lName);
}
if(filter_var($email, FILTER_VALIDATE_EMAIL) !== false){
$this->set_email($email);
}
}
What this does is for each non-empty value it runs the corresponding SET method. Also checking that the email value is valid before saving it. If no values are passed to the class then it doesn't save anything.
Your setting up of the class is incorrect, firstly you need to include the class file into the working PHP so at the top of your page add:
include "path/to/users.class.php";
And then initiate the class correctly:
$userClassInstance = new User($firstName,$lastName,$emailUser);
When the above line runs, you will then have a User object containing three variables referenced as $userClassInstance. you can do var_dump($userClassInstance);
Be careful as your code has newUser as one line and also has an incorrect number of variables in the construct statement. Generally all the functions in a page should be placed inside an appropriate class, so all your string management functions such as errorCheck() could be put into the Users class to check the values given before assigning them to the variables in the class.
Finally, to view the stored variables you would then do:
print $userClassInstance->get_fname(); //will outout the value of the class $fName

PHP Validation Function Returning Values?

I'm trying to create small functions to validate each of my form elements. But I'm having some difficulties. I'm fairly new to PHP functions in general.
Currently I'm trying to create a validation function for the 'surname' entry in a form. This is what I have:
//Call surname validation function
If (validSurname($surname) === false) {
$mistakes[] = 'Your surname is either empty or Enter only ALPHABET characters.';
}
function validSurname($surname) {
$surname = trim($surname);
if (empty($surname) || (!ctype_alpha(str_replace(' ', '', $surname)))) {
$isValid = false;
} else {
//accept surname entry and sanitize it
$surname = mysql_real_escape_string(stripslashes($surname));
}
return $isValid;
}
So currently I use something similar for validating emails, and it works correctly. But now I want to actually pass the surname through certain stages such as:
$surname = trim($surname);
For this new value to be accessed outside of the function and then entered into the database, do I need to return it at the end of the function? e.g. Something like return $surname; at the end of the function?
Put simply - how do I use this new value of $surname (rather than the initial one entered in the form) outside of the function?
You should consider what you function is trying to do. In my mind you would probably need two functions isValidSurname which would return a boolean either true or false and formatSurname would take the valid surname and return it correctly formatted.
You either have to use a global variable, or pass $surname by reference if you want to do it the way you first wrote it.
Alternatively, you could pass back the modified string, or no string at all if it failed.
$surname = validSurname($surname);
if (strlen($surname) == 0) {
$mistakes[] = 'Your surname is either empty or Enter only ALPHABET characters.';
}
function validSurname($surname) {
$surname = trim($surname);
if (empty($surname) || (!ctype_alpha(str_replace(' ', '', $surname)))) {
$surname = '';
} else {
//accept surname entry and sanitize it
$surname = mysql_real_escape_string(stripslashes($surname));
}
return $surname;
}
You should set it to global within the function. I wouldn't use the same variable name as what you're using as a parameter to your function though. If you want to mess with $surnameVar, do this:
function validSurname($surname) {
global $surnameVar;
$surnameVar = trim($surname);
if (empty($surname) || (!ctype_alpha(str_replace(' ', '', $surname)))) {
$isValid = false;
} else {
//accept surname entry and sanitize it
$surname = mysql_real_escape_string(stripslashes($surname));
}
return $isValid;
}
You be more explicit with your function names and return the new value.
For example:
function isSurnameValid($surname) {
return (empty($surname) || (!ctype_alpha(str_replace(' ', '', $surname)))) ? false : true;
}
function cleanSurname($surname) {
$surname = mysql_real_escape_string(stripslashes(trim($surname)));
return $surname;
}
This way you have clear, descriptive function names and every function has a single responsibility.

PHP Check Function

I have a check function:
function checkCandidateEmail($email)
{
$email = $_POST;
if($email)
{
$candemail = (SQL);
if(isset($candemail['email']))
{
return TRUE;
} else {
return FALSE;
}
return $canEmailCheck;
}
}
I have started to create a function but I am getting NULL
function checkCandidateEmail($email)
{
$email = $_POST; // being immediately overwritten - redundant argument.
if($email) // Since $email isn't an optional argument, you'll get a PHP warning if it is missing, making this check confusing.
{
$candemail = (SQL); // Evaluating a constant? this will be bool
if(isset($candemail['email'])) // Since $candemail is a bool and not an array, this will never return true
{
return TRUE;
} else {
return FALSE;
} // this entire if/else block can be simplified to this: return (isset($candemail['email']));
return $canEmailCheck; // this is an undefined variable and will never get returned anyway because of the above return statements.
}
}
Please, elaborate more on your questions next time. I am not sure what you attempt to compare, if the $_POST with the SQL query or the argument passed with the SQL query. I assume the former.
If the email from that SQL table row equals the submitted email, returns TRUE. Else, returns FALSE. Really simplified version. Now it also checks if the user provided an email:
function checkCandidateEmail()
{
if (!$_POST['email']) echo "Error, please provide an email";
else
{
$candemail = (SQL); // Return a row from a query
return $candemail['email'] == $_POST['email'];
}
}
If an argument is passed, compares that against the database. If none is passed, compares the submitted $_POST['email'] against the database.
function checkCandidateEmail($email=null)
{
$candemail = (SQL); // Return a row from a query
if (!$email) $email = $_POST['email'];
return $candemail['email'] == $email;
}
NOTE: In both cases you have to substitute SQL for the right string and function depending on your database.
NOTE 2: Make sure that your query returns an email, as this simple code does not check if both strings are empty.

Categories