code in elseif block partially running when it shouldn't - php

Ok, I have a registration form for my site.
When there are errors up pops a box with the errors. The box is made up of an html div, an h2 header, and php echoing my errors.
If I hit submit it shows the errors like it should, but the header and div show up no matter what.
I dont understand why.
Here is the code block that echoes the errors.
} else if (!empty($errors)){
echo '<div class="msg_module">';
echo '<h2>Registration Errors:</h2>';
echo $General->outputErrors($errors);
echo '</div>';
}
Thanks all!
Edit: I should mention that $errors is an array.
EDIT: My internet is back, here is the outputErrors function:
public function outputErrors($errors = ''){
if(is_array($errors)){
// handle for passed array
foreach ($errors as $error){
if(is_array($error)){
general::outputErrors($error);
} else{
general::$errStr.= ($error != '')?'<li>'.$error.'</li>':'';
}
}
} else if($errors != ''){
// handle for passed string
general::$errStr = $errors;
}
return '<ul id="error_list">'.general::$errStr.'</ul>';
}//outputErrors

Use var_dump($errors); and you will probably see that the variable is not empty.
From your comment, I assume that the variable is of type array
Read the PHP Manual for the empty function and you will see that it returns true for empty arrays (arrays not containing any element)
Now remember that if the variable is of type String, then most strings are considered non-empty.

Related

Pasting a form into a string (with str_replace) is not working

I'd like to paste a signup form into a text (let's call it $mystring) with str_replace.
The basic idea is to change [signup] to SignUp($parameters) in a text.
Finally to echo it: echo $mystring
So it would look like this:
Some text
A working sign up form
Some text
My problem:
The form works properly, but because of the echoes used in it, it appears before the output of $mystring. I'd like it to show up inside the text.
The code here inserts the function into the string, no problem:
$mystring = str_replace("[signup]",SignUp($parameters),$mystring);
Function SignUp() looks like this:
if (!isset($_POST["btn"])) SignUpForm($parameters); // here I show the form if post is empty
else
{
// here I check the values then do some DB inserts if correct
echo $successmessage (or echo $errormessage)
}
Function SignUpForm() contains a HTML form:
echo "<form method='post' action=''>
...and the rest with the input fields and submit button.
Also note the usage of echo here.
So with using the echoes in the two functions, it works flawlessly however it is not displayed inside the text, but before the output of $mystring because of the echoes placed in the functions that are also echoed as echo $mystring.
Changing the echoes to returns does not do the job, the form is not displayed at all.
What should I do to avoid echoing in an echo, to achieve my goal?
I wouldn't suggesting using the SignUp() function directly in str_replace() since there are alternate outcomes and it doesn't always return the string you need. Maybe this will work for you.
function SignUpForm(){
return "<form method='post' action=''>";
}
function SignUp($parameters){
if (!isset($_POST["btn"])){
return SignUpForm($parameters); // here I show the form if post is empty
} else {
return false;
}
}
$signUp = SignUp($parameters);
if ($signUp) {
$mystring = str_replace("[signup]", $signUp, $mystring);
} else {
echo $successmessage (or echo $errormessage);
}
echo $mystring;
Don't echo inside of functions, always return strings.
$mystring = str_replace("[signup]",SignUp($parameters),$mystring);
echo $mystring;
function SignUp($parameters){
global $_POST;
if (!isset($_POST["btn"])){
return SignUpForm($parameters); // here I show the form if post is empty
} else {
// here I check the values then do some DB inserts if correct
return ($successmessage) ?: $errormessage;
}
}
function SignUpForm(){
return "<form method='post' action=''>";
}

if and else both are true in my php codes

i wonder that both if and it's else are true.
i got $apple_id_num from the input select form and it is a number but in string type like "7" and it is how many ids that user wants.so i convert it to integer
now i want to check if it is not more that what i have available in my database.
but statements under conditions ($num_rows<$id_num) and if ($num_rows>=$id_num) both are running.
what i'm doin wrong?
here is my code:
function getAppleID($apple_id_num)
{
$sqli=new mysqlii();
$apple_ids=$sqli->SelectFromDB($apple_id_num);
$num_rows=$sqli->num_rows;
$id_num=(int)$apple_id_num;
if ($num_rows>=$id_num){
$this->printAppleID($apple_ids,$num_rows);
//$sqli->updateRows();
echo"else if running";
return $apple_id_num;
} else if ($num_rows<$id_num)
echo "if statement was rungning";
}
Try this code. always write intended code. Sometimes you may miss a } :P
Use elseif in place of else if.
function getAppleID($apple_id_num)
{
$sqli=new mysqlii();
$apple_ids=$sqli->SelectFromDB($apple_id_num);
$num_rows=$sqli->num_rows;
$id_num=(int)$apple_id_num;
if ($num_rows>=$id_num) {
$this->printAppleID($apple_ids,$num_rows);
//$sqli->updateRows();
echo"else if running";
return $apple_id_num;
} elseif ($num_rows<$id_num) {
echo "if statement was rungning";
}
}

