CodeIgniter - last else if statement fail to meet the condition - php

I think it's just a simple mistake I've made, but until now I still can't get the solution why my last else if {} statement does not execute when it meets the condition.
It's my form. I have 3 form elements as options for users to enter value. They can choose either to upload which are text, photo, or movie. Here is my PHP:
if ( $this->input->post('text') !== '') {
//this executes fine when it meets the condition
} else if ( $this->input->post('photo') !== '' ) {
// this also works fine
} else if ( $this->input->post('video') !== '' ) {
/* however, I can't get to this condition when
the user chooses to upload the movie.
It always go the second condition.
*/
}
Edit:
Here's my view:
<form action="<?php echo base_url()?>action/post" method="post" enctype="multipart/form-data">
<ul class="nav nav-tabs">
<li class="active">
Update Status
</li>
<li>
Post Photos
</li>
<li>
Post Videos
</li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="status">
<textarea name="text"></textarea>
</div>
<div class="tab-pane" id="photos">
<input type="file" name="photo" class="input" />
<input type="text" name="photos-detail" placeholder="description" />
</div>
<div class="tab-pane" id="videos">
<input type="file" name="video" class="input" />
<input type="text" name="videos-detail" placeholder="description" />
</div>
</div>
<button type="submit" class="btn btn-primary" name="post">Post</button>
</form>
Any idea would be really appreciated.

You cant check file inputs reliably like that. I usually check the file size to see if anything has been uploaded, so you could do something like this (should work):
if ( $this->input->post('text') !== '') {
//code
} else if((isset($_FILES["photo"]["size"])) && ($_FILES["photo"]["size"] > 0)){
// code 2
} else if((isset($_FILES["video"]["size"])) && ($_FILES["video"]["size"] > 0)){
// code 3
}
NOTE
You can't just check the file size or you will get undefined index error - hence the isset()

If I use the same code the result that I get is that my view show me the entire code line.
if ( $usuario->party !== '') {
<img src="<?php echo base_url('assets/img/link/sprite1_13.png') ?>">
} else {
<img src="<?php echo base_url('assets/img/link/party.png') ?>">
}
If I don´t use my code works fine:
<?php foreach ($usuarios->result() as $usuario) { ?>
<div id="cuerpo" class="cuerpoMyPerfil">
<div id="columna1">
<div id="contenColumn1" class="corner">
<div class="myFoto">
<img src="<?php echo base_url('assets/img/testimonials/user.jpg') ?>" width="100%" height="auto" alt="nombre" /> </div>
<div class="myNombre">
<?php
echo $usuario->nombre . "<br/>";
echo $usuario->apellidos;
?>
</div>
<div class="myDescripcion">
<?php echo $usuario->acerca; ?>
</div>
if ( $usuario->party !== '') {
<img src="<?php echo base_url('assets/img/link/sprite1_13.png') ?>">
} else {
<img src="<?php echo base_url('assets/img/link/party.png') ?>">
}
<dl class="dl-vertical">
<!-- Verificar que tenga valores en la tabla vincular
Si lo trae, poner el ícono prendido, de lo contrario el apagado-->
<dt>
<img class="pull-right" src="<?php echo base_url('assets/img/link/love.png') ?>"></dt>
<dt><img src="<?php echo base_url('assets/img/link/network.png') ?>">
<img class="pull-right" src="<?php echo base_url('assets/img/link/friends.png') ?>"></dt>
</dl>
</div>
<div class='myTextInvi'>
<div class='textInvitacionActual floatL'>Tienes Invitaciones disponibles</div>
<div class='numInvitacionActual floatL' ><?php echo $usuario->disponibles; ?></div>
</div>
<div class='myBtnInvi'>
<a href="<?php echo base_url('oneperfil/invite') ?>">
<div class='textBtnInvitacion'>ENVIAR INVITACIÓN</div>
</a>
</div>
</div>
</div>
<?php } ?>

Related

MySQL on PHP need 2 reloads to update the values

