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.
Related
I have the following problem.
This error persisting in accompanying me
Fatal error: Uncaught Error: Call to a member function fetchAll() on boolean in C:\xampp\htdocs\certificado\functions.php:49 Stack trace: #0 C:\xampp\htdocs\certificado\index.php(11): get_info_from_email('amanda_pandoka#...') #1 {main} thrown in C:\xampp\htdocs\certificado\functions.php on line 49
In the code below I can not understand the error. Can someone help me?
function connect() {
$socket = new PDO('mysql:host=' . #$host . ';dbname=' . #$nomedobancodedados,
#$usuario, #$senha);
$socket->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
return $socket;
}
function get_info_from_email($email) {
if (!$email)
return false;
global $db;
$sql = "
SELECT
id,
name,
email,
type,
data,
file
FROM
attendee
WHERE 1=1
AND email = '{$email}'
";
if ($info = $db->query($sql))
return false;
if ($info = $info->fetchAll())
return false;
return $info;
}
if ($info = $db->query($sql))
return false;
This says: if the result of $db->query($sql) can be stored in $info and is not something like false, null or an empty string or array, stop now and return false. So basically, if your query executes successfully and properly returns a PDOStatement with results in it, your function stops here.
if ($info = $info->fetchAll())
return false;
This is where you're getting the error. The fact that this code is reached at all means that the query failed to execute (otherwise, it would have returned false earlier). So basically, you're calling fetchAll() on false. Try to see what the error is here (do a print_r($db->errorInfo()); before this if-statement)
By the way, this if-statement will also cause your function to return false if the fetchAll() call was successful, which is probably not what you want. Additionally, by using $db->query() directly with the email address provided in the function call, you're leaving your code open to possible SQL injection attacks. As a rule, never trust any variable if you don't have 100% control over what's in it. You should use a prepared statement instead.
As another rule, always use curly braces on code blocks (if/elseif/else, for/foreach/while/do, try/catch/finally), because then you don't need to think about them anymore if you someday decide that the code block should do two things instead of one, and it's easier to debug code if you can visually see exactly what your code is trying to do.
This code (not tested) should work the way you want:
function get_info_from_email($email) {
if (!$email) {
return false;
}
global $db;
$stmt = $db->prepare("
SELECT
id,
name,
email,
type,
data,
file
FROM
attendee
WHERE 1=1
AND email = :email
");
// return false if the query cannot be executed
if (!$stmt->execute(array(':email' => $email))) {
return false;
}
// return false if there was an **error** retrieving the query results
if (($info = $stmt->fetchAll()) === false) {
return false;
}
return $info;
}
Continue like this
function get_info_from_email($email) {
if (!$email) {
return false;
}
global $db;
$sql = $db->prepare("
SELECT
id,
name,
email,
type,
data,
file
FROM
attendee
WHERE 1=1
AND email = :email
");
print_r($db->errorInfo());
// return false if the query cannot be executed
if (!$sql->execute(array(':email' => $info))) {
return false;
}
// return false if there was an **error** retrieving the query results
if (($info = $sql->fetchAll()) === false) {
return false;
}
return $info;
}
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
I have the following code to validate form data. I have created functions to validate various groups, and then have an if isset statement to check if these functions return true. I have tried many different ways to get this to work.
The problem I am having is this. I want the if isset to end if returning FALSE; but it doesn't, it keeps going and pops up the next alert (in my code I have many functions). How can I get it to exit after the first return FALSE? Do I need to make the isset into a function? So it can exit on return FALSE. thanks
I am having trouble writing a function to call functions in php.
function namecheck ($fname, $lname)
{
$regexp ="/^[A-Za-z]+$/";
//filter through names
if (preg_match($regexp,$fname,$lname))
{
return TRUE;
}
else
{
echo'<script type="text/javascript">alert("Enter your names.")</script>';
return FALSE;
}
}
function emailcheck ($email1, $email2)
{
$regexp="/^[a-zA-A-Z0-9_.]+#[a-zA-Z0-9-]+\.[a-zA-Z0-9.-]+$/";
//validate email address
if (preg_match($regexp,$email1,$email2))
{
return TRUE;
}
else
{
echo '<script type="text/javascript">alert ("Enter a valid email address.")</script>';
return FALSE;
}
}
$fname=$_POST['fname'];
$lname=$_POST['lname'];
$namecheck=namecheck($fname,$lname);
$email1=$_POST['email1'];
$email2=$_POST['email2'];
$emailcheck=emailcheck($email1,$email2);
if (isset($_POST['submit']))
{
if ($namecheck !==TRUE)
{
return FALSE;
}
elseif ($emailcheck!==TRUE)
{
return FALSE;
} //and so on..
else
{
return TRUE;
}
}
A general structure for your functions you could follow is something like this:
function validateName($name) {
// Do Validation. Return true or false.
}
function validateEmail($email) {
// Do Validation. Return true or false.
}
function isFormValid()
{
// Name Validation
if( ! validateName( $_POST['name'] ) )
return false;
// Email Validation
if( ! validateEmail( $_POST['email'] ) )
return false;
// Form is valid if it reached this far.
return true;
}
// In your regular code on Form Submit
if( isset($_POST['submit']) )
{
if( isFormValid() ) {
// Save Form Data to DB
} else {
// Show Some Errors
}
}
That general structure should work fine for you. It could be made a LOT better but, for the sake of learning, this is sufficient.
If you want the script to, as you put, "exit" then you need to use exit(); Generally this is bad as the script will completely stop executing. Maybe you can look into using "break;" to get you out of a loop and stop executing functions within that loop. Another problem is that you are echoing out HTML code in your function which gets executed on assignment and so you will always get an alert generated when it evaluates to FALSE.
edit:
within your if(isset()) block. Inside here you can do{}while(false); which is a loop and will let you break out of it at anytime and prevent further execution of code within that loop.
If a function isn't returning false, then it never reached a return FALSE; statement. It's as simple as that. So let's examine the relevant code:
if (isset($_POST['submit']))
{
if ($namecheck !==TRUE)
{
return FALSE;
}
elseif ($emailcheck !== TRUE)
{
return FALSE;
} //and so on..
else
{
return TRUE;
}
}
So, if $_POST['submit'] is set and is not null, the if block will be reached. Then, if $namecheck is not true OR $emailcheck is not true, the function will return FALSE. You can simplify the above code to just:
if (isset($_POST['submit']))
{
return !(!$namecheck || !$emailcheck);
}
However, it doesn't look like this code is inside a function, so the return statement will do nothing. You have to put it in a function if you want it to work like a function.
Beyond that, I can't help you. I don't know what you want to do with this code. You seem to know how to use and call functions, so I'm not sure what the problem is. If you want to return from a function, put code in a function and call return. Right now your code is not in a function, so return won't do anything.
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.
Im trying to test a pin number in the database compared to one entered by a user, whenever i run it i get a 'Trying to get property on non-object' error ... I cant seem to spot where im going wrong, could someone please help me out ... Its saying the error is on the $thepin = $pins->pin; line
The code i have in my controller is as follows:
function check_pin()
{
$pin = md5($this->input->post('oldpin'));
$email = $this->input->post('email');
$existingpin = $this->users->get_pin_by_email($email);
foreach($existingpin as $pins){
$thepin = $pins->pin;
}
if($pin != $thepin){
$this->form_validation->set_message('check_pin', 'The Old Pin Number does not match the existing one');
return FALSE;
} else {
return TRUE;
}
}
and the following is the code in my model
function get_pin_by_email($emailaddress)
{
$this->db->where('LOWER(email)=', strtolower($emailaddress));
$query = $this->db->get($this->table_name);
if ($query->num_rows() == 1) return $query->row();
return NULL;
}
The Controller code should be:-
function check_pin()
{
$pin = md5($this->input->post('oldpin'));
$email = $this->input->post('email');
$existingpin = $this->users->get_pin_by_email($email);
foreach($existingpin as $pins){
// Check for the NULL return
if ($pins != NULL && is_object($pins)) {
$thepin = $pins->pin;
}
}
if($pin != $thepin){
$this->form_validation->set_message('check_pin', 'The Old Pin Number does not match the existing one');
return FALSE;
} else {
return TRUE;
}
}
If you look closely in the model code, you will find that you are returning two data types - one is Object & another is NULL. So in your controller code, you should also check that accordingly.
Hope it helps.