Field empty and cancel post to database

I'm still beginner and still confused what to add on the code.. I have a form and I want to validate it some errors, for example. field empty.. So..
Do I have to add 'else' or mysql_error?
$post = isset($_REQUEST['post']) ? $_REQUEST['post'] : null;
if (empty($post))
{
echo "<p class=\"info\">The post field is empty</p>";
}
Any ideas? Thanks.
I would do:
if (empty($_REQUEST['post'])) {
die("The Post field is empty.");
} else {
// Write to the database
}
a mysql_error(), on the other part, will be useful to debug if anything goes wrong when writing to the database.

How to send and receive errors for form validation without using $_GET - PHP

I am trying to send and receive errors in php form validation without having to use the $_GET method. What I thought I would do was create an errors array in my functions.php (reusable functions and variables) file like so:
$errors = array();
And manipulate that errors array like so:
//do work with errors array
//set error into array
function setError($error){
$errors[] = $error;
}
//get information from array
function getError(){
return $errors;
}
//empty errors array
function emptyErrorsArray(){
$errors[] = null;
}
//print errors array
function printErrorsArray(){
var_dump($errors);
}
However when I do the above method, I get no feedback to my form as the errors array says NULL the whole time. I tried setting the $errors array to a global variable but that didn't work out so well for me as well. Any ideas?
You should be using if else statements for PHP validation like so :
if(condition)
{
do this
}
else
{
$errors[] = "your error message"
}
after that go just under the body tag and in php blocks put:
if($errors != "")
{
foreach($errors as $error)
{
echo $error;
}
}
This is to display the errors

Twitter Bootstrap and CodeIgniter's Validation_Errors

I am using Twitter Bootstrap to style validation_errors for a registration page:
<?php
echo "<div class='alert alert-error span4'>";
echo validation_errors();
echo "</div>";
?>
The validations work and show up but part of the styling is always present (the div tag has a red background). Is there a way to have the styling show up ONLY when the validation_errors are present. I have tried a few things (embedding html in php tags and enclosing the php in div tags) but the result is the same.
The reason that the div structure still appears is because it's echoing without regard to whether there are errors or not.
You could set the value of a variable to the result of your validation_errors() function in your Controller, then only display the alert div in your View if you've actually got an error...
Your controller would assign the variable to hold the (potential) error:
$this->data['reported_error'] = validation_errors();
$this->load->view('view_name', $this->data);
Then your view would only display the alert div if there was an error:
if ( isset($reported_error) )
{
echo "<div class='alert alert-error span4'>".$reported_error."</div>";
}
This requires your validation_errors function to only return a value if there is an error.
You can try something like this it works for me.
<?php if(validation_errors()):?>
<div class='alert alert-error span4'><?php echo validation_errors(); ?></div>
<?php endif;?>
I use the following construct to put the errors with special classes next to the fields that they reference:
<div class="<?php echo my_error_class('fieldname') ?>">
<input type="whatever" name="fieldname" />
<span class="whatever"><?php echo my_error_msg('fieldname') ?></>
</div>
with the following functions in a CI helper:
<?php
if ( ! function_exists('my_error_class')) {
function my_error_class($field, $error_class = "error") {
if (FALSE === ($OBJ =& _get_validation_object())){
return '';
}
if(isset($OBJ->_field_data[$field]['error']) && !empty($OBJ->_field_data[$field]['error'])) {
return $error_class;
}
else {
return '';
}
}
}
if ( ! function_exists('my_error_msg')) {
function my_error_msg($field,$default = '') {
if (FALSE === ($OBJ =& _get_validation_object())){
return $default;
}
if(isset($OBJ->_field_data[$field]['error']) && !empty($OBJ->_field_data[$field]['error'])) {
return $OBJ->_field_data[$field]['error'];
}
else {
return $default;
}
}
}
I was having the same issue. I assigned validation_errors() to a variable in my controller and passed it to the view.
Going off James' solution, I had to change:
if ( isset($reported_error) )
to:
if (!empty($reported_error))
Once I did this, the alert block only displayed when there was an error.
I didn't find this in the guide but apparently validation_errors takes two optional args for a prefix and suffix... so you can do:
validation_errors('<p class="text-warning">', '</p>');

Categories