$street_address = NULL;
$price = NULL;
$number_bedrooms = NULL;
$number_baths = NULL;
$sq_ft = NULL;
$year_built = NULL;
$featured = NULL;
$pImage = NULL;
//create storage for the checkbox values for featured house items.
$pool = 0;
$finished_basement = 0;
$fenced_yard = 0;
if (isset($_POST['submit'])) {//checks to see if the user submit the form.
// print_r ($_POST); // This will show you what array information is being sent to post on the screen
//print_r ($_FILES); //can be used to view the contents of an array
// Gather the home listing data from the POST
if(isset($_POST['pImage'])) {
$pImage = $_POST['pImage'];
}
$street_address = $_POST['street_address'];
$price = $_POST['price'];
$number_bedrooms = $_POST['number_bedrooms'];
$number_baths = $_POST['number_baths'];
$sq_ft = $_POST['sq_ft'];
$year_built = $_POST['year_built'];
$pDesc = $_POST['pDesc'];
if (isset($_POST['featured']) ) { //used to check whether the user selected if the home was selected as featured. If they didn't the item is not passed to the POST.
$featured = $_POST['featured'];
} else {
$featured = NULL;
}
if (isset($_POST['pool']) ) {
$pool = $_POST['pool'];
} else {
$pool = 0;
} // this end bracket is "attached" to the process checking to see if the checkbox was 'ticked'.
//process checked finished basement box.
if (isset($_POST['finished_basement']) ) {
$finished_basement = $_POST['finished_basement'];
} else {
$finished_basement = 0;
} // end of finished_basement checkbox check
//process checked fenced yard box.
if (isset($_POST['fenced_yard']) ) { // Fenced Yard Checkbox Process Check
$fenced_yard = $_POST['fenced_yard'];
} else {
$fenced_yard = 0;
} // end of finished_basement checkbox check
} // end of $_POST submission check (starts on line #40)
// Street Address Validation Check - See if address was entered into the form.
if (empty($street_address)) {
echo "You didn't fill in a streetaddress. <br />";
$output_form = true; // will print form.
} // end of street_address check
// Image , Price & Image validation check
// Price Validation Check - See if Price was entered into the form as a number.
if (!is_numeric($price)) { //is not a number function.
echo "You didn't fill in price as a number.";
$output_form = true; // will print form.
}
// Used to store information for uploading images associative array.
$pImage = $_FILES['pImage']['name']; //array variable. Code pulled from 02fileglobaladd.txt document. $_FILES used to store file information from uploa
$pImage_type = $_FILES['pImage']['type'];
$pImage_size = $_FILES['pImage']['size'];
// Image File Size Validation check -- checks to be sure that the uploaded image is no larger than 1 MB
if (!empty($pImage)) { // empty is for name of file.
if ((($pImage_type == 'image/gif') || ($pImage_type == 'image/jpeg') || ($pImage_type == 'image/pjpeg') || ($pImage_type == 'image/png'))
&& ($pImage_size > 0) && ($pImage_size <= GW_MAXFILESIZE)) { // check to make sure that the file type is valid and that the file is larger than 0 but less than 1meg
if ($_FILES['pImage']['error'] == 0) { // test to be sure file gets uploaded.
$target = GW_UPLOADPATH . $pImage; // try to move file to images folder // FILE UNIQUE time function added from book (page 252) that duplicates and chages file name if there
// is more than one version
if (move_uploaded_file($_FILES['pImage']['tmp_name'], $target)) {
// Connect to the database
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
// Write the data to the database
$query = "INSERT INTO homes ( street_address, price, number_bedrooms, number_baths, sq_ft, year_built, pool, finished_basement, fenced_yard, featured, pDesc, pImage ) " .
"VALUES ('$street_address', '$price', '$number_bedrooms', '$number_baths', '$sq_ft', '$year_built', '$pool', '$finished_basement', '$fenced_yard', '$featured', '$pDesc','$pImage')";
$result = mysqli_query($dbc, $query)
or die('Error querying database.');
/* Testing echos
echo $query;
echo '<br />'
/**/
// Confirmation for the user that will be displayed once the user clicks the submit button (As long as there are no errors with the PHP code)
echo '<p>Thank you for Your Submission. The home has been added to the database.</p>';
echo 'Street Address: ' . $street_address . '<br />';
echo 'Price: ' . $price . '<br />';
echo 'Number of Bedrooms: ' . $number_bedrooms . '<br />';
echo 'Number of Baths: ' . $number_baths . '<br />';
echo 'Square Feet: ' . $sq_ft . '<br />';
echo 'Year Built: ' . $year_built . '<br />';
// featured if statement
echo 'Featured:' ;
if ($featured = 1) {echo ' Yes <br />'; } else {echo ' No <br /> ';}
//example of using ternary format of if/else -- additional items of home (pool, finished basement, fenced in yard ) checkboxes
echo 'Pool: ' . (($pool) ? 'YES' : 'NO' ). '<br />' ;
echo 'Finished Basement: ' . (($finished_basement) ? 'YES' : 'NO' ). '<br />' ;
echo 'Fenced Yard: ' . (($fenced_yard) ? 'YES' : 'NO' ). '<br />' ;
echo 'Desc:<span class="desc"> ' . ($pDesc). '</span><br />';
echo 'Image File: ';
echo '<img src= " ' . GW_UPLOADPATH . $pImage . ' " alt="Homes Image" /></p>';
echo '<p><< Back to Listings Page.</p>';
// Clear the data in the form
$street_address = "";
$price = "";
$number_bedrooms = "";
$number_baths = "";
$sq_ft = "";
$year_built = "";
$pool = "";
$finished_basement = "";
$featured = "";
$pImage = "";
$pDesc ="";
mysqli_close($dbc);
} //movefile worked....
else { //movefile didn't work... error message is printed out
echo '<p class="error">Sorry, there was a problem loading your product image.</p>';
}
}
} // no file type or size error / ENDING BRACKET
else { // there was a file type or size error / ENDING BRACKET
echo '<p class="error">The screen shot must be a GIF, JPEG, or PNG image file no greater than ' . (GW_MAXFILESIZE / 1024) . ' KB in size.</p>';
} // type size error message printed. / ENDING BRACKET
#unlink($_FILES['pImage']['tmp_name']); // unlink is php command to delete the file. Its getting rid of the temporary file. # symbol ignores any error message.
} // data validated
else { // data didn't validate, show error message.
echo '<p class="error">Please enter all the required product information.</p>';
}
?>
I added an if isset command to both the GET & POST statements, can someone help me. I know I have to fix up my code alot after fixing this issue. My professor mentioned about using the print-r statements...
Thank you for any help... I'm a newbie to PHP
The problem lies in this statement:
if(isset($_POST['pImage'])) {
$pImage = $_POST['pImage'];
}
As $_POST['pImage'] is a image, you cannot use $_POST. To check is it's uploaded, simply use:
if($_FILES['pImage']['name') {
This will check for the name of the image, will return true when available.
This statement is wrong:
if ($featured = 1) {echo ' Yes <br />'; } else {echo ' No <br /> ';}
As you are comparing if $featured is equals to 1, you'll need to use PHP's comparison operator ==. = is used for assigning.
Thus, it should be:
if ($featured == 1) {echo ' Yes <br />'; } else {echo ' No <br /> ';}
More information on PHP Operators: http://php.net/manual/en/language.operators.comparison.php.
Also, you shouldn't suppress error messages:
#unlink($_FILES['pImage']['tmp_name']);
Remove # to enable error reporting. It's very useful in diagnosing syntax errors.
Related
The purpose of this code is to identify all the image files from the folder in which the code is being invoked in order to create an image gallery. The images are listed in alphanumeric order but I require a specific order so reordering with a standard PHP array sorting function doesn't meet my needs.
I am using an if statement to place image collections into different arrays then merging the arrays into my required order.
When I run the code as part of my foreach loop it works fine. I want to put the if conditional into a function to reuse the code but I just get a blank page when I copy and paste the code into the function:
// echo statements are just for testing.
foreach(glob(IMAGEPATH."*.{jpg,png,gif,JPG,PNG,GIF}", GLOB_BRACE) as $var03){
$img_src03 = basename($var03);
$img_label03 = pathinfo($var03, PATHINFO_FILENAME);
// Assign specific values to the arrays as you cycle through $img_src03 values:
if (substr($img_src03, 0, 5) == 'ext_f'){
if (!isset($array33)) {
$array33 = array();
}
$array33[] = $img_src03;
echo $img_src03 . ' : Image label = ' . img_label($img_label03) . '<br>';
} elseif (substr($img_src03, 0, 5) == 'ext_r'){
if (!isset($array33)) {
$array33 = array();
}
$array33[] = $img_src03;
echo $img_src03 . ' : Image label = ' . img_label($img_label03) . '<br>';
} elseif (substr($img_src03, 0, 6) == 'ext_po'){
if (!isset($array34)) {
$array34 = array();
}
$array34[] = $img_src03;
echo $img_src03 . ' : Image label = ' . img_label($img_label03) . '<br>';
} elseif (substr($img_src03, 0, 3) == 'bed'){
if (!isset($array35)) {
$array35 = array();
}
$array35[] = $img_src03;
echo $img_src03 . ' : Image label = ' . img_label($img_label03) . '<br>';
} elseif (substr($img_src03, 0, 3) == 'bth'){
if (!isset($array36)) {
$array36 = array();
}
$array36[] = $img_src03;
echo $img_src03 . ' : Image label = ' . img_label($img_label03) . '<br>';
}
}
$arrayFinal = array_merge($array33, $array34, $array35, $array36);
echo 'This is $arrayFinal:<br><pre>'; print_r($arrayFinal); echo '</pre><br>';
When the exact same if conditional is placed inside function findImage03($img_src03, $img_label03), which is located outside the foreach loop, then called from inside the foreach loop the code fails to work.
foreach(glob(IMAGEPATH."*.{jpg,png,gif,JPG,PNG,GIF}", GLOB_BRACE) as $var03){
$img_src03 = basename($var03);
$img_label03 = pathinfo($var03, PATHINFO_FILENAME);
// Trying to use a function call to run the if conditional. Function is outside the foreach loop. Nothing returned.
findImage03($img_src03, $img_label03);
}
function findImage03($img_src03, $img_label03){
// Assign specific values to the arrays as you cycle through $img_src03 values:
if (substr($img_src03, 0, 5) == 'ext_f'){
if (!isset($array33)) {
$array33 = array();
}
$array33[] = $img_src03;
echo $img_src03 . ' : Image label = ' . img_label($img_label03) . '<br>';
} elseif (substr($img_src03, 0, 5) == 'ext_r'){
if (!isset($array33)) {
$array33 = array();
}
$array33[] = $img_src03;
echo $img_src03 . ' : Image label = ' . img_label($img_label03) . '<br>';
} elseif (substr($img_src03, 0, 6) == 'ext_po'){
if (!isset($array34)) {
$array34 = array();
}
$array34[] = $img_src03;
echo $img_src03 . ' : Image label = ' . img_label($img_label03) . '<br>';
} elseif (substr($img_src03, 0, 3) == 'bed'){
if (!isset($array35)) {
$array35 = array();
}
$array35[] = $img_src03;
echo $img_src03 . ' : Image label = ' . img_label($img_label03) . '<br>';
} elseif (substr($img_src03, 0, 3) == 'bth'){
if (!isset($array36)) {
$array36 = array();
}
$array36[] = $img_src03;
echo $img_src03 . ' : Image label = ' . img_label($img_label03) . '<br>';
}
}
$arrayFinal = array_merge($array33, $array34, $array35, $array36);
echo 'This is $arrayFinal:<br><pre>'; print_r($arrayFinal); echo '</pre><br>';
In researching this I think I have found a couple of issues so I'm not sure if this is down to not being a programmer or not.
I found a solution running foreach() in a function() rather than a function() within a foreach(). The new array is then created using the result of the function call.
array_merge() works only if all the arrays being merged hold values otherwise it fails. Not sure if that could be resolved with !isset.
So this is the code running the foreach() in a function() which can be located in an included file for reuse efficiency plus a single source to maintain/update:
// Define the function to get all the images in the current folder:
function getImages(){
foreach(glob(IMAGEPATH."*.{jpg,png,gif,JPG,PNG,GIF}", GLOB_BRACE) as $var){
$img_src = basename($var);
// Assign specific values to the array as you cycle through the collection. Order here will not affect final array order.
if (substr($img_src, 0, 5) == 'bed_1'){
if (!isset($arrayBed_1)) {
$arrayBed_1 = array();
}
$arrayBed_1[] = $img_src;
} elseif (substr($img_src, 0, 5) == 'bed_2'){
if (!isset($arrayBed_2)) {
$arrayBed_2 = array();
}
$arrayBed_2[] = $img_src;
} elseif (substr($img_src, 0, 5) == 'bed_3'){
if (!isset($arrayBed_3)) {
$arrayBed_3 = array();
}
$arrayBed_3[] = $img_src;
// continue for each type required.
} }
} //End of foreach().
// Create the pre final array for other arrays to push to which defines the sort order:
$arrayPreFinal = array();
if (isset($arrayExt_f)){ // ext_f = exterior front
foreach ($arrayExt_f as $val){
array_push($arrayPreFinal, $val);
}
}
if (isset($arrayExt_r)){ // ext_r = exterior rear
foreach ($arrayExt_r as $val){
array_push($arrayPreFinal, $val);
}
}
if (isset($arrayBed_1)){ // bed_1 = bedroom 1
foreach ($arrayBed_1 as $val){
array_push($arrayPreFinal, $val);
}
}
if (isset($arrayBed_2)){ // bed_2 = bedroom 2
foreach ($arrayBed_2 as $val){
array_push($arrayPreFinal, $val);
}
}
// continue for as many variances as require.
return $arrayPreFinal;
} // End of function()
The code run from the folder where the images are located:
// Set $iwd Image Working Directory:
// Required before gallery_ctrl_body.php inlcude as $iwd is needed before include.
// class IWD changes outside the class.
class IWD {
// Properties
public $iwd;
}
$var = new IWD();
$var->name = getcwd();
$iwd = $var->name;
// Script include needs to be run before function pid_text().
include_once ('../gallery_ctrl_body.php');
# Function to identify the property sub-division from directory path characters using preg_match()
# and define a Property ID Text:
function pid_text($sub_div) { //Need parameter/s in function():
$sub_div_abb = sub_div_abb($sub_div); //20200220 code
$psc = 'ORL'; // Start of Property System Code.
$str = getcwd();
if(preg_match("/{$sub_div}/i", $str)) {
$psc = $psc . $sub_div_abb . strtoupper(basename(__DIR__)); //sub_div_abb may already defined in UPPERCASE.
$pid_textname = constant("PROPERTY_TEXT") . $psc; //strtoupper($psc);
}
return $pid_textname; //Return value AFTER IF statement. REQUIRED!
}
$pid_text = pid_text($sub_div = 'test_200828');
// Define the imagepath and variables:
define('IMAGEPATH', dirname(__FILE__).'/'); // '/' is required.
$img_height = 'height: 400px'; // default image height for gallery.
$img_width = 'width: 600px'; // default image width for gallery.
$img_counter = 0;
$img_style = 'style="' . $img_width . '"'; // only needs to be set once here.
$img_total = 0;
// Create the final array with function call to get images:
$arrayFinal = getImages();
// Calculate total number of images before displaying <div>
// If calculated inside a foreach() $img_counter always equals $img_total.
$img_total = count($arrayFinal);
echo '<div class="property_text-container">';
echo 'Gallery for ' . $pid_text;
echo '</div>';
//<!-- Slideshow container -->
echo '<div class="slideshow-container">';
// foreach ($array1 as $value){
foreach ($arrayFinal as $value){
$img_counter ++; // Set before function() when using function call.
// Call the function located in gallery_ctrl_body:
createGallery($img_width, $img_style, $filename, $img_name, $img_src, $img_counter, $img_total, $value, $pid_text);
}
// <!-- Next and previous buttons -->
echo '<a class="prev" onclick="plusSlides(-1)">❮</a>';
echo '<a class="next" onclick="plusSlides(1)">❯</a> ';
echo '</div>';
// <!-- END: div class="slideshow-container"-->
echo '<br>';
// <!-- Dot container -->
echo '<div class="dot-container">';
// <!-- The dots/circles -->
echo '<div style="text-align:center">';
$slide_counter = 0;
while ($slide_counter < $img_total) {
$slide_counter ++;
echo '<span class="dot" onclick="currentSlide(' . $slide_counter . ')"></span> ';
}
echo '</div>';
echo '</div>';
// Script include needs to be run at end of page including it.
include_once ('../gallery_ctrl_script.php');
So, this code works but I'm not sure if it's the correct way or approach. If works for me as I have a set image naming convention and my galleries can be controlled from a single source file. It will work for any number of images, if they exist, in the folder where the function is being called from although my properties generally will have less than 50.
Basically I need to call a field (wrapped in a div) if the field has a value. I do not want the field or div to display if the field has no value. My PHP knowledge is dire but here is what I have to work with.
Here are instructions provided to me on how to call a custom field by ID:
$cust_1 = $this->fields->getFieldByCaption('Custom Text'); // getFieldByCaption() allow you to get the field by the Caption. This is not the best way to get a field since changing the caption in the back-end will break the reference.
echo '<br />Field ID: ' . $cust_1->getId();
$cust_2 = $this->fields->getFieldById(29); // getFieldById() is the ideal way of getting a field. The ID can be found at 'Custom Fields' section in Mosets Tree's back-end.
echo '<br />Name: ' . $cust_2->getName();
echo '<br />Has Caption? ' . (($cust_2->hasCaption()) ? 'Yes' : 'No');
echo '<br />Caption: ' . $cust_1->getCaption();
echo '<br />Value: ' . $cust_2->getValue();
echo '<br />Output: ' . $cust_2->getOutput(1);
echo '<hr />';
$this->fields->resetPointer();
while( $this->fields->hasNext() ) {
$field = $this->fields->getField();
echo '<br /><strong>' . $field->getCaption() . '</strong>';
echo ': ';
echo $field->getOutput(1); // getOutput() returns the formatted value of the field. ie: For a youtube video, the youtube player will be loaded
// echo $field->getValue(); // getValue() returns the raw value without additional formatting. ie: When getting value from a Online Video field type, it will return the URL.
$this->fields->next();
}
Here is the code I am working with and need help to try and do what I need it to as detailed above:
<?php
if( !is_null($this->fields->getFieldById(35)) ) {
$value = $field->getValue();
$hasValue = $field->hasValue();
$field = $this->fields->getField();
if( $hasValue )
{
echo '<div class="lin" id="lphn">'; {
echo $cust_2 = $this->fields->getFieldById(35);
echo $cust_2->getOutput(1);
echo '</div>';
}
else {
// Print nothing.
}
}
}
?>
not sure if I can example this right...
alright what I have here now runs the loop to check the student# and email I used an $error_check = 0 and $error_check ++ to consider if there's an error. If there is then an error will show and something will be printed into an error.log if not then something like the .txt file is good will print out and prints the contents
But I just realized the script will only run properly IF there's an error in the first row of my .txt file or else if there's an error to my second+ rows of contents in my .txt file then for the correct message will print out with the first row of content AND the error message will print out too.
But of course I want it the script to run that even if the first row of contents has no error and some other rows have error then only the error message will be printed.
I think it should be something about where I put the scripts in the loop but somehow I keep on reading my script and no idea what I should change....
else //else file exist then.......else #1
{
$fileContents = file("./courses/" . $_GET["filename"]); //calls out the file into $fileContents[] array....so $fileContents[0] is like the first row of the contents
$datePrinted = false; //setting a flag first so the date will be print only once when there's error..being used later in the foreach loop
$error_message = false; //setting a flag so error message only show once and being used later in the foreach loop
$well_formed = false; //another flag to stop the looping message saying the file is correctly formed
$table = false;
$error_check = 0;
sort($fileContents);
foreach($fileContents as $row) //the contents will be then seen as $row
{
$column = preg_split("/,/", $row); //splits the row by , and name each array as $column
$error_log = fopen("./courses/path/error.log","a+") or die ("File can not be opened"); //creates/open an error.log file
if(!(isEmailAddressWellFormed($column[3])) || !(isStudentNumberWellFormed($column[0]))) //two functions calls from page4.php using preg_match to check email and student# validation
//if one of them do not validate the following will start
{
$error_check++;
if(!$error_message) //if this is false then the error message+link will show
{
echo "Errors have been found in " . $_GET['filename'] . "<br/><a href='./courses/path/error.log'>Click here for the log</a>";
$error_message = true; //since this is in a loop but doesn't need to print it out so many times so changing the value here to true so when this loop runs again if(!error_message) will not run again
}
if(!$datePrinted) //works as how error_message works. the date only print once by here
{
fwrite($error_log, date("F t, Y (h:i:s a)") . PHP_EOL);
$datePrinted = true;
}
if(!(isEmailAddressWellFormed($column[3]))) //checks again if the email is not valid then print the follow to error.log
{
fwrite($error_log, "Improper email address from" . $_GET["filename"] . " :" . PHP_EOL);
fwrite($error_log, "$column[2] $column[1] $column[3]" . PHP_EOL);
}
if(!(isStudentNumberWellFormed($column[0]))) //checks again if the student # is not valid then print the follow to error.log
{
fwrite($error_log, "Improper student numbers from" . $_GET["filename"] . " :" . PHP_EOL);
fwrite($error_log, "$column[2] $column[1] $column[0]" . PHP_EOL . "\n");
}
}
elseif($error_check == 0)
{
if(!$well_formed)
{
echo "<h1 style='color: red'>" . $_GET["filename"] . " is well formed.</h1>";
echo "<table>";
$well_formed = true;
}
echo $column[0];
echo $column[1];
echo $column[2];
echo $column[3];
}
}//closing foreach
fwrite($error_log, str_repeat("-",80) . PHP_EOL); //puts a line to separate the next error but each time the page runs this line will print even if there's no error
fclose($error_log);
if(!$table)
{
echo "</table>";
$table = true;
}
}//closing else #1
thanks in advance for people helping...thanks....
I added
$row = $column[0] . $column[1] . $column[2] . $column[3];
at the beginning of the foreach after the preg_split then at the bottom I changed to...
elseif($error_check == 0)
{
$row.=$row;
}
}//closing foreach
fwrite($error_log, str_repeat("-",80) . PHP_EOL); //puts a line to separate the next error but each time the page runs this line will print even if there's no error
fclose($error_log);
if($error_check == 0)
{
echo "<h1 style='color: red'>" . $_GET["filename"] . " is well formed.</h1>";
echo "<table>";
echo $row;
echo "</table>";
}
}//closing else #1
?>
but now it only prints out the second row in the contents O.o only have three rows of contents at the moment for testing....am I missing something minor here?
I have some problems with displaying ÅÄÖ in jcart, I'm not very good at explaining but if you look here you'll see what I mean.
At first it all seems to work, but if you update the page or go to the checkout it doesn't. If you press "Ta bort" or add another item after updating the characters will be displayed correctly again. I use UTF-8 as charset and I've tried ISO-8859-1 which use to fix these problems, but instead it shows another symbol. Don't know exactly where the problem is so please tell me, if you have a clue, what you need more information about.
Looking at the demo may give you some ideas? Thanks!
To show the cart I have this: <?php $jcart->display_cart();?>
And here's some code from jcart.php (included file):
/**
* Process and display cart
*/
public function display_cart() {
$config = $this->config;
$errorMessage = null;
// Simplify some config variables
$checkout = $config['checkoutPath'];
$priceFormat = $config['priceFormat'];
$id = $config['item']['id'];
$name = $config['item']['name'];
$price = $config['item']['price'];
$qty = $config['item']['qty'];
$url = $config['item']['url'];
$add = $config['item']['add'];
// Use config values as literal indices for incoming POST values
// Values are the HTML name attributes set in config.json
$id = $_POST[$id];
$name = $_POST[$name];
$price = $_POST[$price];
$qty = $_POST[$qty];
$url = $_POST[$url];
// Optional CSRF protection, see: http://conceptlogic.com/jcart/security.php
$jcartToken = $_POST['jcartToken'];
// Only generate unique token once per session
if(!$_SESSION['jcartToken']){
$_SESSION['jcartToken'] = md5(session_id() . time() . $_SERVER['HTTP_USER_AGENT']);
}
// If enabled, check submitted token against session token for POST requests
if ($config['csrfToken'] === 'true' && $_POST && $jcartToken != $_SESSION['jcartToken']) {
$errorMessage = 'Invalid token!' . $jcartToken . ' / ' . $_SESSION['jcartToken'];
}
// Sanitize values for output in the browser
$id = filter_var($id, FILTER_SANITIZE_SPECIAL_CHARS, FILTER_FLAG_STRIP_LOW);
$name = filter_var($name, FILTER_SANITIZE_SPECIAL_CHARS, FILTER_FLAG_STRIP_LOW);
$url = filter_var($url, FILTER_SANITIZE_URL);
// Round the quantity if necessary
if($config['decimalPlaces'] === true) {
$qty = round($qty, $config['decimalPlaces']);
}
// Add an item
if ($_POST[$add]) {
$itemAdded = $this->add_item($id, $name, $price, $qty, $url);
// If not true the add item function returns the error type
if ($itemAdded !== true) {
$errorType = $itemAdded;
switch($errorType) {
case 'qty':
$errorMessage = $config['text']['quantityError'];
break;
case 'price':
$errorMessage = $config['text']['priceError'];
break;
}
}
}
// Update a single item
if ($_POST['jcartUpdate']) {
$itemUpdated = $this->update_item($_POST['itemId'], $_POST['itemQty']);
if ($itemUpdated !== true) {
$errorMessage = $config['text']['quantityError'];
}
}
// Update all items in the cart
if($_POST['jcartUpdateCart'] || $_POST['jcartCheckout']) {
$cartUpdated = $this->update_cart();
if ($cartUpdated !== true) {
$errorMessage = $config['text']['quantityError'];
}
}
// Remove an item
/* After an item is removed, its id stays set in the query string,
preventing the same item from being added back to the cart in
subsequent POST requests. As result, it's not enough to check for
GET before deleting the item, must also check that this isn't a POST
request. */
if($_GET['jcartRemove'] && !$_POST) {
$this->remove_item($_GET['jcartRemove']);
}
// Empty the cart
if($_POST['jcartEmpty']) {
$this->empty_cart();
}
// Determine which text to use for the number of items in the cart
$itemsText = $config['text']['multipleItems'];
if ($this->itemCount == 1) {
$itemsText = $config['text']['singleItem'];
}
// Determine if this is the checkout page
/* First we check the request uri against the config checkout (set when
the visitor first clicks checkout), then check for the hidden input
sent with Ajax request (set when visitor has javascript enabled and
updates an item quantity). */
$isCheckout = strpos(request_uri(), $checkout);
if ($isCheckout !== false || $_REQUEST['jcartIsCheckout'] == 'true') {
$isCheckout = true;
}
else {
$isCheckout = false;
}
// Overwrite the form action to post to gateway.php instead of posting back to checkout page
if ($isCheckout === true) {
// Sanititze config path
$path = filter_var($config['jcartPath'], FILTER_SANITIZE_URL);
// Trim trailing slash if necessary
$path = rtrim($path, '/');
$checkout = $path . '/gateway.php';
}
// Default input type
// Overridden if using button images in config.php
$inputType = 'submit';
// If this error is true the visitor updated the cart from the checkout page using an invalid price format
// Passed as a session var since the checkout page uses a header redirect
// If passed via GET the query string stays set even after subsequent POST requests
if ($_SESSION['quantityError'] === true) {
$errorMessage = $config['text']['quantityError'];
unset($_SESSION['quantityError']);
}
////////////////////////////////////////////////////////////////////////
// Output the cart
// Return specified number of tabs to improve readability of HTML output
function tab($n) {
$tabs = null;
while ($n > 0) {
$tabs .= "\t";
--$n;
}
return $tabs;
}
// If there's an error message wrap it in some HTML
if ($errorMessage) {
$errorMessage = "<p id='jcart-error'>$errorMessage</p>";
}
// Display the cart header
echo tab(1) . "$errorMessage\n";
echo tab(1) . "<form method='post' action='$checkout'>\n";
echo tab(2) . "<fieldset>\n";
echo tab(3) . "<input type='hidden' name='jcartToken' value='{$_SESSION['jcartToken']}' />\n";
echo tab(3) . "<table border='0'>\n";
echo tab(4) . "<thead>\n";
echo tab(5) . "<tr>\n";
echo tab(6) . "<th colspan='3'>\n";
echo tab(7) . "<div align='center'><span style='font-size:24px;' id='jcart-title'><br />VARUKORG</span> ($this->itemCount $itemsText) </div>\n";
echo tab(6) . "</th>\n";
echo tab(5) . "</tr>". "\n";
echo tab(4) . "</thead>\n";
// Display the cart footer
echo tab(4) . "<tfoot>\n";
echo tab(5) . "<tr>\n";
echo tab(6) . "<th colspan='3'>\n";
// If this is the checkout hide the cart checkout button
if ($isCheckout !== true) {
if ($config['button']['checkout']) {
$inputType = "image";
$src = " src='jcart/images/checkout.gif' alt='{$config['text']['checkout']}' title='' ";
}
echo tab(7) . "<input type='$inputType' $src id='jcart-checkout' name='jcartCheckout' class='jcart-button' value='{$config['text']['checkout']}' /> \n";
}
echo tab(7) . "<span id='jcart-subtotal'>{$config['text']['subtotal']}: <strong>" . number_format($this->subtotal, $priceFormat['decimals'], $priceFormat['dec_point'], $priceFormat['thousands_sep']) . " </strong></span>\n";
echo tab(6) . "</th>\n";
echo tab(5) . "</tr>\n";
echo tab(4) . "</tfoot>\n";
echo tab(4) . "<tbody>\n";
// If any items in the cart
if($this->itemCount > 0) {
// Display line items
foreach($this->get_contents() as $item) {
echo tab(5) . "<tr>\n";
echo tab(6) . "<td class='jcart-item-qty'>\n";
echo tab(7) . "<input name='jcartItemId[]' type='hidden' value='{$item['id']}' />\n";
echo tab(7) . "<input id='jcartItemQty-{$item['id']}' name='jcartItemQty[]' size='1' style='margin:0;padding:0;width:20px;' type='text' value='{$item['qty']}' />\n";
echo tab(6) . "</td>\n";
echo tab(6) . "<td class='jcart-item-name'>\n";
if ($item['url']) {
echo tab(7) . "<a href='{$item['url']}'>{$item['name']}</a>\n";
}
else {
echo tab(7) . $item['name'] . "\n";
}
echo tab(7) . "<input name='jcartItemName[]' type='hidden' value='{$item['name']}' />\n";
echo tab(6) . "</td>\n";
echo tab(6) . "<td class='jcart-item-price'>\n";
echo tab(7) . "<span>" . number_format($item['subtotal'], $priceFormat['decimals'], $priceFormat['dec_point'], $priceFormat['thousands_sep']) . "</span><input name='jcartItemPrice[]' type='hidden' value='{$item['price']}' />\n";
echo tab(7) . "<a class='jcart-remove' href='?jcartRemove={$item['id']}'>{$config['text']['removeLink']}</a>\n";
echo tab(6) . "</td>\n";
echo tab(5) . "</tr>\n";
}
}
Sorry for the huge ignorance on the topic, but I really have no idea where to look other than this website when I come into trouble with my PHP.
What I'm trying to do here is use pre-designated IDs to call particular movies from a database. But all I get is an 'Invalid argument supplied for foreach()' message on the second and third foreach's below.
Here's my code in the head:
//Custom lists of movies to bring in
//New Releases list
$films_new_releases = array(40805, 46705, 41630, 44564, 39451, 20352, 43933, 49009, 49797, 42194);
//Most Popular list
$films_most_popular = array(27205, 16290, 10138, 41733, 37799, 18785, 19995, 17654, 10140, 12162);
//Get information from address bar
$list = $_GET['l'];
if ($list == 'new releases') {
$list_chosen = $films_new_releases;
}
elseif ($list == 'most popular') {
$list_chosen = $films_most_popular;
}
else {
$list_chosen = $films_new_releases;
}
And in amongst the body:
// Loop through each film returned
foreach ($list_chosen as $list_chosen_film) {
$films_result = $tmdb->getMovie($list_chosen_film);
$film = json_decode($films_result);
// Set default poster image to use if film doesn't have one
$backdrop_url = 'images/placeholder-film.gif';
// Loop through each poster for current film
foreach($film->backdrops as $backdrop) {
if ($backdrop->image->size == 'poster') {
$backdrop_url = $backdrop->image->url;
}
}
echo '<div class="view-films-film">
<img src="' . $backdrop_url . '" alt="' . $film->name . '" />
<div class="view-films-film-snippet">
<h2>' . $film->name . '</h2>';
if ($film->certification != null) {
echo '<img src="images/bbfc-' . strtolower($film->certification) . '.png" alt="" />';
}
echo ' <h3>Starring</h3>
<p>';
$num_actors = 0;
foreach ($film->cast as $cast) {
if ($cast->job == 'Actor') {
echo '' . $cast->name . ' ';
$num_actors++;
if ($num_actors == 5)
break;
}
echo ' </p>
<h3>Director</h3>
<p>';
foreach ($film->cast as $cast) {
if ($cast->job == 'Director') {
echo '' . $cast->name . ' ';
}
}
echo ' </p>
</div>
</div>';
}
// End films
}
The little testing I've done is checking what $list_chosen, $list_chosen_film, $films_result and $film actually contain by printing them at the bottom of the page.
$list_chosen shows - Array, $list_chosen_film shows - 42194, $films_result shows the entire JSON string, $film shows - Array.
Try adding:
print_r($film->backdrop);
before the second foreach() loop. Before the error message it won't be an array or it will contain zero elements (not allowed). If you also add:
echo $films_result;
you will be able to debug it and fully understand what is wrong. If not, post the whole output in your question.
This happens, because - as error displayed by PHP informed you - you have provided wrong parameter to foreach loop, probably null or some other value. Make sure you are providing array to foreach.
Also, every time you use foreach, do it like that:
if (count($some_list) > 0) {
foreach ($some_list as $list_item) {
// code for each item on the list
}
} else {
// code when there is nothing on the list
}
This will ensure you will not see errors just because there is nothing on the list.
EDIT:
On the documentation page you can find some tip how to avoid such errors if the collection you are trying to iterate through is empty. Just cast the collection to array type:
foreach ((array) $some_list as $list_item) {
// code for each item on the list
}
Can you provide a dump of $film? The error is telling you that you are pointing to an object that cannot be iterated through (most likely null).