Hostgator cron job not working with this script - php

So I've been trying to use the Cron Job Manager at Hostgator, I select the php file and it should execute when sheduled. If i want to run the script manually, then I'd write http://thesitename.com/myfile.php and would execute, in this case, I'm sending PDFs to an email. Please check my code and see if I'm doing something wrong:
<?php
define('WP_USE_THEMES', true);
require( dirname( __FILE__ ) . '/wp-blog-header.php' );
set_time_limit(0);
ignore_user_abort(1);
$args = array(
'post_type' => 'inversion',
'orderby' => 'meta_value_num',
'meta_key' => 'numero_de_ordenamiento',
'order' => 'ASC',
'meta_query' => array(
array(
'key' => 'inversionista'
)
)
);
$the_query = new WP_Query( $args );
$current_posts = $the_query->get_posts();
print_r($current_posts);
foreach ($current_posts as $post)
{
$post_id = $post->ID;
$inversion = get_post($post_id);
$eluser = get_field('inversionista',$post_id);
$numconf=get_field('numero_de_cliente', 'user_'.$eluser['ID']);
$numord = get_field('numero_de_ordenamiento',$post_id);
ob_start(); ?>
<section class="wrap">
<img src="<?php bloginfo('template_directory');?>/images/CherryV.jpg" width="20%" alt="Site Logo">
<img style="float:right;" src="<?php bloginfo('template_directory');?>/images/info.jpg" width="45%" alt="Site Logo">
</section>
<br>
Logout
<br>
<h3 style="color:red;"><u>Estado de movimientos <?php $month = date(m);
if($month==1)
{
$elmes = "Enero";
}elseif($month==2){
$elmes = "Febrero";
}elseif($month==3){
$elmes = "Marzo";
}elseif($month==4){
$elmes = "Abril";
}elseif($month==5){
$elmes = "Mayo";
}elseif($month==6){
$elmes = "Junio";
}elseif($month==7){
$elmes = "Julio";
}elseif($month==8){
$elmes = "Agosto";
}elseif($month==9){
$elmes = "Septiembre";
}elseif($month==10){
$elmes = "Octubre";
}elseif($month==11){
$elmes = "Noviembre";
}elseif($month==12){
$elmes = "Diciembre";
}
echo $elmes;
echo " ";
echo date(Y); ?></u></h3>
<h3>Cliente confidencial: <?php echo $numconf; ?> </h3>
<h3>Movimientos correspondientes al periodo: 1 al 31 de <?php echo $elmes ." ".date(Y); ?></h3>
<br>
<div id="customers">
<table class="tabla" autosize="1" cellpadding="0" cellspacing="0" width="100%" border="1">
<thead>
<tr>
<td>
<h3 class="table2" >Periodo de Inversión</h3>
</td>
<td>
<h3 class="table2">Saldo Inicial</h3>
</td>
<td>
<h3 class="table2" >Inversión en el Periodo</h3>
</td>
<td>
<h3 class="table2" >Interés Causado en el Periodo</h3>
</td>
<td>
<h3 class="table2" >Intereses Pagados</h3>
</td>
<td>
<h3 class="table2" >Intereses Reinvertidos</h3>
</td>
<td>
<h3 class="table2" >Saldo Final</h3>
</td>
</tr>
</thead>
<tbody>
<?php
$igalf = 0;
if( have_rows('datos_especificos') ):
?>
<?php
$highest = 0;
$arraycount=0;
$thearrayking = array();
$arrayinsert = array();
while ( have_rows('datos_especificos') ) : the_row();
$icelpx = get_sub_field('interes_causado_en_el_periodo',$post_id);
$cpx = get_sub_field('cantidad_pagada',$post_id);
$crx = get_sub_field('cantidad_reinvertida',$post_id);
$sal1x = get_sub_field('saldo',$post_id);
$ipx = get_sub_field('inversion_en_el_periodo',$post_id);
$sal2x = get_sub_field('saldo_final',$post_id);
$fech = get_sub_field('fecha',$post_id);
$fecharray0 = substr($fech,0,4);
$fecharray1 = substr($fech,4,2);
$fecharray = $fecharray1."/".$fecharray0;
$sal1 = get_sub_field('saldo',$post_id);
$ielp = get_sub_field('inversion_en_el_periodo',$post_id);
$icelp = get_sub_field('interes_causado_en_el_periodo',$post_id);
$cp = get_sub_field('cantidad_pagada',$post_id);
$elsf2 = get_sub_field('saldo_final',$post_id);
$cr = get_sub_field('cantidad_reinvertida',$post_id);
$crt = $crt+$cr;
$sal2 = get_sub_field('saldo_final',$post_id);
$igalf = $igalf+$icelp;
$fech2 = $fech+100;
$ID= $the_query->ID;
if($highest<$elsf2)
{
$highest = $elsf2;
}
$arrayinsert = array($fecharray, $elsf2);
array_push($thearrayking, $arrayinsert);
$arraycount = $arraycount+1;
$fechstring="$fech";
$part1=substr("$fechstring", 0, 4);
$part2=substr("$fechstring", 4, 2);
$part3=substr("$fechstring", 6,2);
//$date = DateTime::createFromFormat('Ymd', $retrieved); ?>
<tr>
<td>
<p class="table" style="text-align:center;"> <?php echo $part3."/".$part2."/".$part1; ?> </p>
</td>
<td>
<p class="table" style="text-align:center;"> <?php echo "$ ".number_format($sal1,2); ?> </p>
</td>
<td>
<p class="table" style="text-align:center;"> <?php echo "$ ".number_format($ielp,2); ?> </p>
</td>
<td>
<p class="table" style="text-align:center;"> <?php echo "$ ".number_format($icelp,2); ?> </p>
</td>
<td>
<p class="table" style="text-align:center;"> <?php echo "$ ".number_format($cp,2); ?> </p>
</td>
<td>
<p class="table" style="text-align:center;"> <?php echo "$ ".number_format($crx,2); ?> </p>
</td>
<td>
<p class="table" style="text-align:center;"> <?php echo "$ ".number_format($sal2x,2); ?> </p>
</td>
</tr>
<?php
endwhile;
else :
// no rows found
endif;
?>
</tbody>
</table>
</div>
<br>
<br>
<h1>Resumen de Inversión</h1>
<br>
<table autosize="5">
<?php
$fech7 = $fech + 100;
$ptest = substr($fech7,4,2);
if($ptest==12)
{
$fech7=$fech7-1200+10000;
}
$fechstringxx = $fech7;
$part1x=substr("$fechstringxx", 0, 4);
$part2x=substr("$fechstringxx", 4, 2);
$part3x=substr("$fechstringxx", 6, 2);
// $date2 = DateTime::createFromFormat('Ymd', $retrieved2); ?>
<tr>
<td>
<h3 class="table2" style="text-align:center;"> Saldo Inicial <?php echo $part3."/".$part2."/".$part1; ?> </h3>
</td>
<td>
<p class="table" style="text-align:center;"> <?php echo "$ ".number_format( $sal1,2); ?> </p>
</td>
</tr>
<tr>
<td>
<h3 class="table2" style="text-align:center;"> Nuevas Inversiones </h3>
</td>
<td>
<p class="table" style="text-align:center;"> <?php echo "$ ".number_format( $ielp,2); ?> </p>
</td>
</tr>
<tr>
<td>
<h3 class="table2" style="text-align:center;"> Intereses Pagados </h3>
</td>
<td>
<p class="table" style="text-align:center;"> <?php echo "$ ".number_format( $cp,2); ?> </p>
</td>
</tr>
<tr>
<td>
<h3 class="table2" style="text-align:center;"> Intereses Reinvertidos </h3>
</td>
<td>
<p class="table" style="text-align:center;"> <?php echo "$ ".number_format( $crx,2); ?> </p>
</td>
</tr>
<tr>
<td>
<h3 class="table2" style="text-align:center;"> Total Intereses Generados a la fecha</h3>
</td>
<td>
<p class="table" style="text-align:center;"> <?php echo "$ ".number_format( $igalf,2); ?> </p>
</td>
</tr>
<tr>
<td>
<h3 class="table2" style="text-align:center;"> Saldo Final <?php echo $part3x."/".$part2x."/".$part1x; ?> </h3>
</td>
<td>
<p class="table" style="text-align:center;"> <?php echo "$ ".number_format( $sal2,2); ?> </p>
</td>
</tr>
</table>
<?php $tableVar = ob_get_contents();
$numord2 = str_replace(".","-",$numord);
$correo = $current_user->user_email;
// echo $correo;
$mpdf = new mPDF('c');
$stylesheet = file_get_contents(get_template_directory_uri() . '/table.css');
$mpdf->WriteHTML($stylesheet,1);
$mpdf->WriteHTML($tableVar,2);
$mpdf->Output('test24.pdf','F');
$content = $mpdf->Output('', 'S');
$content = chunk_split(base64_encode($content));
$mailto = $correo; //Mailto here
$from_name = 'Cherry'; //Name of sender mail
$from_mail = '9#gmail.com'; //Mailfrom here
$subject = 'Reporte De Inversion'.$numord;
$message = 'Hola te mando tu reporte de inversion';
$filename = "Reporte-De-Inversiones-".date("m-Y",time())." ".$numord2; //Your Filename whit local date and time
//Headers of PDF and e-mail
$boundary = "XYZ-" . date("dmYis") . "-ZYX";
$header = "--$boundary\r\n";
$header .= "Content-Transfer-Encoding: 8bits\r\n";
$header .= "Content-Type: text/html; charset=ISO-8859-1\r\n\r\n"; //plain
$header .= "$message\r\n";
$header .= "--$boundary\r\n";
$header .= "Content-Type: application/pdf; name=\"".$filename."\"\r\n";
$header .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n";
$header .= "Content-Transfer-Encoding: base64\r\n\r\n";
$header .= "$content\r\n";
$header .= "--$boundary--\r\n";
$header2 = "MIME-Version: 1.0\r\n";
$header2 .= "From: ".$from_name." \r\n";
$header2 .= "Return-Path: $from_mail\r\n";
$header2 .= "Content-type: multipart/mixed; boundary=\"$boundary\"\r\n";
$header2 .= "$boundary\r\n";
$bob = "bobsemail#email.com";
//$sended = mail($mailto,$subject,$header,$header2, "-r".$from_mail);
$sended2 = mail($bob,$subject,$header,$header2, "-r".$from_mail);
//echo($sended);
echo($sended2);
$mpdf->Output($filename ,'F');
}
?>

