For loop variable, confused about single and double quotes - php

I'd like to make the following code a for loop to make everything read better, but I can't seem to get the quotes right and end up with a blank page
if ($_POST['week'])
{
$week = $_POST['week'];
}
//or check for a value submitted by the week menu
elseif ($_POST["user_week1"] == "week1") {
$week = "1";
}
elseif ($_POST["user_week2"] == "week2") {
$week = "2";
}
else if ($_POST["user_week3"] == "week3") {
$week = "3";
}
else if ($_POST["user_week4"] == "week4") {
$week = "4";
}
else if ($_POST["user_week5"] == "week5") {
$week = "5";
}
else if ($_POST["user_week6"] == "week6") {
$week = "6";
}
else {
$week = "1";
}
I tried to do:
if ($_POST['week'])
{
$week = $_POST['week'];
}
for ($i = 1; $i<7; $i++)
{
else if ($_POST["user_week'.$i.'"] == "week'.$i.'") {
$week = $i;
}
}
else {
$week = "1";
}
But that didn't work out too well, I tried using double quotes instead of single around the variables, plus '" and "' to no avail.
Can anyone help with this, or point me towards a good resource on single and double quotes for variables?

Are you all igrnoring the fact that the else if mustn`t be there!?
What you should do is the following
$week = "1";
if ($_POST['week']) {
$week = $_POST['week'];
} else {
for ($i = 1; $i < 7; $i++) {
if ($_POST["user_week" . $i] == "week" . $i) {
$week = $i;
break;
}
}
}

elseif ($_POST['user_week' . $i] == 'week' . $i)
above correction should work

Related

Joining a string with input fields = one value

how can I get this result as a value of LUC-1701-000005 field I made ..
I get the current value from one field ($value = $_POST['wpuef_options']['c26'];), but I want to make it easier for customers to not enter those LUCs ... than just numbers..
current code looks like this ..
for($I=0; $I<= 5; $I++){
if($I == 0){
$value = $_POST['wpuef_options']['c26'];
}
else if($I == 1){
$value = $_POST['wpuef_options']['c30'];
}
else if($I == 2){
$value = $_POST['wpuef_options']['c34'];
}
else if($I == 3){
$value = $_POST['wpuef_options']['c44'];
}
else if($I == 4){
$value = $_POST['wpuef_options']['c50'];
}
this is something I need ..but this is not correct ..
$value = "LUC-" + $_POST['wpuef_options']['c26'] + "-" + $_POST['wpuef_options']['c23'];
Try this:
$value = "LUC-" . $_POST['wpuef_options']['c26'] . "-" . $_POST['wpuef_options']['c23'];
You are using + for concatenation, which is wrong, in PHP it is just . .

i want to sum all digit in a number

i want to add all digit in a number and if it is 11,22 then i want to display only 11 or 22 else i want to make it a single digit.
example 30=3+0=3
28=2+8=10=1+0=1
i just made a codebut it have an error
please help.
<?php
$day = 17;
$month = 8;
$year = 1993;
function sumday($day)
{
if ($day == 11)
{
$sday = 11;
}
elseif ($day == 22)
{
$sday = 22;
}
elseif ($day == 29)
{
$sday = 11;
}
else
{
do {
$nday = $day . "";
$sday = 0;
for ($i = 0; $i < strlen($nday); ++$i)
{
$sday += $nday[$i];
}
while ($sday <=9);
}
return $sday;
}
First of all I would suggest you to learn to separate the tasks that a function do.
You ask to sum up the digits of a number, you may first create a function called sum_digits
<?php
function sum_digits($num) {
if ($num < 10)
return $num;
return $num % 10 + sum_digits(floor($num/10));
}
and then via conditional do whatever you need to do.
please refer to unnikked's answer, that's a good answer.
And here's the full code, combined with unnikked's answer
<?php
$day = 17;
$month = 8;
$year = 1993;
function sumday($day)
{
if ($day == 11)
{
$sday = 11;
}
elseif ($day == 22)
{
$sday = 22;
}
elseif ($day == 29)
{
$sday = 11;
}
else{
$sday = $day;
do {
$sday = $sday % 10 + floor($sday/10);
} while ($sday >= 10);
}
return $sday;
}
?>
EDIT: If you want to return the sum if it's 11,22,33 in the while loop, then put the conditions in the while loop rather than using if else condition, it's much simpler tho :)
function sumday($day)
{
$sday = $day;
while ($sday >= 10 && $sday != 11 && $sday != 22 && $sday != 29){
$sday = $sday % 10 + floor($sday/10);
}
return $sday;
}
EDIT: here's the logic that can split the day and sum them
function sumday($day)
{
$sday = $day;
$arrday = str_split($sday); // split the day into array
$sumarrday = 0;
for($i = 0; $i < strlen((string)$sday); $i++){
$sumarrday = $sumarrday + $arrday[$i]; // sum the day from the array
}
$sday = $sumarrday;
// here you can modify the condition of while statement for your needs
// for example, if you want to return 29 when 29 shows up, add this to your condition, && $sday != 29
while ($sday >= 10){
$sday = $sday % 10 + floor($sday/10);
}
return $sday;
}
Try this:
else {
$nday = $day . ""; //moved out wrom loop
do {
$sday = 0;
for ($i = 0; $i < strlen($nday); ++$i)
{
$sday += $nday[$i];
}
$nday = $sday . ""; // you forget this line
while ($sday <=9);
}

automatic number increase in php based web form [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
So I have created an html form which then posts the results to a php file that overlays them on a PDF and then emails that PDF to myself and the email that was put in the form. All I want to do now is find a simple way to make it so that the PDF includes a sequential number.
For example: When the form is filled out for the first time the number 0001 is input automatically into the PDF and 0002 for the second time and so on.
Is there an easy PHP function to accomplish this?
Essentially I am creating an online invoicing form so when I do service calls I can create an invoice on the spot from a web browser which is then emailed to my office and the client.
Any help would be greatly appreciated.
For an incrementing number, you could keep a number in a database and then extract it, add 1 to it, use it, and then put it back in the DB for next time, but this seems complicated. Somebody in the comments mentioned using the timestamp, which would be done like so:
$invoicenumber = time(); //This number will always be unique
The time function works like so (copied from w3schools):
The time() function returns the current time in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).
Since actual seconds can only go up (increment), this number will never be the same twice.
I hope this is helpful.
-Edit
You can also display this date/time in a readable format like so:
$time = time();
echo date("Y-m-d H:i:s",$time);
-Edit 2
If you want an incrementing number, you basically need a very simple database to save it, which might be as simple as a table called invoices, with a column called invoicenumber, which stores your invoice number in it. You could / probably should use this to store other invoice information in it too, so you'd have each invoice number saved (which means we want to only get the highest one)
Then your code would look like this, for each time you want to use it:
Firstly you'd have a database information file (settings.php or something similar) with your database definitions in it, which might look like this:
define('DB_HOST', 'localhost');
define('DB_USER', 'db_username');
define('DB_PASS', 'db_password');
define('DB_NAME', 'database_name');
Your code would look like this:
//Establish a mysql connection
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
//Set up a query to get the highest number
$query = "SELECT invoicenumber FROM invoices ORDER BY invoicenumber DESC LIMIT 1";
//Get the result
$result = $mysqli->query($query);
$row = $result->fetch_assoc();
//If we have a record
if($row){
//New invoice number
$invoicenumber = $row['invoicenumber']++;
//Else (database is empty, so start at the beginning)
}else{
$invoicenumber = 1;
}
//Now we have our invoice number, so do whatever you want with it
/**
* Code here to use the number
* */
//Now we wanna add the new invoice to the database, so
/**
* Add any other info to this statement if you want.
* If any of it is user submitted data, be sure to use prepared statements
* (just look at php.net's documentation on prepared statements)
* w3schools also has some nice tutorials on how to safely insert stuff
* in to a database, so check it all out :)
* */
$query = "INSERT INTO invoices(invoicenumber) VALUES($invoicenumber)";
//Execute the query
if($mysqli->query($query)){
//Show success
echo "Invoice $invoicenumber has been added to the database.";
}else{
//Show error
echo "Unfortunately we could not add invoice $invoicenumber to the database.";
}
//Now we can clear up our resources
$stmt->free_result(); $stmt->close(); $mysqli->close();
Please note: this is a very basic example. Yours will have additions and enhanced security if you are using user submitted data, so please do your homework and make sure that you fully understand each line of this code before you proceed to use it.
I do exactly the same with patient accession numbers on patient reports.
include('/home/user/php/class.pdf2text.php');
$p2t = new PDF2Text();
$p2t->setFilename($pdf);
$p2t->decodePDF();
$data = $p2t->output();
$len = strlen($data);
$pos = strpos($data,$accession);
if (pos){
$in .= "$accession,";
$checked++;
}
else{
$missingPDF += 1;echo "\n<p> <span class='bold red'>INCORRECT ACCESSION NUMBER c=$row[0] p=$row[1]</span>\n";
}
if ($checked > 0){
$in = substr($in,0,-1) . ')';
$sql = "UPDATE `Patient` SET `PDF`=1 WHERE $in";
}
pdf2text.php
class PDF2Text {
// Some settings
var $multibyte = 4; // Use setUnicode(TRUE|FALSE)
var $convertquotes = ENT_QUOTES; // ENT_COMPAT (double-quotes), ENT_QUOTES (Both), ENT_NOQUOTES (None)
var $showprogress = true; // TRUE if you have problems with time-out
// Variables
var $filename = '';
var $decodedtext = '';
function setFilename($filename) {
// Reset
$this->decodedtext = '';
$this->filename = $filename;
}
function output($echo = false) {
if($echo) echo $this->decodedtext;
else return $this->decodedtext;
}
function setUnicode($input) {
// 4 for unicode. But 2 should work in most cases just fine
if($input == true) $this->multibyte = 4;
else $this->multibyte = 2;
}
function decodePDF() {
// Read the data from pdf file
$infile = #file_get_contents($this->filename, FILE_BINARY);
if (empty($infile))
return "";
// Get all text data.
$transformations = array();
$texts = array();
// Get the list of all objects.
preg_match_all("#obj[\n|\r](.*)endobj[\n|\r]#ismU", $infile . "endobj\r", $objects);
$objects = #$objects[1];
// Select objects with streams.
for ($i = 0; $i < count($objects); $i++) {
$currentObject = $objects[$i];
// Prevent time-out
#set_time_limit ();
if($this->showprogress) {
// echo ". ";
flush(); ob_flush();
}
// Check if an object includes data stream.
if (preg_match("#stream[\n|\r](.*)endstream[\n|\r]#ismU", $currentObject . "endstream\r", $stream )) {
$stream = ltrim($stream[1]);
// Check object parameters and look for text data.
$options = $this->getObjectOptions($currentObject);
if (!(empty($options["Length1"]) && empty($options["Type"]) && empty($options["Subtype"])) )
// if ( $options["Image"] && $options["Subtype"] )
// if (!(empty($options["Length1"]) && empty($options["Subtype"])) )
continue;
// Hack, length doesnt always seem to be correct
unset($options["Length"]);
// So, we have text data. Decode it.
$data = $this->getDecodedStream($stream, $options);
if (strlen($data)) {
if (preg_match_all("#BT[\n|\r](.*)ET[\n|\r]#ismU", $data . "ET\r", $textContainers)) {
$textContainers = #$textContainers[1];
$this->getDirtyTexts($texts, $textContainers);
} else
$this->getCharTransformations($transformations, $data);
}
}
}
// Analyze text blocks taking into account character transformations and return results.
$this->decodedtext = $this->getTextUsingTransformations($texts, $transformations);
}
function decodeAsciiHex($input) {
$output = "";
$isOdd = true;
$isComment = false;
for($i = 0, $codeHigh = -1; $i < strlen($input) && $input[$i] != '>'; $i++) {
$c = $input[$i];
if($isComment) {
if ($c == '\r' || $c == '\n')
$isComment = false;
continue;
}
switch($c) {
case '\0': case '\t': case '\r': case '\f': case '\n': case ' ': break;
case '%':
$isComment = true;
break;
default:
$code = hexdec($c);
if($code === 0 && $c != '0')
return "";
if($isOdd)
$codeHigh = $code;
else
$output .= chr($codeHigh * 16 + $code);
$isOdd = !$isOdd;
break;
}
}
if($input[$i] != '>')
return "";
if($isOdd)
$output .= chr($codeHigh * 16);
return $output;
}
function decodeAscii85($input) {
$output = "";
$isComment = false;
$ords = array();
for($i = 0, $state = 0; $i < strlen($input) && $input[$i] != '~'; $i++) {
$c = $input[$i];
if($isComment) {
if ($c == '\r' || $c == '\n')
$isComment = false;
continue;
}
if ($c == '\0' || $c == '\t' || $c == '\r' || $c == '\f' || $c == '\n' || $c == ' ')
continue;
if ($c == '%') {
$isComment = true;
continue;
}
if ($c == 'z' && $state === 0) {
$output .= str_repeat(chr(0), 4);
continue;
}
if ($c < '!' || $c > 'u')
return "";
$code = ord($input[$i]) & 0xff;
$ords[$state++] = $code - ord('!');
if ($state == 5) {
$state = 0;
for ($sum = 0, $j = 0; $j < 5; $j++)
$sum = $sum * 85 + $ords[$j];
for ($j = 3; $j >= 0; $j--)
$output .= chr($sum >> ($j * 8));
}
}
if ($state === 1)
return "";
elseif ($state > 1) {
for ($i = 0, $sum = 0; $i < $state; $i++)
$sum += ($ords[$i] + ($i == $state - 1)) * pow(85, 4 - $i);
for ($i = 0; $i < $state - 1; $i++) {
try {
if(false == ($o = chr($sum >> ((3 - $i) * 8)))) {
throw new Exception('Error');
}
$output .= $o;
} catch (Exception $e) { /*Dont do anything*/ }
}
}
return $output;
}
function decodeFlate($data) {
return #gzuncompress($data);
}
function getObjectOptions($object) {
$options = array();
if (preg_match("#<<(.*)>>#ismU", $object, $options)) {
$options = explode("/", $options[1]);
#array_shift($options);
$o = array();
for ($j = 0; $j < #count($options); $j++) {
$options[$j] = preg_replace("#\s+#", " ", trim($options[$j]));
if (strpos($options[$j], " ") !== false) {
$parts = explode(" ", $options[$j]);
$o[$parts[0]] = $parts[1];
} else
$o[$options[$j]] = true;
}
$options = $o;
unset($o);
}
return $options;
}
function getDecodedStream($stream, $options) {
$data = "";
if (empty($options["Filter"]))
$data = $stream;
else {
$length = !empty($options["Length"]) ? $options["Length"] : strlen($stream);
$_stream = substr($stream, 0, $length);
foreach ($options as $key => $value) {
if ($key == "ASCIIHexDecode")
$_stream = $this->decodeAsciiHex($_stream);
elseif ($key == "ASCII85Decode")
$_stream = $this->decodeAscii85($_stream);
elseif ($key == "FlateDecode")
$_stream = $this->decodeFlate($_stream);
elseif ($key == "Crypt") { // TO DO
}
}
$data = $_stream;
}
return $data;
}
function getDirtyTexts(&$texts, $textContainers) {
for ($j = 0; $j < count($textContainers); $j++) {
if (preg_match_all("#\[(.*)\]\s*TJ[\n|\r]#ismU", $textContainers[$j], $parts))
$texts = array_merge($texts, array(#implode('', $parts[1])));
elseif (preg_match_all("#T[d|w|m|f]\s*(\(.*\))\s*Tj[\n|\r]#ismU", $textContainers[$j], $parts))
$texts = array_merge($texts, array(#implode('', $parts[1])));
elseif (preg_match_all("#T[d|w|m|f]\s*(\[.*\])\s*Tj[\n|\r]#ismU", $textContainers[$j], $parts))
$texts = array_merge($texts, array(#implode('', $parts[1])));
}
}
function getCharTransformations(&$transformations, $stream) {
preg_match_all("#([0-9]+)\s+beginbfchar(.*)endbfchar#ismU", $stream, $chars, PREG_SET_ORDER);
preg_match_all("#([0-9]+)\s+beginbfrange(.*)endbfrange#ismU", $stream, $ranges, PREG_SET_ORDER);
for ($j = 0; $j < count($chars); $j++) {
$count = $chars[$j][1];
$current = explode("\n", trim($chars[$j][2]));
for ($k = 0; $k < $count && $k < count($current); $k++) {
if (preg_match("#<([0-9a-f]{2,4})>\s+<([0-9a-f]{4,512})>#is", trim($current[$k]), $map))
$transformations[str_pad($map[1], 4, "0")] = $map[2];
}
}
for ($j = 0; $j < count($ranges); $j++) {
$count = $ranges[$j][1];
$current = explode("\n", trim($ranges[$j][2]));
for ($k = 0; $k < $count && $k < count($current); $k++) {
if (preg_match("#<([0-9a-f]{4})>\s+<([0-9a-f]{4})>\s+<([0-9a-f]{4})>#is", trim($current[$k]), $map)) {
$from = hexdec($map[1]);
$to = hexdec($map[2]);
$_from = hexdec($map[3]);
for ($m = $from, $n = 0; $m <= $to; $m++, $n++)
$transformations[sprintf("%04X", $m)] = sprintf("%04X", $_from + $n);
} elseif (preg_match("#<([0-9a-f]{4})>\s+<([0-9a-f]{4})>\s+\[(.*)\]#ismU", trim($current[$k]), $map)) {
$from = hexdec($map[1]);
$to = hexdec($map[2]);
$parts = preg_split("#\s+#", trim($map[3]));
for ($m = $from, $n = 0; $m <= $to && $n < count($parts); $m++, $n++)
$transformations[sprintf("%04X", $m)] = sprintf("%04X", hexdec($parts[$n]));
}
}
}
}
function getTextUsingTransformations($texts, $transformations) {
$document = "";
for ($i = 0; $i < count($texts); $i++) {
$isHex = false;
$isPlain = false;
$hex = "";
$plain = "";
for ($j = 0; $j < strlen($texts[$i]); $j++) {
$c = $texts[$i][$j];
switch($c) {
case "<":
$hex = "";
$isHex = true;
$isPlain = false;
break;
case ">":
$hexs = str_split($hex, $this->multibyte); // 2 or 4 (UTF8 or ISO)
for ($k = 0; $k < count($hexs); $k++) {
$chex = str_pad($hexs[$k], 4, "0"); // Add tailing zero
if (isset($transformations[$chex]))
$chex = $transformations[$chex];
$document .= html_entity_decode("&#x".$chex.";");
}
$isHex = false;
break;
case "(":
$plain = "";
$isPlain = true;
$isHex = false;
break;
case ")":
$document .= $plain;
$isPlain = false;
break;
case "\\":
$c2 = $texts[$i][$j + 1];
if (in_array($c2, array("\\", "(", ")"))) $plain .= $c2;
elseif ($c2 == "n") $plain .= '\n';
elseif ($c2 == "r") $plain .= '\r';
elseif ($c2 == "t") $plain .= '\t';
elseif ($c2 == "b") $plain .= '\b';
elseif ($c2 == "f") $plain .= '\f';
elseif ($c2 >= '0' && $c2 <= '9') {
$oct = preg_replace("#[^0-9]#", "", substr($texts[$i], $j + 1, 3));
$j += strlen($oct) - 1;
$plain .= html_entity_decode("&#".octdec($oct).";", $this->convertquotes);
}
$j++;
break;
default:
if ($isHex)
$hex .= $c;
elseif ($isPlain)
$plain .= $c;
break;
}
}
$document .= "\n";
}
return $document;
}
}

Change variable inside function foreach loop

I've a problem that i can't solve. I think it's an easy fix, but after 3 hours of searching and trail-error. I've decided to ask the question over here:
This is my time function for a schedule application.
date_default_timezone_set('Europe/Amsterdam');
$current_time = time();
$unixtime = $current_time;
$time = date("Gi",$unixtime);
global $time;
function time_left($time, $active_class, $maxtime, $mintime){
if($time < $maxtime and $time > $mintime){
global $active_class;
$active_class = 'active';
echo 'succes!';
}
}
Here is my foreach loop, i loop through an array
foreach($rows as $row){
switch($hours){
case 1:
$t = '8:45 - 9:15';
$mintime = 845;
$maxtime = 914;
time_left($time, $maxtime, $mintime);
break;
case 2:
$t = '8:45 - 9:15';
$mintime = 845;
$maxtime = 914;
time_left($time, $maxtime, $mintime);
break;
/* etc.. etc.. etc... */
}
echo "<li class='" . $active_class ."'>";
echo "<div class='right'></div>";
echo "<div class='hour'>", $times, "</div><span class='divider-time'>|</span>";
$hours++;
$i = 0;
foreach($row[$day] as $r[1]){
$i++;
if ($i == 1) {
$class = 'vk';
} elseif ($i == 2) {
$class = 'lok';
} elseif ($i == 3) {
$class = 'doc';
}
echo "<span class='" . $class . "'>", $r[1], "</span>";
}
echo "</li>";
$class++;
}
I get the 'succes!' echo on the right location. But the active class is not working properly. The idea behind it is that the active class is only shown on one row. Now it searches for a match and everything behind it also gets the active class.
Thanks in advanced.
You should restart the $active_class variable in every iteration.
Otherwise, once it is set to active it won't change its value again.
foreach($rows as $row){
$active_class = '';
//YOUR CODE HERE
....
}

PHP echo only 1 higher or 1 lower then current hour

So I'm having this issue where I want to echo only the things that are 1 higher or 1 lower then the current hour. Example if current hour = 14 only echo 13, 14 and 15
Anyone have a clue on how I can do this?
<?php
mysql_connect("*******", "******", "**");
if(!mysql_select_db("deb67423_dj")) {
die("<b>Mislukt!</b><br>Het verbinden met de database is mislukt.");
}
$textweek = date("D");
if($textweek == "Mon") {
$dag = 0;
} else
if($textweek == "Tue") {
$dag = 1;
} else
if($textweek == "Wed") {
$dag = 2;
} else
if($textweek == "Thu") {
$dag = 3;
} else
if($textweek == "Fri") {
$dag = 4;
} else
if($textweek == "Sat") {
$dag = 5;
} else
if($textweek == "Sun") {
$dag = 6;
}
$textuur = date("G");
$SQL = "SELECT * FROM rooster WHERE dag = '$dag'";
$result = mysql_query($SQL);
echo "<table>";
while ($row = mysql_fetch_assoc($result)) {
echo "<td> Hiervoor: DJ ".$row['gebruikersnaam']. "</td>";
}
echo "</table>";
$currHour = date('G');
echo $currHour - 1, ', ', $currHour, ', ', $currHour + 1;
Take note that $currHour can be 0 and you will have to take care of this "special" case... But I think this snippet will get you started. See the PHP date() documentation for more help.

Categories