I made a message deleter button, but I need 2 reloads to appear the changes...
(The rest of the code work, so it's normal that I don't show you the rest of the code...)
<?php while($r = $replies->fetch()) { ?>
<div class="message" id="<?= $r['id'] ?>">
<div class="profile">
<img class="avatar" src="members/avatars/<?php if(empty(get_avatar($r['id_author']))) { echo "default.png"; } else { echo get_avatar($r['id_author']); } ?>" width="150" height="150">
<h3 style="text-align: center;"><?= get_username($r['id_author']) ?></h3>
</div>
<div class="content">
<div class="date">
<?= date('d F Y - g:iA', strtotime($r['date_hour_post'])) ?>
</div>
<br><br>
<?= htmlspecialchars_decode($r['content']) ?>
<form method="POST"><button name="delete<?= $r['id'] ?>">Test</button></form>
<?php
$test = "delete".$r['id'];
if(isset($_POST[$test])) {
$delete = $db->prepare('DELETE FROM f_messages WHERE id = ?');
$delete->execute(array($r['id']));
$success = "Your message was successfully removed !";
}
?>
</div>
</div>
<br>
<?php } ?>
UPDATE:
I added the deleting code at the top of my php code, and it's working, thanks to Ray Andison
By the way thanks to keidakida too; he helped me to find a solution to my value problem. (And I think he don't know that)
Your form doesn't contain any data (the id to be deleted) or action (page to submit data to)?
<form method="POST" action="thispage.php">
<input id="test" name="test" type="hidden" value="<?= $r['id'] ?>">
<input type="submit">
</form>
UPDATED:
<?
if(isset($_POST[id])) {
$delete = $db->prepare('DELETE FROM f_messages WHERE id = ?');
$delete->execute(array($_POST[id]));
$success = "Your message was successfully removed !";
}
while($r = $replies->fetch()){
echo '
<div class="message" id="'.$r[id].'">
<div class="profile">
<img class="avatar" src="members/avatars/';
if(empty(get_avatar($r[id_author]))){
echo "default.png";
}else{
echo get_avatar($r[id_author]);
}
echo '
" width="150" height="150">
<h3 style="text-align:center;">
'.get_username($r[id_author]).'
</h3>
</div>
<div class="content">
<div class="date">
'.date('d F Y - g:iA', strtotime($r[date_hour_post])).'
</div>
<br>
<br>
'.htmlspecialchars_decode($r[content]).'
<form method="POST" action="thispage.php">
<input id="id" name="id" type="hidden" value="'.$r[id].'">
<input type="submit">
</form>
</div>
</div>';
}
?>
This is how I would code this, you need to change the action="thispage.php" to be the name of itself so it posts to itself, replace with the actual name of your php file
It is because the delete PHP code is at the bottom. Actions such as delete should be at the top of the HTML or while loops before presenting the data. SO try this:
<?php
if(isset($_POST["delete"])) {
$delete = $db->prepare('DELETE FROM f_messages WHERE id = ?');
$delete->execute(array($_POST['delete']));
$success = "Your message was successfully removed !";
}
while($r = $replies->fetch()) { ?>
<div class="message" id="<?= $r['id'] ?>">
<div class="profile">
<img class="avatar" src="members/avatars/<?php if(empty(get_avatar($r['id_author']))) { echo "default.png"; } else { echo get_avatar($r['id_author']); } ?>" width="150" height="150">
<h3 style="text-align: center;"><?= get_username($r['id_author']) ?></h3>
</div>
<div class="content">
<div class="date">
<?= date('d F Y - g:iA', strtotime($r['date_hour_post'])) ?>
</div>
<br><br>
<?= htmlspecialchars_decode($r['content']) ?>
<form method="POST">
<button type="button" name="delete" value="<?php echo $r['id']; ?>">Test</button>
</form>
</div>
</div>
<br>
<?php
}
?>
But you can do the same functionality without any page reload. Check AJAX PHP
Since it would be better and easier with AJAX, this is how it goes:
main.php
<?php
while ($r = $replies->fetch()) { ?>
<div class="message" id="<?= $r['id'] ?>">
<?php echo htmlspecialchars_decode($r['content']) ?>
<button onclick="delete('<?php echo $r['id']; ?>')">Delete</button>
</div>
<br>
<?php } ?>
<script>
function delete(id) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert("Delete successfully");
location.reload();
}
};
xmlhttp.open("POST", "delete.php", true);
// Mandatory for simple POST request
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Send id you want to delete
xmlhttp.send("id=" + id);
}
</script>
And make another PHP file name is delete.php like this:
<?php
include 'YOUR_DB_Connect.php';
if(isset($_POST["delete"])) {
$delete = $db->prepare('DELETE FROM f_messages WHERE id = ?');
$delete->execute(array($_POST['delete']));
}
?>

