PHP Fatal error break; - php

I am using a wordpress plugin that fetches stock quote feed from Yahoo finance. IT JUST HAPPENS VERY RARELY... OTHERWISE IT DON'T SHOW UP. I randomly get fatal error saying on line 140 ... and line 140 is break; i am copying below quote to understand the code. EDIT: NOW I HAVE PUT THE ENTIRE PHP FILE...!!
<?php
/*
Plugin Name: Stock Quotes
Plugin URI: http://www.dagondesign.com/articles/stock-quotes-plugin-for-wordpress/
Description: Displays stock quotes on your website
Author: Dagon Design
Version: 1.0.1
Author URI: http://www.dagondesign.com
*/
$ddsq_version = '1.0.1';
// Setup defaults if options do not exist
add_option('ddsq_format', '%NAME%: %LAST% ( %CHANGE% )');
add_option('ddsq_up_color', '00BB00');
add_option('ddsq_down_color', 'FF0000');
add_option('ddsq_update_time', '10');
function ddsq_add_option_pages() {
if (function_exists('add_options_page')) {
add_options_page('Stock Quotes', 'DDStockQuotes', 8, FILE, 'ddsq_options_page');
}
}
function ddsq_options_page() {
global $ddsq_version;
if (isset($_POST['set_defaults'])) {
echo '<div id="message" class="updated fade"><p><strong>';
update_option('ddsq_format', '<strong>%NAME%</strong> %LAST% [<strong>%CHANGE%</strong>]');
update_option('ddsq_up_color', '00BB00');
update_option('ddsq_down_color', 'FF0000');
update_option('ddsq_update_time', '10');
echo 'Default Options Loaded!';
echo '</strong></p></div>';
} else if (isset($_POST['info_update'])) {
update_option('ddsq_format', (string) $_POST["ddsq_format"]);
update_option('ddsq_up_color', (string) $_POST["ddsq_up_color"]);
update_option('ddsq_down_color', (string) $_POST["ddsq_down_color"]);
update_option('ddsq_update_time', $_POST["ddsq_update_time"]);
echo 'Configuration Updated!';
echo '</strong></p></div>';
} ?>
<div class=wrap>
<h2>Stock Quotes v<?php echo $ddsq_version; ?></h2>
<p>For information and updates, please visit:<br />
http://www.dagondesign.com/articles/stock-quotes-plugin-for-wordpress/</p>
<form method="post" action="<?php echo $_SERVER["REQUEST_URI"]; ?>">
<input type="hidden" name="info_update" id="info_update" value="true" />
<h3>Usage</h3>
<p>There are two ways you can display quotes:</p>
<p><strong>1) In a post or page</strong>
<br />
[stock MSFT]</p>
<p><strong>2) In a template file</strong>
<br />
<?php echo ddsq_get_quote('MSFT'); ?></p>
<h3>Options</h3>
<table width="100%" border="0" cellspacing="6" cellpadding="4">
<tr valign="top"><td width="13%">
<strong>Output Format </strong>
</td><td align="left">
<input name="ddsq_format" type="text" size="100" value="<?php echo htmlspecialchars(stripslashes(get_option('ddsq_format'))) ?>"/>
<br />Placeholders for data: <strong>%NAME% %LAST% %CHANGE%</strong>
</td></tr>
<tr valign="top"><td width="13%">
<strong>Up Color </strong>
</td><td align="left">
<input name="ddsq_up_color" type="text" size="7" value="<?php echo get_option('ddsq_up_color') ?>"/>
Color to use for price change when up (leave blank to disable)
</td></tr>
<tr valign="top"><td width="13%">
<strong>Down Color </strong>
</td><td align="left">
<input name="ddsq_down_color" type="text" size="7" value="<?php echo get_option('ddsq_down_color') ?>"/>
Color to use for price change when down (leave blank to disable)
</td></tr>
<tr valign="top"><td width="13%">
<strong>Update Time </strong>
</td><td align="left">
<input name="ddsq_update_time" type="text" size="3" value="<?php echo get_option('ddsq_update_time') ?>"/>
Number of minutes to wait, before fetching updated stock prices
</td></tr>
</table>
<div class="submit">
<input type="submit" name="set_defaults" value="<?php _e('Load Default Options'); ?> »" />
<input type="submit" name="info_update" value="<?php _e('Update options'); ?> »" />
</div>
</form>
</div><?php
}
function ddsq_get_quote($symb) {
$up_color = trim(get_option('ddsq_up_color'));
$down_color = trim(get_option('ddsq_down_color'));
$quote_format = stripslashes(get_option('ddsq_format'));
$update_time = trim(get_option('ddsq_update_time'));
$update_time = $update_time * 60;
$t_out = '';
$time_diff = '';
// Trying to open local cached file first
$file_path = WP_PLUGIN_DIR . "/" . $symb . ".txt";
if (file_exists($file_path)){
$time_diff = date('U') - filemtime($file_path);
}
$lf = #fopen($file_path, "r");
if (($lf == FALSE) || ($time_diff >= $update_time)) {
$url = "http://finance.yahoo.com/d/quotes.csv?s=" . $symb . "&f=sl1c1";
$fp = #fopen($url, "r");
if ($fp == FALSE) {
#$t_out = 'Error opening: ' . htmlspecialchars($url);
break;
} else {
$array = #fgetcsv($fp , 4096 , ', ');
#fclose($fp);
$sq_name = $array[0];
$sq_last = $array[1];
$sq_change = $array[2];
$col = NULL;
if (($sq_change[0] == '-') && ($down_color != '')) {
$col = $down_color;
} else if (($sq_change[0] == '+') && ($up_color != '')) {
$col = $up_color;
}
if ($col !== NULL) {
$sq_change = '<span style="color: #' . $col . ';">' . $sq_change . '</span>';
}
$t_out = $quote_format;
$t_out = str_replace('%NAME%', $sq_name, $t_out);
$t_out = str_replace('%LAST%', $sq_last, $t_out);
$t_out = str_replace('%CHANGE%', $sq_change, $t_out);
$cache_file = fopen($file_path, "w+");
fwrite($cache_file, $t_out);
}
} else {
fclose($lf);
$t_out = file_get_contents($file_path);
if ($t_out == FALSE){
echo "ERROR opening cache file";
}
}
return $t_out;
}
function ddsq_process($content) {
$results = array();
preg_match_all("/\[\s?stock\s?(.*)\s?\]/", $content, $results);
$i = 0;
foreach ($results[0] as $r) {
$content = str_replace($r, ddsq_get_quote($results[1][$i]), $content);
$i++;
}
return $content;
}
add_filter('the_content', 'ddsq_process');
add_action('admin_menu', 'ddsq_add_option_pages');
?>