Before all: Hostgator doesn't allow Crons running with a difference of under 15 minutes, you can read that information here. If that is your case, your problem is solved.
Now there are two ways of solving your problem:
1. Fix the cron and run the script (the wrong or at least, the incorrect way, I'll explain below):
You need to give read and write access to the file so the system can run it. Try 777 for debugging.
If it's not working, please edit the OP with the cron instruction so we can debug it.
It should look something like the example below, Hostgator give you information on how it should look here:
/opt/php55/bin/php /home/username/public_html/cron.php
Hostgator provides information about Crons here, about cURL here and there's someone complaining about the same thing in their forums here.
Somewhere in your /home/ folder should be a file called cron.errors.log, you can find there relevant information, for sure.
I'm pretty sure your problem is related with the include path.
I say this is the incorrect way because you're using Wordpress and in that case you should use native WP core function in order to make your script work, particularly by doing a plugin and using wp_schedule_event()
2. The correct way to do it - Plugin + wp_schedule_event();
Transform your script into a plugin. This way there's no need to include the wp-blog-header.php to access the functions and things will work much more integrated.
Here's a quick tutorial on how to do a plugin and you can access information about wp_schedule_event in the Wordpress page about it.
Basically, should look something like this:
register_activation_hook( __FILE__, 'prefix_activation' );
/**
* On activation, set a time, frequency and name of an action hook to be scheduled.
*/
function prefix_activation() {
wp_schedule_event( time(), 'hourly', 'prefix_hourly_event_hook' );
}
add_action( 'prefix_hourly_event_hook', 'prefix_do_this_hourly' );
/**
* On the scheduled action hook, run the function.
*/
function prefix_do_this_hourly() {
// do something every hour
}
But there's a catch: the scheduled event only runs if the site has visitors. It's not the best behavior but is what we have available.
This way you'll be free of Hostgator and can have a cool plugin that is perfectly integrated with your system.

Related

How do you "transfer" a dynamic value from one php page to another php page?

How can you pass dynamic details which are retrieved from a database (e.g. details in a shopping cart table) from one page to another page so that you could send them via email using the mail() function?I tried many ways using the "$message" but none worked. I am new to PHP and do not have much experience with it yet. Any help would be appreciated, thank you.
page 1:
<?php session_start();
//starting the session
include("adminarea/includes/DBcon.php");
include ("functions/php1.php");
include ("header.php");
require 'obj.php';
?>
<link rel="stylesheet" href = "styles/styling.css" media="all" />
<body>
<?php
//Fetches information from the database and displays them with the help of obj.php
if(isset($_GET['pID'])){
$res = mysqli_query($connection, 'select * from product where pID='.$_GET['pID']);
$prod = mysqli_fetch_object($res);
$obj = new obj();
$obj->pID = $prod->pID;
$obj->pName = $prod->pName;
$obj->pPrice = $prod->pPrice;
$obj->qty = 1;
//to check if products exists in cart or not
$index = -1;
$cart = unserialize(serialize($_SESSION['cart']));
for($i=0;$i<count($cart);$i++)
if($cart[$i]->pID==$_GET['pID'])
{
$index = $i;
break;
}
if($index==-1)
$_SESSION['cart'][] = $obj;
else{
$cart[$index]->qty++;
$_SESSION['cart']=$cart;
}
echo "
<script>
window.open('cart.php','_self')
</script>
";
$_SESSION['pID'] = $_POST['pID'];
$_SESSION['pName'] = $_POST['pName'];
$_SESSION['pPrice'] = $_POST['pPrice'];
$_SESSION['qty'] = $_POST['qty'];
}
if(!(isset($_SESSION['cart']))){
echo "
<script>
alert('Shopping cart is empty!')
window.location.href='index.php';
</script>
";
}
//if statement to delete the chosen product inside the cart
if(isset($_GET['index']))
{
$cart = unserialize(serialize($_SESSION['cart']));
unset ($cart[$_GET['index']]);
$cart = array_values($cart);
$_SESSION['cart'] = $cart;
}
?>
<!-- This is to display the shopping cart table-->
<table cellpadding="5" cellspacing="4" border ="9" align="center" width="100%" border="9" bgcolor="darkred">
<td style="color:#FFF" colspan="10" align="center"><h2><u><i>Shopping Cart:</i></u></h2>
<tr>
<th style="color:#FFF">Option</th>
<th style="color:#FFF">Id</th>
<th style="color:#FFF">Name</th>
<th style="color:#FFF">Price</th>
<th style="color:#FFF">Quantity</th>
<th style="color:#FFF">SubTotal</th>
</tr>
<?php
$cart = unserialize(serialize($_SESSION['cart']));
$s = 0;
$index = 0;
for($i=0; $i<count($cart); $i++){
$s += $cart[$i] ->pPrice * $cart[$i]->qty;
?>
<tr>
<td>
<div class="shopcart">
<input id="input" type="submit" name="ctable"/>Remove</input></td>
<td style="color:#FFF" align="center"><?php echo $cart[$i] ->pID; ?> </td>
<td style="color:#FFF" align="center"><?php echo $cart[$i] ->pName; ?></td>
<td style="color:#FFF" align="center">€<?php echo $cart[$i] ->pPrice; ?></td>
<td style="color:#FFF" align="center"><?php echo $cart[$i] ->qty; ?></td>
<td style="color:#FFF" align="center">€<?php echo $cart[$i] ->pPrice * $cart[$i]->qty;?></td>
</tr>
<?php }
$index++;
?>
<tr>
<td colspan="5" align="right" style="color:#FFF">Total</td>
<td style="color:#FFF" align="center">€<?php echo $s;?></td>
</tr>
</table>
<br>
<a id="a" style="margin-left: 10px;" href="products.php"> Go back</a><br><br>
<div id="checkout">
<form id="checkout" method="post" action="checkout.php">
<input id="input" type="submit" name="check" value="Checkout" style="background-color:gray; width:200px; margin-right: 10px;">
</div>
</div>
<?php include("footer.php") ?>
</body>
</html>
page 2:
<?php session_start();
require 'obj.php';
include("adminarea/includes/DBcon.php");
$to = "techologyy#gmail.com";//direction
$subject = "Purchase Details:";
$message = $_SESSION['pID'];
$message .= $_SESSION['pName']."\r\n";
$message .= $_SESSION['pPrice']."\r\n";
$message .= $_SESSION['qty']."\r\n";
$headers = 'From: techologyy#gmail.com' . "\r\n"; //from
//mail paramter with correct order
mail($to, $subject, $message, $headers);
//echo to display alert
echo "
<script>
alert('The checkout has been done successfully! Thank you')
window.location.href='index.php';
</script>
"; //returns the user back to homepage
?>
Please specify what you have tried so far.
you want to send the data from one page to another, try using form tag in html
and set the method attribute to post and action attribute to where you want to send the data.
The html code will look like this
<form action="post" action="getdata.php"> <input id="val" type="text" value="" name="cart" style="display:none;"> <button type="submit" >hit me</button> </form>
You can set the value of input using javascript
document.getElementById("val").value="YourValue";
getdata.php will look like this
> if ($_SERVER["REQUEST_METHOD"] == "POST"){
> $cartval=$_POST['cart'];
> echo $cartval; }
be sure to validate the data and check for any hidden code before executing the user input

Making use of PHP to send an email when checkout is done

So I have been working on a website and I tried to make a functional shopping cart with a checkout system. However, the shopping cart does not allow removal of added items in Mozilla Firefox, on other browsers it works well; I do not know why this is so.
Furthermore, my second problem is that in the checkout.php function, whenever I press the checkout button in the shopping cart page, it does not send the email of order to the business email. Is there a way how I can make this work please? Below I have put all the necessary code. Thank you.
cart.php:
<link rel="stylesheet" href = "styles/styling.css" media="all" />
<?php
session_start();
include("adminarea/includes/DBcon.php");
include ("functions/php1.php");
include ("header.php");
require 'obj.php';
?>
<body>
<?php
//Fetches information from the database and displays them with the help of obj.php
if(isset($_GET['pID'])){
$res = mysqli_query($connection, 'select * from product where pID='.$_GET['pID']);
$prod = mysqli_fetch_object($res);
$obj = new obj();
$obj->pID = $prod->pID;
$obj->pName = $prod->pName;
$obj->pPrice = $prod->pPrice;
$obj->qty = 1;
//to check if products exists in cart or not
$index = -1;
$cart = unserialize(serialize($_SESSION['cart']));
for($i=0;$i<count($cart);$i++)
if($cart[$i]->pID==$_GET['pID'])
{
$index = $i;
break;
}
if($index==-1)
$_SESSION['cart'][] = $obj;
else{
$cart[$index]->qty++;
$_SESSION['cart']=$cart;
}
echo "
<script>
window.open('cart.php','_self')
</script>
";
}
if(!(isset($_SESSION['cart']))){
echo "
<script>
alert('Shopping cart is empty!')
</script>
";
echo "
<script>
window.open('products.php','_self')
</script>
";
}
//if statement to delete the chosen product inside the cart
if(isset($_GET['index']))
{
$cart = unserialize(serialize($_SESSION['cart']));
unset ($cart[$_GET['index']]);
$cart = array_values($cart);
$_SESSION['cart'] = $cart;
}
?>
<!-- This is to display the shopping cart table-->
<table cellpadding="5" cellspacing="4" border ="9" align="center" width="100%" border="9" bgcolor="darkred">
<td style="color:#FFF" colspan="10" align="center"><h2><u><i>Shopping Cart:</i></u></h2>
<tr>
<th style="color:#FFF">Option</th>
<th style="color:#FFF">Id</th>
<th style="color:#FFF">Name</th>
<th style="color:#FFF">Price</th>
<th style="color:#FFF">Quantity</th>
<th style="color:#FFF">SubTotal</th>
</tr>
<?php
$cart = unserialize(serialize($_SESSION['cart']));
$s = 0;
$index = 0;
for($i=0; $i<count($cart); $i++){
$s += $cart[$i] ->pPrice * $cart[$i]->qty;
?>
<tr>
<td>
<div class="shopcart">
<button style="width:150px; height:50px;">Remove</button></td>
<td style="color:#FFF" align="center"><?php echo $cart[$i] ->pID; ?> </td>
<td style="color:#FFF" align="center"><?php echo $cart[$i] ->pName; ?></td>
<td style="color:#FFF" align="center">€<?php echo $cart[$i] ->pPrice; ?></td>
<td style="color:#FFF" align="center"><?php echo $cart[$i] ->qty; ?></td>
<td style="color:#FFF" align="center">€<?php echo $cart[$i] ->pPrice * $cart[$i]->qty;?></td>
</tr>
<?php }
$index++;
?>
<tr>
<td colspan="5" align="right" style="color:#FFF">Total</td>
<td style="color:#FFF" align="center">€<?php echo $s;?></td>
</tr>
</table>
<br>
<a id="a" style="margin-left: 10px;" href="products.php"> Go back</a><br><br>
<div id="checkout">
<form id="checkout" method="post" action="checkout.php">
<input id="input" type="submit" name="check" value="Checkout" style="background-color:gray; width:200px; margin-right: 10px;">
</div>
</div>
<?php include("footer.php") ?>
</body>
</html>
checkout.php:
<?php
//starting the session
session_start();
$from = "techologyy#gmail.com"; //from
$feedback = "Purchase details";
$to = "techologyy#gmail.com";//direction
$email = "Email from: $from \r\n";
mail("techologyy#gmail.com", $feedback, $from);
header("Location: index.php"); //returns the user back to homepage
echo "
<script>
alert('The checkout has been done successfully! Thank you')
</script>
";
?>
It looks to me like your mail() call is incorrect
The order of the parameters should be: to address, subject, email body and then sender. The sender should be in the format From: sender#email.com
So, adjust your code to something like this:
$from = "techologyy#gmail.com"; //from
$feedback = "Purchase details";
$to = "techologyy#gmail.com";//direction
$email = "Email from: $from \r\n";
mail($to, $feedback, $email, "From: $from");

Dynamic Accordion Repetitive Code

I have built a navigation page in an accordion format using mysqli and php. You can see an example at
[1]: http://www.outerhebridesalgae.uk/marine/marine-taxononic-list.php/ "Marine Algae".
This works perfectly well, but the coding is very repetitive as I am repeating the same code for each heading in the accordion. This is fine for a limited number of headings, but some of my tables have 30 or more headings! Is there a more efficient approach? Thank you for your assistance.
A sample of the code follows:
<?phprequire '../assets/includes/conn.inc.php';
$query1 = mysqli_query($connect, "SELECT * FROM marine WHERE famid='1' ORDER BY marine.species");
$row1 = mysqli_fetch_assoc($query1);
$totalRows_query1 = mysqli_num_rows($query1);
$query2 = mysqli_query($connect, "SELECT * FROM marine WHERE famid='2' ORDER BY marine.species");
$row2= mysqli_fetch_assoc($query2);
$totalRows_query2 = mysqli_num_rows($query2);
$query4 = mysqli_query($connect, "SELECT * FROM marine WHERE famid='4' ORDER BY marine.species");
$row4= mysqli_fetch_assoc($query4);
$totalRows_query4 = mysqli_num_rows($query4);
?>
<!DOCTYPE html>
<head>.......</head>
<body>
<div class="uk-panel uk-panel-box uk-margin">
<h2 class="uk-panel-title">Chlorophyta - Green Seaweeds</h2>
<div id="firstpane" class="msg_list">
<p class="msg_head"> <?php echo $row1['family']; ?><img src="../images/arrow.jpg" alt="arrow open" align="right"></p>
<div class="msg_body">
<table width="100%" >
<?php do { ?>
<tr>
<td id="marine.species"><?php echo $row1['species']; ?></td>
<?php } while ($row1 = mysqli_fetch_assoc($query1)); ?>
</tr>
</table>
</div>
<p class="msg_head"><?php echo $row2['family']; ?><img src="../images/arrow.jpg" alt="arrow open" align="right"></p>
<div class="msg_body">
<table width="100%" >
<?php do { ?>
<tr>
<td id="marine.species"><?php echo $row2['species']; ?></td>
<?php } while ($row2 = mysqli_fetch_assoc($query2)); ?>
</tr>
</table>
</div>
<p class="msg_head"><?php echo $row4['family']; ?><img src="../images/arrow.jpg" alt="arrow open" align="right"></p>
<div class="msg_body">
<table width="100%" >
<?php do { ?>
<tr>
<td id="marine.species"><?php echo $row4['species']; ?></td>
<?php } while ($row4 = mysqli_fetch_assoc($query4)); ?>
</tr>
</table>
</div></body></html>

Why Redirect Function is not refreshing the page correctly?

I am trying to redirect the page back to general_faq_category route but when it is redirected the data is not loaded correctly. So i manually refresh the page and then the data is loaded correctly (sorted). Why is the page not refreshing automatically? It should load the data sorted but it isn't loading when the below func is executed, however after manually refreshing the route the changes appear.
The following is the code i used for redirecting
Function for sorting data:
function executeFaqCategoryOrder(sfWebRequest $request) {
$faqid = $request->getParameter('faqid');
$direction = $request->getParameter('direction');
if ($faqid & $direction) {
$c = new Criteria();
$c->add(FaqCategoryPeer::ID, $faqid);
$current_faq = FaqCategoryPeer::doSelectOne($c);
$current_order = $current_faq->getOrder();
switch ($direction) {
case 'UP':
$c = new Criteria();
$c->add(FaqCategoryPeer::ORDER, $current_order - 1);
$previous_faq = FaqCategoryPeer::doSelectOne($c);
$current_faq->setOrder($previous_faq->getOrder());
$current_faq->save();
$previous_faq->setOrder($current_order);
$previous_faq->save();
$this->redirect($this->generateUrl('general_faq_category'));
break;
break;
case 'DOWN':
$c = new Criteria();
$c->add(FaqCategoryPeer::ORDER, $current_order + 1);
$next_faq = FaqCategoryPeer::doSelectOne($c);
$current_faq->setOrder($next_faq->getOrder());
$current_faq->save();
$next_faq->setOrder($current_order);
$next_faq->save();
$this->redirect($this->generateUrl('general_faq_category'));
break;
break;
default:
$this->redirect($this->generateUrl('general_faq_category'));
break;
}
$this->redirect($this->generateUrl('general_faq_category'));
}
}
Another Func from actions.php
public function preExecute() {
self::$formName = "FaqCategoryAdminForm";
self::$modelPeer = "FaqCategoryPeer";
self::$model = "FaqCategory";
$this->redirectUrl = 'faq_category/index';
}
View Code:
<div class="pagead">
<div class="pagein"align="center">
<div align="center">
<h3>FAQ Category (Total: <?php echo $total ?>)</h3>
<span style="float: right;">
Back |
New FAQ Category
</span>
</div>
<br/>
<div align="center"><?php $pager->render() ?></div>
<table width="100%" id="category">
<tr>
<th width="30%">Name</th>
<th width="15%">Created At</th>
<th width="5%">Order</th>
<th width="12%">Action</th>
</tr>
<?php foreach ($pager->getResults() as $row): ?>
<tr id="category_<?php echo $row['id'] ?>" class="categories">
<td align="center"><?php echo $row['name']; ?></td>
<td align="center"><?php echo date(sfConfig::get('app_display_alternate_format_for_date'), strtotime($row['created_at'])); ?></td>
<td>
▲
▼
</td>
<td align="center">
<?php echo link_to(image_tag("/images/edit.png", array("title" => "Click to modify category")), $sf_params->get('module') . '/edit?id=' . $row['id']); ?>
<?php echo link_to(image_tag("/images/cross.png", array("title" => "Click to delete category")), $sf_params->get('module') . '/delete?id=' . $row['id'], array('confirm' => 'All related records will be deleted, are you sure ?')); ?>
</td>
</tr>
<?php endforeach; ?>
</table>
</div>
<br/>
<br/>
</div>
<div class="bot"></div>

Delete image(s) associated with record from folder

I have a page that allows for multiple record deletes using checkboxes and all works fine.
However, each record may have an image associated with it stored in a folder that would also need to be deleted but I have no idea how to achieve this even though I've searched Stackoverflow and Google.
How do I delete the record(s) from the MySQL database and the image(s) associated with it from the folder?
What I have so far is:
The code that deletes the records:
if ( isset( $_POST[ 'chk_id' ] ) ) {
$arr = $_POST[ 'chk_id' ];
foreach ( $arr as $id ) {
#mysqli_query( $KCC, "DELETE FROM pageContent WHERE contentID = " . $id );
}
$msg = "Page(s) Successfully Deleted!";
header( "Location: delete-familyservices.php?msg=$msg" );
}
The form that selects the records to delete:
<form name="deleteRecord" id="deleteRecord" method="post" action="delete-familyservices.php">
<?php if (isset($_GET['msg'])) { ?>
<p class="alert alert-success">
<?php echo $_GET['msg']; ?>
</p>
<?php } ?>
<table width="100%" class="table table-striped table-bordered table-responsive">
<tr>
<th>Page Title</th>
<th>Page Text</th>
<th>Page Image</th>
<th>Delete</th>
</tr>
<?php do { ?>
<tr>
<td width="30%" style="vertical-align: middle">
<h4 style="text-align: left">
<?php echo $row_rsContent['contentTitle']; ?>
</h4>
</td>
<td width="45%" style="vertical-align: middle">
<?php echo limit_words($row_rsContent['contentData'], 10); ?> ...</td>
<td align="center" style="vertical-align: middle">
<?php if (($row_rsContent['contentImage']) != null) { ?>
<img src="../images/<?php echo $row_rsContent['contentImage']; ?>" class="img-responsive">
<?php } else { ?> No Image
<?php } ?>
</td>
<td width="5%" align="center" style="vertical-align: middle"><input type="checkbox" name="chk_id" id="chk_id" class="checkbox" value="<?php echo $row_rsContent['contentID']; ?>">
</td>
</tr>
<?php } while ($row_rsContent = mysqli_fetch_assoc($rsContent)); ?>
</table>
<p> </p>
<div class="form-group" style="text-align: center">
<button type="submit" name="submit" id="submit" class="btn btn-success btn-lg butt">Delete Selected Page(s)</button>
<button class="btn btn-danger btn-lg butt" type="reset">Cancel Deletion(s)</button>
</div>
</form>
The final piece of code, which is a confirmation script:
<script type="text/javascript">
$( document ).ready( function () {
$( '#deleteRecord' ).submit( function ( e ) {
if ( !confirm( "Delete the Selected Page(s)?\nThis cannot be undone." ) ) {
e.preventDefault();
}
} );
} );
</script>
I've seen the unlink() function mentioned but I don't know if this is what to use or have any idea how to incorporate it into the existing code if it is.
you'll have to use the path of the image which is stored on you database like so :
unlink(' the link of the images which is fetched from db'); // correct
don't forget to check for image existence file_exists() //
Got this from another site and a bit of trial and error.
if($_POST) {
$arr = isset($_POST['chk_id']) ? $_POST['chk_id'] : false;
if (is_array($arr)) {
$filter = implode(',', $arr);
$query = "SELECT *filename* FROM *table* WHERE *uniqueField* IN ({$filter})";
$result = mysqli_query(*$con*, $query);
while ($row = mysqli_fetch_object($result)) {
$pathToImages = "*path/to/images*";
{
unlink("{$pathToImages}/{$row->contentImage}");
}
}
// DELETE CAN BE DONE IN ONE STATEMENT
$query = "DELETE FROM *table* WHERE *uniqueField* IN ({$filter})";
mysqli_query(*$con*, $query);
$msg = "Page(s) Successfully Deleted!";
header("Location: *your-page.php*?msg=$msg");
}
}
Thanks to everyone who contributed.
Hope this is of some help to others.

Categories