Posting Comments to PHP Using Ajax

I'm having this comment form. this comment form works but not correctly whenever I post comment it works on 1 post and on another it refreshes the page and data is also not inserted all the post are fetch by while loop
JS:
< script type = "text/javascript" >
$(function() {
$("#submit").click(function() {
var mcomment = $("input#mcomment").val(); // define the name variable
var mesgid = $("input#mesgid").val();
if (mcomment == '') // if name field is empty
{
alert("Write Comment Please."); // alert an error mesaage
} else {
$.ajax({ // JQuery ajax function
type: "POST", // ajax submit method
url: "status/savecomment.php",
data: 'mcomment=' + mcomment + '&mesgid=' + mesgid, // data sent to php file
cache: false,
success: function(html) { // if the result returns success
$("#comment_display").after(html);
}
});
}
return false;
});
});
< /script>
HTML:
<form method="POST" id="commentform">
<div class="panel-footer p15">
<div class="admin-form">
<img src="image.png">
<label for="reply1" >
<input name="mesgid" id="mesgid" type="hidden" value="
<?php echo $id ?>">
<input name="mcomment" id="mcomment" placeholder="Respond with a
comment." type="text" style="width:130%;">
</label>
<button type="submit" id="submit" class="button
btn-primary submit-btn" name="" style="width:90px; margin-
left:50px;">Comment</button>
</div>
</div>
</form>
here is all new edited code
<?php
$msql=mysql_query("SELECT * from `messages` ORDER BY `msg_id` DESC LIMIT
$post_limit");
while($messagecount=mysql_fetch_array($msql))
{
$id=$messagecount['msg_id'];
$msgcontent=$messagecount['message'];
$usermsg=$messagecount['username'];
$userimg=$messagecount['image'];
$userimg1=$messagecount['user_img'];
$usertime=$messagecount['time'];
?>
<i class="pointer" id="pagination-<?php echo $id;?>"></i>
<div style="display: block;" class="timeline-item" id="clone-3">
<div class="panel">
<div class="panel-heading">
<span class="panel-title" style="color:#000;"><?php echo
ucfirst($usermsg); ?> Updated a </span><a href="post.php?id=<?php echo
$id;?>">Post</a>
<span class="panel-date pull-right mr10 text-muted fs12">
<?php echo timeAgo($messagecount['time']);?> via Web</span>
</div>
<div class="panel-body">
<p><img src="image.php/<?php echo $userimg1;?>?width=60&
height=70&nocache&quality=100&image=http://localhost/niftians/profile
/upload/<?php echo $userimg1;?>" /> <?php echo
parse_smileys(make_clickable(nl2br(stripslashes($msgcontent))),
$smiley_folder); ?><br><br><?php if(!empty($messagecount['image'])) { ?>
<img src="status/image.php/<?php echo
$messagecount['image'];?>?width=350&nocache&quality=100&
image=http://localhost/niftians/profile/upload/<?php echo
$messagecount['image'];?>" style="margin-left:10%;">
<?php } ?></p>
</div>
</div>
</div>
<?php
$sql=mysql_query("select * from comments where msg_id_fk='$id' order by
com_id");
$comment_count=mysql_num_rows($sql);
if($comment_count>2)
{
$second_count=$comment_count-2;
?><div class="comment_ui" id="view<?php echo $id; ?>">
<div>
<a href="#" class="view_comments" id="<?php echo $id; ?>">View all <?php
echo $comment_count; ?> comments</a>
</div>
</div>
<?php
}
else
{
$second_count=0;
}
?>
<div id="view_comments<?php echo $id; ?>"></div>
<div id="two_comments<?php echo $id; ?>">
<?php
$listsql=mysql_query("select * from comments where msg_id_fk='$id' order
by com_id limit $second_count,2 ");
while($rowsmall=mysql_fetch_array($listsql))
{
$c_id=$rowsmall['com_id'];
$comment=$rowsmall['comments'];
$userid3=$rowsmall['username'];
$userimg5=$rowsmall['user_img'];
$usercom=$rowsmall['time'];
?> <div id="comment_display"></div>
<div class="media mt15" id="aniket">
<a class="pull-left" href="#"> <img class="media-
object thumbnail thumbnail-sm rounded mw40" src="image.php/<?php echo
$userimg5;?>?width=60&height=60&nocache&quality=100&
image=http://localhost
/niftians/profile/upload/<?php echo $userimg5;?>" alt="..."> </a>
<div class="media-body mb5">
<h5 class="media-heading mbn"><a href="<?php echo
$userid3; ?>"><?php echo ucfirst($userid3); ?></a>
<small> -<?php echo timeAgo($rowsmall['time']);?>
</small>
</h5>
<p><?php echo
parse_smileys(make_clickable(nl2br(stripslashes($comment))),
$smiley_folder); ?></p>
</div>
</div>
<?php } ?>
</div>
<form method="POST" id="commentform">
<div class="panel-footer p15">
<div class="admin-form">
<img src="image.php/<?php echo $info->img;?>?width=45&nocache&
quality=100&image=http://localhost/niftians/profile/upload/<?php echo
$info->img;?>">
<label for="reply1" >
<input name="mesgid" id="mesgid" type="hidden" value="<?php echo $id ?>">
<input name="mcomment" id="mcomment" placeholder="Respond with a
comment." type="text" style="width:130%;">
</label>
<button type="submit" id="submit" class="button
btn-primary submit-btn" name="" style="width:90px; margin-
left:50px;">Comment</button>
</div>
</div>
</form>
<br>
<?php
}
?>
What you need to do is
Remove Submit Button and add <input type="button">
2nd create a div in your page named as <div id="comment_display"></div>
And if this does not solve problem, post your While loop.
Replace this line
$("#submit").click(function() {
with
$("#submit").on('.submit','click',function(e) {
e.preventDefault();
Note: Your submit can work too, but you would have to stop its default behavior using jquery

If / Else Statements

I am having a problem placing the IF / ELSE statement without breaking the rest of the page.
I have a following banner on my page :
<div class="awesome-banner">
<div class="image-wrap<?php echo $banner ? '' : ' awesome-hide'; ?>">
<?php $banner_url = $banner ? wp_get_attachment_url($banner) : ''; ?>
<input type="hidden" class="awesome-file-field" value="<?php echo $banner; ?>" name="awesome_banner">
<img class="awesome-banner-img" src="<?php echo esc_url($banner_url); ?>">
<a class="close awesome-remove-banner-image">×</a>
</div>
<div class="button-area<?php echo $banner ? ' awesome-hide' : ''; ?>">
<i class="fa fa-cloud-upload"></i>
<?php _e('Upload banner', 'awesome'); ?>
<p class="help-block"><?php _e('(Upload a banner for your profile. Banner size is (825x300) pixel. )', 'awesome'); ?></p>
</div>
</div> <!-- .awesome-banner -->
<?php do_action('awesome_settings_after_banner', $current_user, $profile_info); ?>
I need to place in the following statement inside this banner ( PLEASE CORRECT IF WRONG ):
<?
if ((current_user_can('manager')) )
{ ?>
<div class="access-restricted">
<h5>Sign In Or Sign Up</h5>
<p class="non-manager-notice">You need to be a manager to upload a banner</p>
<div class="upgrade-button">
Upgrade Account
</div>
</div>
<?
return;
} else{
return false;
}
?>
So basically it should state the following inside this banner :
If the current user is user role "manager" then instead of the <div class="button-area"> it should display <div class="access-restricted">
Otherwise just go on as normally.
I am trying to place the statement directly inside like this :
<div class="awesome-banner">
<div class="image-wrap<?php echo $banner ? '' : ' awesome-hide'; ?>">
<?php $banner_url = $banner ? wp_get_attachment_url($banner) : ''; ?>
<input type="hidden" class="awesome-file-field" value="<?php echo $banner; ?>" name="awesome_banner">
<img class="awesome-banner-img" src="<?php echo esc_url($banner_url); ?>">
<a class="close awesome-remove-banner-image">×</a>
</div>
// Here I am placing my statement like this
<?
if ((current_user_can('manager')) )
{ ?>
<div class="access-restricted">
<h5>Sign In Or Sign Up</h5>
<p class="non-manager-notice">You need to be a manager to upload a banner</p>
<div class="upgrade-button">
Upgrade Account
</div>
</div>
<?
return;
} else{
return false;
}
?>
// End of my statement
<div class="button-area<?php echo $banner ? ' awesome-hide' : ''; ?>">
<i class="fa fa-cloud-upload"></i>
<?php _e('Upload banner', 'awesome'); ?>
<p class="help-block"><?php _e('(Upload a banner for your profile. Banner size is (825x300) pixel. )', 'awesome'); ?></p>
</div>
</div> <!-- .awesome-banner -->
<?php do_action('awesome_settings_after_banner', $current_user, $profile_info); ?>
It displays the content correctly for the role, but it breaks the rest of the content on the page behind the awesome banner div.
Am I closing my statement and everything else correctly ?? Thanks
Further to my (and #maiorano84's comments), the return will stop your code if either condition is met (true or false):
if(current_user_can('manager')) { ?>
<div class="access-restricted">
<h5>Sign In Or Sign Up</h5>
<p class="non-manager-notice">You need to be a manager to upload a banner</p>
<div class="upgrade-button">
Upgrade Account
</div>
</div><?
// If you need to record a true or false here, assign to a variable.
// Don't return or your code will stop here.
$manager = true;
}
else { ?>
<div class="button-area<?php if($banner) echo ' awesome-hide'; ?>">
<i class="fa fa-cloud-upload"></i>
<?php _e('Upload banner', 'awesome'); ?>
<p class="help-block"><?php _e('(Upload a banner for your profile. Banner size is (825x300) pixel. )', 'awesome'); ?></p>
</div><?php
// If you need true/false, assign here
$manager = false;
} ?>

javascript executing php code

i have a php web application project ... and i want to implement a javascript onclick code ..
for example :
when user clicks follow this post ... the MySQL query inserts into database that the user followed this ... so the page is refreshed and after that it will appear as FOLLOWED ..
what's the javascript code needed to do this ... or is there any example may fit ??
here's a sample code
<div id="main_content">
<?php
if(isset($_GET['et']))
{
$et = $_GET['et'];
}
$result = mysql_query("select * from events where event_type =$et") ;
require_once('queries/category_extract.php') ;
?>
<div id="body_content">
<div id="event_tag">
<a><?php echo $cattitle["categ_title"]?>s</a>
</div>
<?php
while($row=mysql_fetch_array($result) )
{
require('queries/followers_extract.php')
?>
<div id="postpreview">
<div id="postpreview_up">
<div id="postpreview_up_left">
<div id="postpreview_up_left_left">
<a>Event Title :</a>
</div>
<div id="postpreview_up_left_right">
<a><?php echo $row["event_title"] ?></a>
</div>
</div>
<div id="postpreview_up_right">
<img src="images/read_more.gif" />
</div>
</div>
<div id="postpreview_bottom">
<div id="postpreview_bottom_left">
<div id="postpreview_bottom_left_left">
<a>Date :</a>
</div>
<div id="postpreview_bottom_left_right">
<a><?php echo $row["event_date"] ?></a>
</div>
</div>
<div id="postpreview_bottom_right">
<div id="postpreview_bottom_right_left">
<?php
if($follower['follower_id'] ==NULL){echo " <img src='images/follow_button.jpg' /> " ; }
else { echo " <img src='images/follow_closed.jpg' /> " ;}
?>
</div>
<div id="postpreview_bottom_right_right">
<?php
if($follower['follower_id'] !=NULL){ echo " <img src='images/following_button.jpg' /> " ; }
else { echo " <img src='images/following_Closed.jpg' /> " ;}
?>
</div>
<div id="postpreview_bottom_right_right">
<?php
if($follower['follower_id'] !=NULL){ echo " <img src='images/unfollow_button.jpg' /> " ; }
else { echo " <img src='images/unfollow_closed.jpg' /> " ;}
?>
</div>
</div>
</div>
</div>
<div id="splitter"></div>
<?php
}
?>
<!--End Of Post Preview-->
<!--End Of Post Preview-->
ok go for this: http://www.9lessons.info/2009/04/exactly-twitter-like-follow-and-remove.html
you have to learn the basics as i read.

foreach and if, displaying content in correct order

Here is my code, it basically grabs $banners and displays them out, there are 2 at the moment, however , it stops after the first one and displays out the html div id="footerNews... etc and carries on again after that. This is correct...
<?php if ($banners) { $i = 1; ?>
<div id="footerBanners">
<?php foreach ($banners as $banner) { ?>
<img src="<?php echo $banner['image']; ?>" alt="<?php echo $banner['title']; ?>" />
<?php if ($i == 1) { ?>
<div id="footerNewsletter">
<p>Newsletter Sign Up</p>
Go
<input type="text" name="email" placeholder="Email address" />
</div>
<div id="footerEvents"><?php echo $text_events; ?></div>
<?php } ?>
<?php $i++; } ?>
</div>
<?php } ?>
The problem is that some of variables in $banners dont actually have a link. To get around this, I attempted to put an if statement in to not display <a href> if there is no link. however this messes up the order that of the content, its important that I keep the content in the correct order as above ^. Here was my attempt.
<?php if ($banners) { $i = 1; ?>
<div id="footerBanners">
<?php foreach ($banners as $banner) { ?>
<?php if ($banner['link'] == '') { ?>
<img src="<?php echo $banner['image']; ?>" alt="<?php echo $banner['title']; ?>" /><?php }
else { ?>
<img src="<?php echo $banner['image']; ?>" alt="<?php echo $banner['title']; ?>" /><?php } ?>
<?php } ?>
<?php if ($i == 1) { ?>
<div id="footerNewsletter">
<p>Newsletter Sign Up</p>
Go
<input type="text" name="email" placeholder="Email address" />
</div>
<div id="footerEvents"><?php echo $text_events; ?></div>
<?php } ?>
<?php $i++; } ?>
</div>
While the code does what it says its supposed to do, its not displaying the correct order anymore, its displaying the 1 linkable $banner then the html, and THEN the image(ie the second $banner with no link. However I need it to display in the same layout as the first bit of code.
Here is the outputted html code, although the image is appearing last on the site.
<div id="footerBanners">
<img src="http://mysite.com/image/data/banner4.jpg" alt="Free Delivery" />
<img src="http://mysite.com/image/data/banner5.jpg" alt="Gift Vouchers" /> <div id="footerNewsletter">
<p>Newsletter Sign Up</p>
Go
<input type="text" name="email" placeholder="Email address" />
</div>
<div id="footerEvents">EVENTS</div>
</div>
Any pointers?
<?php if ($banners) {
echo '<div id="footerBanners">';
foreach ($banners as $banner) {
if ($banner['link'] == '') {
echo '<img src="'.$banner['image'].'" alt="'.$banner['title'].'" />';
}
else {
echo '<img src="'.$banner['image'].'" alt="'.$banner['title'].'" />';
}
if ($first_banner != 'displayed') {
echo '<div id="footerNewsletter">
<p>Newsletter Sign Up</p>
Go
<input type="text" name="email" placeholder="Email address" />
</div>
<div id="footerEvents">'.$text_events.'</div>';
$first_banner = 'displayed';
}
}
echo '</div>';
}
?>

Categories