As far as I can see there is no loop or control structure (like switch), that accepts break; within itself. I guess, that you sometimes call this code within a loop. In this case break; is allowed. But sometimes it's not. At all break; doesn't make any sense within an if-block.

I´m not sure if a file-pointer can evaluate to false, but when checking fopen for errors, you need to use:
if ($fp === FALSE)
Apart from that, take a look at #mhitza's comment.

Related

How to make an entry in a text box required when one specific radio button is selected?

I have several radio buttons which can be chosen and then the form can be sent without an issue. However a user can easily select the "Other" radio button and submit without giving any context or reason on why they chose it leaving the people receiving the "completed" form guessing what the issue is.
What I want to happen is that if a person selects the "Other" radio button and try and submit without a note/message/comment they will be interrupted with a requirement massage.
The snippet of the form that I want this to happen to is:
<label>
<input name="category" type="radio" value="Other" checked>Other
</label><br><br><br>
Note: <br> <textarea name="comment" rows="10" cols="70" placeholder="More detail... (Is there a way to recreate the error? What happened?)"></textarea>
<br><br>
<input type="submit" name="submit" value="Submit" class="userFriendly">
I have tried many variations of if statements and the required function given with HTML5 but can not seem to get what I need.
Any help will be appreciated and thanks in advance.
Edit 1:
Here is the full code of my form:
<form action="send_form_email.php?OperationID=<?php print ($OperationID) ?>&title=<?php print ($title) ?>" method="post" onsubmit="return this.users.value != ''">
<table>
<tr>
<td>Name:</td>
<td>
<select required name="users">
<option value=""></option>
<?php
foreach($users as $key => $value){
echo "<option value=\"$key\">$key</option>";
}
?>
</select>
</td>
</tr>
<tr>
<td <?php print $hiddenJobDiv ?>>Job Number:</td>
<td><input type="text" name="jobid" value="<?php echo ($jobid) ?>" <?php echo $disabledInput ?>></td>
</tr>
<tr>
<td <?php print $hiddenPartDiv ?>>Part Number:</td>
<td><input type="text" name="partid" value="<?php echo ($part_id) ?>" <?php echo $disabledInput ?>></td>
</tr>
<?php if ($OperationID == 20){ ?>
<tr>
<td>Machine:</td>
<td><input type="text" name="mach" value="<?php echo ($machCode) ?>" <?php echo $disabledInput ?>></td>
<tr>
<?php } ?>
</table><br>
Error:<br><br><br> <!-- Display of dynamic list. -->
<?php
$html = customErr($OperationID);
foreach ($html as $oneError):?> <!-- foreach used to find the next iteration of the array. -->
<label> <!-- Beginning of the dynamic radio button list. -->
<input name="category"
type="radio"
value="<?php echo $oneError; ?>"> <!-- Dynamic value to be used in Slack API and email. -->
<?php echo $oneError; ?> <!-- Dynamic value as a visual representation for user. -->
</label><br><br><br>
<?endforeach;?> <!-- Stops foreach and goes to next object if avaliable. -->
<label> <!-- A permanent radio button labeled "Other" for (cont.) -->
<input name="category" type="radio" value="Other" checked>Other <!-- all report error forms. -->
</label><br><br><br>
<?php
if (isset($_POST['category'])=="Other" && isset($_POST["comment"])=="")
{
$required[] = ("You must write a note if you choose \'other\'.");
}
return $required;
?>
Note: <?php echo $required ?> <br> <textarea name="comment" rows="10" cols="70"
placeholder="More detail... (Is there a way to recreate the error? What happened?)"></textarea> <!-- Allows the user to type in a custom message/note. -->
<br><br>
<input type="submit" name="submit" value="Submit" class="userFriendly"> <!-- A large 'submit' button for touch screen. -->
<input type="submit" name="close" value="Close" class="userFriendly"> <!-- A large 'close' button for touch screens. -->
</form>
Edit 2:
Here is the full code:
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" type="text/css" href="/css/main_style.css">
<style>
.error {color: #FF0000;}
table, th, td {border: 1px solid white;}
</style>
</head>
<body>
<script>
function close_window() {
close();
}
</script>
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
include("includes/classes.php");
include("includes/classes_monitoring.php");
$link = open_v8_db();
$users = get_clocked_in_users();
$OperationID = #$_REQUEST['OperationID'];
$title = "";
$grayedOut = false;
$disabledInput = "";
$hiddenJobDiv = "";
$hiddenPartDiv = "";
$ID = "";
$html = "";
$jobid = #$_REQUEST['JobID'];
$part_id = #$_REQUEST['PartID'];
$machCode = #$_REQUEST['Machine'];
if ($OperationID == 20)
{
$title = "Punching Machine";
$grayedOut = true;
}
elseif ($OperationID == 30)
{
$title = "Folding Machine";
$grayedOut = true;
}
elseif ($OperationID == 40 || $OperationID == 140)
{
$title = "Powder Coating";
$grayedOut = true;
}
elseif ($OperationID == 50 || $OperationID == 150)
{
$title = "Assembly";
$grayedOut = true;
}
elseif ($OperationID == 60 || $OperationID == 160)
{
$title = "Inspection";
$grayedOut = true;
}
elseif ($jobid != "" && $part_id == "")
{
$title = "Job";
$OperationID = 70;
}
else
{
$title = "General";
$OperationID = 80;
$grayedOut = false;
}
if ($greyedOut = true)
{
$disabledInput = "readonly";
}
function customErr($ID)
{
$html = "";
$issueReport_folder = 'document/Production System/';
$issueReporting = $issueReport_folder.'IssueReporting.csv';
$file_handle = fopen($issueReporting, "r");
if ($ID == 20)
{
while (!feof($file_handle))
{
$line_of_text = fgetcsv($file_handle, 1024);
if ($line_of_text[2] == "Punch")
{
$html[] = $line_of_text[1];
}
}
}
if ($ID == 30)
{
while (!feof($file_handle))
{
$line_of_text = fgetcsv($file_handle, 1024);
if ($line_of_text[2] == "Fold")
{
$html[] = $line_of_text[1];
}
}
}
if ($ID == 40 || $ID == 140)
{
while (!feof($file_handle))
{
$line_of_text = fgetcsv($file_handle, 1024);
if ($line_of_text[2] == "Powder")
{
$html[] = $line_of_text[1];
}
}
}
if ($ID == 50 || $ID == 150)
{
while (!feof($file_handle))
{
$line_of_text = fgetcsv($file_handle, 1024);
if ($line_of_text[2] == "Assembly")
{
$html[] = $line_of_text[1];
}
}
}
if ($ID == 60 || $ID == 160)
{
while (!feof($file_handle))
{
$line_of_text = fgetcsv($file_handle, 1024);
if ($line_of_text[2] == "Inspectoin")
{
$html[] = $line_of_text[1];
}
}
}
if ($ID == 70)
{
while (!feof($file_handle))
{
$line_of_text = fgetcsv($file_handle, 1024);
if ($line_of_text[2] == "Job")
{
$html[] = $line_of_text[1];
}
}
}
if ($ID == 80)
{
while (!feof($file_handle))
{
$line_of_text = fgetcsv($file_handle, 1024);
if ($line_of_text[2] == "General")
{
$html[] = $line_of_text[1];
}
}
}
fclose($file_handle);
return $html;
}
$jobErr = $partErr = $machErr = "";
$job = $part = $mach = $note = "";
if ($jobid == "")
{
$hiddenJobDiv = "style=\"display:none;";
}
if ($part_id == "")
{
$hiddenPartDiv = "style=\"display:none;";
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div class="reportForm">
<h2>Report <u><?php echo $title; ?></u> Error</h2>
<form action="send_form_email.php?OperationID=<?php print ($OperationID) ?>&title=<?php print ($title) ?>" method="post" onsubmit="return this.users.value != ''">
<table>
<tr>
<td>Name:</td>
<td>
<select required name="users">
<option value=""></option>
<?php
foreach($users as $key => $value){
echo "<option value=\"$key\">$key</option>";
}
?>
</select>
</td>
</tr>
<tr>
<td <?php print $hiddenJobDiv ?>>Job Number:</td>
<td><input type="text" name="jobid" value="<?php echo ($jobid) ?>" <?php echo $disabledInput ?>></td>
</tr>
<tr>
<td <?php print $hiddenPartDiv ?>>Part Number:</td>
<td><input type="text" name="partid" value="<?php echo ($part_id) ?>" <?php echo $disabledInput ?>></td>
</tr>
<?php if ($OperationID == 20){ ?>
<tr>
<td>Machine:</td>
<td><input type="text" name="mach" value="<?php echo ($machCode) ?>" <?php echo $disabledInput ?>></td>
<tr>
<?php } ?>
</table><br>
Error:<br><br><br> <!-- Display of dynamic list. -->
<?php
$html = customErr($OperationID);
foreach ($html as $oneError):?> <!-- foreach used to find the next iteration of the array. -->
<label> <!-- Beginning of the dynamic radio button list. -->
<input name="category"
type="radio"
value="<?php echo $oneError; ?>"> <!-- Dynamic value to be used in Slack API and email. -->
<?php echo $oneError; ?> <!-- Dynamic value as a visual representation for user. -->
</label><br><br><br>
<?endforeach;?> <!-- Stops foreach and goes to next object if avaliable. -->
<label> <!-- A permanent radio button labeled "Other" for (cont.) -->
<input name="category" type="radio" value="Other" checked>Other <!-- all report error forms. -->
</label><br><br><br>
<?php
if (isset($_POST['category'])=="Other" && isset($_POST["comment"])=="")
{
$required[] = ("You must write a note if you choose \'other\'.");
}
return $required;
?>
Note: <?php echo $required ?> <br> <textarea name="comment" rows="10" cols="70"
placeholder="More detail... (Is there a way to recreate the error? What happened?)"></textarea> <!-- Allows the user to type in a custom message/note. -->
<br><br>
<input type="submit" name="submit" value="Submit" class="userFriendly"> <!-- A large 'submit' button for touch screen. -->
<input type="submit" name="close" value="Close" class="userFriendly"> <!-- A large 'close' button for touch screens. -->
</form> <!-- End of form. -->
</div>
</body>
</html>
you can't use required method like that. I think your solution is add dynamically textbox when user clicked the option button like that:
Add this javascript function in your file:
<script language="javascript">
function activateNote()
{
var i = 1;
note_div.innerHTML = "Note: <br> <textarea required id='comment' name='comment' rows='10' cols='70' placeholder='More detail... (Is there a way to recreate the error? What happened?)' ></textarea><br><br>"
}
</script>
Change your elements like that, "delete note textarea" than add div element:
<label>
<input onClick="activateNote()" type="radio" name="category" value="Other">Other
</label>
<div id="note_div"></div>
One possible solution is to conditionally add the required HTML5 attribute to the required field when the "Other" radio button is selected.
You can do this with a javascript method attached to your radio button that is (de/)activated on select.

Can't set variable in generated php code

I have a php script that generates 3 files:
A .txt file
A .php file
The Script works fine but one thing destroys the idyll, the script does not write the vars in the 2nd generated script (I have also tried . $var . ). Any help would be appreciated.
The Code:
<?php
$filename = uniqid(rand(), true) . '.php';
$fh = fopen($filename, "w+");
if($fh)
{
fwrite($fh, "<html><body>
<div align='center'>
Neue Nachricht erstellen<br><br>
<form action='' . $filenamebes . '' Method='post'>
Titel:<br>
<input name='Name' size='40'><br><br>
Inhalt:<br>
<textarea name='inhalt' cols='40' rows='12'
wrap='physical'></textarea><p>
<input type='submit' value='Absenden'>
</form><br><br>
<?php
$beitrag = file('' . $filenametxt . '');
krsort($beitrag);
foreach($beitrag as $ausgabe)
{
$ausgabe = stripslashes($ausgabe);
$zerlegen = explode('|', $ausgabe);
echo '
<table align=\'center\'
border=\'1\' cellspacing=\'0\'
cellpadding=\'5\' bordercolorlight=\'black\'
bordercolordark=\'black\' width=\'50%\'>
<tr>
<td>
Titel: <a href=\'mailto:$zerlegen[0]\'>$zerlegen[1]</a>
am $zerlegen[2]
</td>
</tr>
<tr>
<td>
$zerlegen[3]
</td>
</tr>
</table><br>
';
}
?>
</div>
</body>
</html>
");
}
fclose($fh);
$filenametxt = uniqid(rand(), true) . '.txt';
$fhtxt = fopen($filenametxt, "w+");
if($fhtxt)
{
fwrite($fhtxt, "");
}
fclose($fhtxt);
$filenamebes = uniqid(rand(), true) . '.php';
$fhbes = fopen($filenamebes, "w+");
if($fhbes)
{
fwrite($fhbes, "<html>
<head>
<title>Speichere Nachricht</title>
</head>
<body>
<?php
$user = {$_POST['Name']};
$user = htmlentities($user);
$inhalt = {$_POST['inhalt']};
$inhalt = htmlentities($inhalt);
$inhalt = str_replace('\n', '<br>', $inhalt);
$email = {$_POST['EMail']};
$email = htmlentities($email);
if ($inhalt == '' or $user == '')
{
echo 'Sie müssen das Feld \'Namen\'
und \'Inhalt\' ausfüllen';
}
else
{
$datum= date('d.m.Y H:i:s');
$eintrag='$email|$user|$datum|$inhalt';
$datei = fopen('' . $filenametxt . '', 'a');
fwrite($datei, '\n'.$eintrag);
fclose($datei);
echo 'Ihre Nachricht wurde erfolgreich gespeichert';
}
?>
<br>
<a href='' . $filename . ''>Zurück</a>
</body>
</html>");
}
fclose($fhbes);
echo "PHP = $filename TXT = $filenametxt BES = $filenamebes <br><br><a href='".$filename."'>ÖffnenPHP</a> <br><br><a href='".$filenametxt."'>ÖffnenTXT</a> <br><br><a href='".$filenamebes."'>ÖffnenBES</a>"
?>
You are using Super string format to build your string.
Super string means double quotes "".
here
fwrite($fh, "<html><body>
and you use php variables in the super string format. So php identify the variable as a string or whatever it contains
Ex :
$a="ABCD";
echo "$a"; // this will print ABCD
but when you do it this way
$a="ABCD";
echo '$a';// this will print $a
Here is the solution
fwrite($fh, '<html><body>
<div align="center">
Neue Nachricht erstellen<br><br>
<form action=" . $filenamebes . " Method="post">
Titel:<br>
<input name="Name" size="40"><br><br>
Inhalt:<br>
<textarea name="inhalt" cols="40" rows="12"
wrap="physical"></textarea><p>
<input type="submit" value="Absenden">
</form><br><br>
<?php
$beitrag = file(" . $filenametxt . ");
krsort($beitrag);
foreach($beitrag as $ausgabe)
{
$ausgabe = stripslashes($ausgabe);
$zerlegen = explode("|", $ausgabe);
echo "
<table align=\"center\"
border=\"1\" cellspacing=\"0\"
cellpadding=\"5\" bordercolorlight=\"black\"
bordercolordark=\"black\" width=\"50%\">
<tr>
<td>
Titel: $zerlegen[1]
am $zerlegen[2]
</td>
</tr>
<tr>
<td>
$zerlegen[3]
</td>
</tr>
</table><br>
";
}
?>
</div>
</body>
</html>
');
PHP is treating those terms "$filenamebes" "$zerlegen" as actual variables.
Because those variables don't exist, it will not write anything to the file.
Instead you should escape those variables like so: \$filenamebes. This will allow you to physically write $filenamebes to the file, and not have PHP search for its value (null).
Proof of concept:
<?php
$a = 'test';
$s = "\$a";
echo $s ."\n"; //will print '$a'
echo "---\n";
$s = "$a";
echo $s ."\n"; //will print 'test'

PHP Update shows previous database entry's

I'm currently just coding around in my free time and follow up some random tutorials that other developers/coder's created in there spare time. Now I'm stuck with something very small. I have been trying to find a answer on the interwebz but I cant seem to find one, so here I'm hoping that someone is willing to read my PHP and HTML and see the error I created.
But before I share my code let me tell you what my problem is and what I try to achieve.
If you go to the following link "removed because problem is solved." and when you click on Home/About/Service/Random, you are able to edit one of these menu's. (title, posistion, visible). Now when I want to change the menu name "Home" to "Welcome" it correctly execute my SQL but for some reason, in the HTML Form it loads it's previous information. What I can do is copy the PHP and save it in a new php file and when clicking on submit it will change both menu/title/html form at the same time, but it wont show my succes and fail message anymore. I hope any of you understand what I'm trying to explain here and try to achieve. Now lets share the code.
PHP
<? find_selected_page(); ?>
<?
if (intval($_GET['info']) == 0){
redirect_to("content.php");
}
if(isset($_POST['submit'])){
$errors = array();
$required_fields = array('menu', 'position', 'visible');
foreach ($required_fields as $fieldname){
if (!isset($POST[$fieldname]) || (empty($_POST[$fieldname]) &&
!is_numeric($_POST[$fieldname]))) {
$errors [] = $fieldname;
}
}
$fields_with_lengths = array('menu' => 30);
foreach($fields_with_lengths as $fieldname => $maxlength) {
if(strlen(trim(mysql_prep($_POST[$fieldname]))) > $maxlength){
$errors[] = $fieldname;
}
}
$id = mysql_prep($_GET['info']);
$menu = mysql_prep($_POST['menu']); //use post array cuz we used post var to coll val in form
$position = mysql_prep($_POST['position']);
$visible = mysql_prep($_POST['visible']);
$query = "UPDATE information SET menu = '{$menu}', position = {$position}, visible = {$visible} WHERE id = {$id}";
$result = mysql_query($query, $connection);
if (mysql_affected_rows() == 1) {
$message = "The information was correctly updated.";
} else {
//failed
}
} else { //errors
}
?>
HTML
<? require_once ("includes/functions.php"); ?>
<? require_once ("includes/connect.php"); ?> //HERE IS MY CONNECTION TO MY DATABASE
///HERE IS MY PHP CODE
<? include ("includes/header.php"); ?>
<div id="content"> <!-- content here -->
<table id="table">
<tr>
<td id="nav">
<? echo navigation($sel_table1, $table2); ?>
</td>
<td id="main">
<h2>Edit Info <? echo $sel_table1['menu']; ?></h2>
<? if (!empty($message)) { echo "<p class=\"message\">" . $message . "</p>";} ?>
<form action="edit_info.php?info=<? echo urlencode($sel_table1['id']); ?>" method="post"/>
<p>Menu title
<input type="text" name="menu" value="<? echo ($sel_table1['menu']); ?>" id="menu">
</p>
<p>Position
<select name="position">
<?
$info_set = get_all_info();
$info_count = mysql_num_rows($info_set); //asks how many rows there are should be 3
for($count=1; $count <= $info_count+1; $count++){
echo "<option value='{$count}'";
if($sel_table1['position'] == $count){
echo "selected";
}
echo ">{$count}</option>";
}
?>
</select>
</p>
<p>Visible:
<input type="radio" name="visible" value="0"
<? if ($sel_table1['visible'] == 0){ echo "checked"; } ?>
/>No
<input type="radio" name="visible" value="1"
<? if ($sel_table1['visible'] == 1){ echo "checked"; } ?>
/>Yes
</p>
<input type="submit" name='submit' value="Edit information" />
</form> <br>
Cancel
</td>
</tr>
</table>
</div>
<? include ("includes/footer.php");?> //HERE I HAVE IF ISSET MYSQL CLOSE
And a more simple short version of the story is, I want to update the menu's with the success and failure message's without getting the old previous data in my HTML FORM
if needed for any reasons I have included the part of my functions.php where $sel_table and $table2 are staying.
function find_selected_page(){
global $sel_table1;
global $table2;
if (isset($_GET['info'])){
$sel_table1 = get_info_by_id($_GET['info']);
$sel_t2 = 0;
$table2 = NULL;
} else if (isset($_GET['page'])){
$table1 = 0;
$sel_table1 = NULL;
$table2 = get_pages_by_id($_GET['page']);
} else {
$table1 = NULL;
$sel_table1 = NULL;
$table2 = 0;
}
}
function navigation($sel_table1, $table2){
$output = "<ul class='info'>";
$info_set = get_all_info();
while ($info = mysql_fetch_array($info_set))
{
$output .= "<li"; if ($info["id"] == $sel_table1 ["id"]){
$output .= " class='selected'";
}
$output .= "><a href='edit_info.php?info=" . urlencode($info["id"]) . "'>{$info['menu']}</a></li>";
$page_set = get_pages_for_info($info["id"]);
$output .= "<ul class='pages'>";
while ($page = mysql_fetch_array($page_set))
{
$output .= "<li"; if ($page["id"] == $table2 ["id"]){
$output .= " class='selected'";
}
$output .= "><a href='content.php?page=" . urlencode($page["id"]) . "'>{$page['menu']}</a></li>"; }
$output .= "</ul>";
}
$output .= "</ul>";
return $output;
}

Update Textbox value which are in loop using Post Submit (Codeigniter)

i have 2 textbox in loop
and i want to update their value in database when i press button.
the issue is that when i press button it updates only last textbox value .
following is my model.
function approvedHrs($taskid,$data)
{
//$this->db->where('id', $id);
$this->db->where('taskid', $taskid);
$this->db->update(MILESTONE, $data);
}
Following is my View (For lop is here)
<?php
foreach ($result as $milestone_row) {
?>
<tr id="<?php echo $milestone_row->id; ?>">
<?php
if ($is_master_admin) {
if ($i > 1) {
if ($milestone_row->userid == $userid) {
} else {
$userid = $milestone_row->userid;
echo $milestone_row->usertitle;
}
} else {
$userid = $milestone_row->userid;
echo $milestone_row->usertitle;
}
}
?>
<li class="in">
Add Bug
<div class="message">
<span class="arrow"></span>
<span class="body">
<?php
echo '<b> <U> Task Title </U>:- </b> &nbsp';
echo $milestone_row->tasktitle;
echo '<br/>';
echo '<b> <U> Workspace Title </U>:- </b> &nbsp';
echo $milestone_row->workspacetitle;
echo '<br/>';
echo '<b> <U> Description </U>:- </b> &nbsp';
echo $milestone_row->description;
echo '<br/>';
echo '<b> <U> Hours </U>:- </b> &nbsp';
echo $milestone_row->esthours;
echo 'hrs';
echo '<br/>';
echo '<b> <U> Minutes </U>:- </b> &nbsp';
echo $milestone_row->estmin;
echo'mins';
echo '<br/>';
?>
<b><u>Approved Hours:-</u></b>
<input style="height:14px;font-size:10pt; width: 33px" type="text" id="hours" name="approvedhrs" data-required="1" value="<?php echo $milestone_row->esthours; ?>" placeholder="Hours" onkeypress="return isNumberKey(event)" />
<input style="height:14px;font-size:10pt; width: 33px" type="text" id="minutes" name="approvedmins" value="<?php echo $milestone_row->estmin; ?>" data-required="1" placeholder="Minutes" onkeypress="return isNumberKey(event)" />
Edit
<?php echo " | ";?>
Delete
<!--<span class="datetime">at <?php //echo $milestone_row->createddate; ?></span> -->
</span>
</div>
</li>
Followinf is myController
function approvedHrs($taskid)
{
if ($this->session->userdata('logged_in')){
$session_data = $this->session->userdata('logged_in');
$id = $session_data['id'];
$username = $session_data['username'];
$is_master_admin = $session_data['master'];
$imagethumb = $session_data['imagethumb'];
$pendingbug = $this->bugmodel->getBug($id, $is_master_admin);
$pendingtask = $this->taskmodel->getTask($id, $is_master_admin);
$data = '';
$data = array(
'approvedhrs' =>$this->input->post('approvedhrs'),
'approvedmins'=>$this->input->post('approvedmins')
);
// print_r($data);
// exit;
$result = $this->milestonemodel->approvedHrs($taskid,$data);
// $this->session->set_userdata('msg', $result);
redirect('task', 'refresh');
}
else
{
redirect('login', 'refresh');
}
}
When i use array like this it gives me following error
PHP Error Occured :Message: Array to string conversion
Database Error : Unknown column 'Array' in 'field list'
UPDATE milestone SET approvedhrs = Array, approvedmins = Array WHERE taskid = '17'
You should simplify your code like this
$post = $this->input->post();
$data['approvedhrs'] = $post['approvedhrs'];
$data['approvedmins'] = $post['approvedmins'];
print_r($data);
$result = $this->milestonemodel->approvedHrs($taskid,$data);
You should make sure $post['approvedhrs'] and $post['approvedmins'] do not have arrays. They could contain array when defined in the form like this
<input type='text' name="approvedhrs[]" />
<input type='text' name="approvedmins[]" />
EDIT
As you are making inputs inside loops there fore both approvedhrs and approvedmins are posted as array. Which is causing problem in updating.
EDIT
You should make the inputs in your loop like this
<input type='text' name="approvedhrs[]" />
<input type='text' name="approvedmins[]" />
Make hidden inputs for row id and task id
<input type='hidden' name="rowid[]" />
<input type='hidden' name="taskid[]" />
<input type='text' name="approvedhrs[]" />
<input type='text' name="approvedmins[]" />
And now php
$post = $this->input->post();
$data['approvedhrs'] = $post['approvedhrs'];
$data['approvedmins'] = $post['approvedmins'];
for($i=0;$i<count($data['approvedhrs']);$i++){
$update_data['approvedhrs'] = $data['approvedhrs'][$i];
$update_data['approvedmins'] = $data['approvedmins'][$i];
$taskid = $data['taskid'][$i];
print_r($update_data);
$result = $this->milestonemodel->approvedHrs($taskid,$update_data);
unset($update_data);
unset($taskid);
}
As you are passing array of data to update, you can use update_batch mentod.
In your controller, prepare the data as below.
$k= 0 ;
$data = array();
$aphrs = $this->input->post('approvedhrs'); // returns array
$apmis = $this->input->post('approvedmins'); //
foreach($aphrs as $hrs)
{
$data[] = array(
'approvedhrs' =>$hrs,
'approvedmins'=>$apmis[$k]
);
$k++;
}
// call your model function
$result = $this->milestonemodel->approvedHrs($taskid,$data);
In your model function: add update_batch method. So no need to call update method in forloop.
for update_batch, check this tutorial.
http://ellislab.com/codeigniter/user-guide/database/active_record.html#update
View
<input type='hidden' name="milestoneid[]" value ="<?php echo $milestone_row->id ?>" />
<input type="text" id="hours" name="approvedhrs[<?php echo $milestone_row->id ?>][]" value="<?php echo $milestone_row->esthours; ?>"/>
<input type="text" name="approvedmins[<?php echo $milestone_row->id ?>][]" value="<?php echo $milestone_row->estmin; ?>"/>
Controller
function approvedHrs($taskid) {
if ($this->session->userdata('logged_in')) {
$session_data = $this->session->userdata('logged_in');
$id = $session_data['id'];
$username = $session_data['username'];
$is_master_admin = $session_data['master'];
$imagethumb = $session_data['imagethumb'];
$pendingbug = $this->bugmodel->getBug($id, $is_master_admin);
$pendingtask = $this->taskmodel->getTask($id, $is_master_admin);
$data = array();
$milestoneIDs = $this->input->post('milestoneid');
$approvedhrs = $this->input->post('approvedhrs');
$approvedmins = $this->input->post('approvedmins');
foreach ($milestoneIDs as $milestoneID) {
$data = array(
'approvedhrs' => isset($approvedhrs[$milestoneID]) ? $approvedhrs[$milestoneID] : '',
'approvedmins' => isset($approvedmins[$milestoneID]) ? $approvedmins[$milestoneID] : '',
);
$this->milestone_model->approvedHrs($milestoneID,$data);//change this model name as per you use
unset($data);
}
redirect('task', 'refresh');
} else {
redirect('login', 'refresh');
}
}
Model
function approvedHrs($milestoteid, $data) {
//$this->db->where('id', $editid);
$this->db->where('milestoteid', $milestoteid);
$this->db->update(MILESTONE, $data);
}

PHP image upload in admin section only allowing client to upload 19 images

I've been working on a client's admin panel (A photography company uploading images to a client's gallery), when I took on the role as web developer, it only allowed him to upload 30 images, even though there was 100 file upload boxes. This was fixed simply by changing the for loop to run 100 times. This fixed this problem.
But recently, without even touching the code, my client can only upload 19 images.. I haven't changed this form, he has previously uploaded 40+ images, so I don't quite understand what could have happened.. I've checked the code over and over, and can't quite seem to pinpoint the issue. Could this be server side, as I've recently moved from his old developer's host to my hostgator account. Maybe something in the htaccess? I add this because the image label's update, but not the image itself (I can't find it uploaded either, after it has been posted, but my browser shows it uploading)
Here is the edit gallery code itself, if it gives any assistance to the problem:
<?php
require_once("../conn.php");
require_once("access.php");
require_once("GalleryNavigation.php");
require_once("dThumbMaker.inc.php");
/////////////common varilable
$__table = "devbg_gallery";
$__page = $_SERVER['PHP_SELF'];
$__page2 = "AddGallery.php";
$__id = "ItemID";
$__pagetitle = "GALLERY";
$__uploadfolder = "../myimages/";
$__thumbuploadfolder = "../myimages/thumbs/";
$__imageprefix = "Gallery";
$Thumb_Imgwidth = 200;
$Thumb_Imgheight = 77;
/////////////
if(isset($_POST[ds]))
{
if(count($_POST['DelItem']) > '0')
{
while(list(, $value) = each($_POST['DelItem']))
{
$DelInfo = $value;
$r2 = mysql_query("select * from ".$__table." where ".$__id." = '$DelInfo' ") or die(mysql_error());
$a2 = mysql_fetch_array($r2);
for($i=1;$i<=100;$i++)
{
if(file_exists($__uploadfolder.$a2['ItemImage'.$i]))
{
unlink($__uploadfolder.$a2['ItemImage'.$i]);
unlink($__thumbuploadfolder.$a2['ItemImage'.$i]);
}
}
//delete the product
mysql_query("delete from ".$__table." where ".$__id." = '".$DelInfo."' ") or die(mysql_error());
}
}
}
if(isset($_POST[s100]))
{
$MyProductName = mysql_escape_string(trim(stripslashes(strip_tags($_POST[ProductName]))));
$Description = mysql_escape_string(trim(strip_tags(stripslashes($_POST['Description']))));
$Link = trim(strip_tags(stripslashes($_POST['Link'])));
$TopLabel = cleaninput($_POST['TopLabel'],"mres|he|tr");
$status = $_POST['status'];
$NewTopLabelName = $TopLabel;
if(!empty($_FILES['TopImage']['name']))
{
$NewTopImageName = $__imageprefix.$t.$_FILES['TopImage']['name'];
if(is_uploaded_file($_FILES['TopImage']['tmp_name']))
{
move_uploaded_file($_FILES['TopImage']['tmp_name'], $__uploadfolder.$NewTopImageName);
$NewTopImageName = $NewTopImageName;
$NewTopLabelName = $TopLabel;
//lets make the thumb
$tm = new dThumbMaker;
$load = $tm->loadFile($__uploadfolder.$NewTopImageName);
if($load === true)
{ // Note three '='
$tm->cropCenter($Thumb_Imgwidth, $Thumb_Imgheight);
$tm->build($__thumbuploadfolder.$NewTopImageName);
}
else
{
// Error returned.
$error .= "Could not open the file '".$NewTopImageName."'.\n";
$error .= "The error returned was: ";
$error .= $load;
}
}
}
else
{
$NewTopImageName = $_POST['OldTopImage'];
$NewTopLabelName = $NewTopLabelName;
}
for($i=1;$i<=100;$i++) //This is where I believe the problem is --------------------------------------------------------------------
{
${'NewsItemLabel'.$i} = cleaninput($_POST['ItemLabel'.$i],"mres|he|tr");
$ItemLabels .= "ItemLabel".$i ." = '". cleaninput($_POST['ItemLabel'.$i],"mres|he|tr") ."',";
if(!empty($_FILES['ItemImage'.$i]['name']))
{
${'NewImageName'.$i} = $__imageprefix.$t.$_FILES['ItemImage'.$i]['name'];
if(is_uploaded_file($_FILES['ItemImage'.$i]['tmp_name']))
{
move_uploaded_file($_FILES['ItemImage'.$i]['tmp_name'], $__uploadfolder.${'NewImageName'.$i});
//lets make the thumb
$tm = new dThumbMaker;
$load = $tm->loadFile($__uploadfolder.${'NewImageName'.$i});
if($load === true)
{ // Note three '='
$tm->cropCenter($Thumb_Imgwidth, $Thumb_Imgheight);
$tm->build($__thumbuploadfolder.${'NewImageName'.$i});
$ItemImages .= "ItemImage".$i ." = '". ${'NewImageName'.$i} ."',";
}
else
{
// Error returned.
$error .= "Could not open the file '".${'NewImageName'.$i}."'.\n";
$error .= "The error returned was: ";
$error .= $load;
}
} else { }
}
else
{
${'NewImageName'.$i} = $_POST['OldItemImage'.$i];
}
}
if(empty($error))
{
//update the database
$q1 = "update ".$__table." set
ItemName = '".$MyProductName."',
Description = '".$Description."',
Link = '".$Link."',
TopImage = '$NewTopImageName',
Toplabel = '$NewTopLabelName',
".$ItemImages.$ItemLabels."
status = '".$status."'
where ".$__id." = '".$_POST[$__id]."' ";
mysql_query($q1) or die(mysql_error());
echo "<br><br><center>Gallery Updated</center>";
}
}
if(!empty($_GET[$__id]))
{
$_POST[$__id] = $_GET[$__id];
}
if(!empty($_POST[$__id]))
{
//get the product info
$r1 = mysql_query("select * from devbg_gallery where ".$__id." = '".$_POST[$__id]."' ") or die(mysql_error());
$a1 = mysql_fetch_array($r1);
echo $error;
?>
<form method=post action=EditGallery.php enctype="multipart/form-data">
<table align=center width=740>
<caption align=center><b>Gallery Name:</b></caption>
<tr>
<td align='right'>Event Name:</td>
<td><input type=text class=input name="ProductName" value="<?php echo $a1['ItemName'];?>"></td>
</tr>
<TR>
<td align='right'>Description:</td>
<td><textarea name="Description"cols=60 rows=10><?php echo $a1['Description'];?></textarea></td>
</TR>
<?php
if(!empty($a1['TopImage']))
{
$v = $a1['TopImage'];
echo "<tr>";
echo "<td></td><td><img src='".$__uploadfolder.$v."' width='72' border='0'><br><a href='DeleteImage.php?".$__id."=".$a1[$__id]."&Type=gallery&file=".$v."&img=top'>Delete Image</a></td>";
echo "</tr>";
}
?>
<tr>
<td align='right'>Top Image:</td>
<td><input type=file name=TopImage></td>
</tr>
<tr>
<td align='right'>Top Image Label:</td>
<td><input type=text name=TopLabel value="<?php echo $a1['TopLabel'];?>"></td>
</tr>
<?php
for($i = 1; $i <= 100; $i++)
{
if($a1['ItemImage'.$i] != "")
{
echo "<tr>";
echo "<td></td><td><img src='".$__uploadfolder.$a1['ItemImage'.$i]."' width='72' border='0'><br><a href='DeleteImage.php?".$__id."=".$a1[$__id]."&Type=gallery&file=".$a1['ItemImage'.$i]."&id=".$i."'>Delete Image</a></td>";
echo "</tr>";
}
echo "<TR><TD align='right'>Image $i: </TD><TD><input type=file name='ItemImage$i'></TD></TR>\n\t";
echo "<TR><TD align='right'>Label $i: </td><TD><input type=text name='ItemLabel".$i."' value='".cleaninput($a1['ItemLabel'.$i],"ss|hd|tr")."' size='79'></TD></TR>\n\t";
echo "<input type='hidden' name='OldImage$i' value='".$a1['ItemImage'.$i]."'>";
echo "<input type='hidden' name='OldLabel$i' value='".cleaninput($a1['ItemLabel'.$i],"ss|hd|tr")."'>";
}
?>
<tr>
<td></td>
<td>
<input type="hidden" name="OldTopImage" value="<?php echo $a1['TopImage'];?>">
<input type="hidden" name="OldTopLabel" value="<?php echo $a1['TopLabel'];?>">
<input type="hidden" name=<?php echo $__id;?> value="<?php echo $_POST[$__id];?>">
<input type="submit" name="s100" value="Edit Gallery">
</td>
</tr>
</form>
<?php
exit();
}
if(!empty($_GET[Start]))
{
$Start = $_GET[Start];
}
else
{
$Start = '0';
}
$ByPage = "10";
//get the products list
$r1 = mysql_query("select * from devbg_gallery order by ordering_id ASC limit $Start,$ByPage") or die(mysql_error());
if(mysql_num_rows($r1) == '0')
{
echo "<center>You have no items at the database!</center>";
exit();
}
?>
<form method=post>
<table align=center width=500 cellspacing="0" cellpadding="3">
<tr style="background-color:#b5c3ce; color:white; font-family:verdana; font-size:11; font-weight:bold">
<td>Title</td>
<td>User</td>
<td align='center'>Edit</td>
<td align='center'>Delete</td>
</tr>
<?php
$col = "white";
$i=0;
while($a1 = mysql_fetch_array($r1))
{
$r2 = mysql_query("select * from tbl_register where GID = '".$a1['ItemID']."'") or die(mysql_error());
$a2 = mysql_fetch_array($r2);
$name = $a2['firstname'] . " " . $a2['lastname'];
$i++;
if($col == "white" )
{
$col = "#f3f6f8";
}
else
{
$col = "white";
}
echo "<tr bgcolor=$col>
<td>".$a1['ItemName']."</td>
<td>".$name."</td>";
echo "<td align=center><input type=radio name='".$__id."' value='".$a1[$__id]."'></td>
<td align='center'><input type='checkbox' name='DelItem[]' value='".$a1[$__id]."'></td>
</tr>\n\n";
}
echo "<tr>
<td colspan=4 align=right><br>\n\t<input class=input type=submit name=ds value='Edit Selected'> <input type='submit' class='input' name='ds' value='Delete Selected'></td>
</tr>
</table>
</form>\n\n";
//build the "next" - "prev" navigatioin
$qnav = "select * from ".$__table." order by ItemName ";
$rnav = mysql_query($qnav) or die(mysql_error());
$rows = mysql_num_rows($rnav);
echo "<br><table align=center width=600>";
echo "<td align=center><font face=verdana size=2> | ";
$pages = ceil($rows/$ByPage);
for($i = 0; $i <= ($pages); $i++)
{
$PageStart = $ByPage*$i;
$i2 = $i + 1;
if($PageStart == $Start)
{
$links[] = " <span class=bodybold>$i2</span>\n\t ";
}
elseif($PageStart < $rows)
{
$links[] = " <a class=bodybold href=EditGallery.php?Start=$PageStart>$i2</a>\n\t ";
}
}
$links2 = implode(" | ", $links);
echo $links2;
echo "| </td>";
echo "</table><br>\n";
?>
<?php include("footer.php");?>
If there's any other information I could provide that would help find a solution, I can post it straight up. This problem has really messed with my head, and my client needs his gallery running! Makes me wish I could have coded this myself and got there before his previous developer. Thanks everybody!
A friend of mine figured out that when I moved host, my max_file_uploads setting in my php.ini was set to 20, and that the code you see above loops each image and tries to upload it, even if there is no image, which explains why even if I only tried to upload 1 by itself, it wouldn't upload any after 19. Just a simple setting overlooked.
Changed this to max_file_uploads = 100 in my ini, everything works fine now, client happy!

Categories