PHP - Beginning Php 5.3 Problem
I'm reading through this book which is actually not bad but, on page 286 there's a shopping_cart.php code (which I downloaded from the web site). The code that seems relevant to me is this:
<?php $totalPrice = 0; foreach ( $_SESSION["cart"] as $product) { $totalPrice += $product->getPrice(); //<<<LINE 94 ?> The error I get is Fatal error: Call to a member function getPrice() on a non-object in C:\usr\web\shopping_cart.php on line 94 Should $product be a cast to the Product object? class Product { private $productId; private $productName; private $price; public function __construct( $productId, $productName, $price ) { $this->productId = $productId; $this->productName = $productName; $this->price = $price; } public function getPrice() { return $this->price; } //etc. } Similar Tutorialshi... i have a table ... i add and remove data in the table...when i add new record , information add to center of the table ! whats problem? i want add data in first of table. please guide me.thanks
The below code returns a radio list after an input box in a profile edit section. All I want to do is add a space at the beginning of the radio list so to separate the input box and the radio list. Where the magic happens here is on this line: return $selhtml . ' ' . getFieldIcons( $_CB_framework->getUi(), $required, null, $fieldHandler->getFieldDescription( $field, $user, $output, $reason ), $fieldHandler->getFieldTitle( $field, $user, $output, $reason ) ); I've tried several variations of trying to use &nspb; both in the return string directly as well as creating a var for it. I've tried various ways of wrapping it in a div to simply add a margin, I've tried kicking my dog, I've tried banging my head against the wall, nothing seems to work. I either get a t var error, an unexpected something or other like . or & error depending on what I'm doing, or it tries to divide by zero using /'s. Here's a larger view of the code: function onFieldIcons( &$fieldHandler, &$field, &$user, $output, $reason, $tag, $type, $value, $additional, $allValues, $displayFieldIcons, $required ) { global $_CB_framework, $ueConfig, $_CB_fieldIconDisplayed; if ( is_object( $field->params ) ) { $privacyLevel = $field->params->get( 'plug_cbprivacy_level' ); } else { $privacyLevel = 0; } if ( $displayFieldIcons && ( $reason != 'search' ) ) { if ( ( $privacyLevel == 1 ) && ( $field->profile != 0 ) ) { $privacy =& moscomprofilerPrivacy::getInstance( $user, 'field', $field->fieldid ); $selected = ( $privacy ? $privacy->rule : '' ); $selectorName = $field->name . '___cbprivacy'; $connTypes = array(); if ( $this->params->get( 'conns_by_type', 0 ) ) { if ( $ueConfig['connection_categories'] ) { $connTypes = explode( "\n", $ueConfig['connection_categories'] ); foreach ( array_keys( $connTypes ) as $k) { $connTypes[$k] = trim( $connTypes[$k] ); } } if ( $selected == 2 ) { $type = $privacy->getParam( 'conn_cat' ); if ( $type ) { $selected = $selected . '|*|' . $type; } } } $options = array(); $options[] = moscomprofilerHTML::makeOption( '', '' . CBTxt::T(' ') ); if ( ( $ueConfig['allow_profileviewbyGID'] == -2 ) && $this->params->get( 'prop_registered', 1 ) ) { $options[] = moscomprofilerHTML::makeOption( '1', '' . CBTxt::T(' ' ) ); } if ( $ueConfig['allowConnections'] ) { $prop_connections = $this->params->get( 'prop_connections', 1 ); if ( $prop_connections ) { $options[] = moscomprofilerHTML::makeOption( '2', '' . CBTxt::T( ' ' ) ); } if ( count( $connTypes ) > 1 ) { foreach ($connTypes as $type ) { $options[] = moscomprofilerHTML::makeOption( '2|*|' . htmlspecialchars( $type ), ( $prop_connections ? ' ⌊ ' : '' ) . '' . sprintf( CBTxt::T( 'Only for %s' ), $type ) ); } } if ( $this->params->get( 'prop_fofs', 1 ) ) { $options[] = moscomprofilerHTML::makeOption( '3', '' . CBTxt::T( 'Also for friends of friends' ) ); } } if ( $this->params->get( 'prop_invisible', 1 ) ) { $options[] = moscomprofilerHTML::makeOption( '99', '' . CBTxt::T( ' ' ) ); } $selHtml = moscomprofilerHTML::radioList( $options, $selectorName, '', 'value', 'text', $selected, 2, false ); if ( isset( $_CB_fieldIconDisplayed[$field->fieldid] ) ) { return $selHtml; } else { $_CB_fieldIconDisplayed[$field->fieldid] = true; return $selHtml . ' ' . getFieldIcons( $_CB_framework->getUi(), $required, null, $fieldHandler->getFieldDescription( $field, $user, $output, $reason ), $fieldHandler->getFieldTitle( $field, $user, $output, $reason ) ); } } else { if ( isset( $_CB_fieldIconDisplayed[$field->fieldid] ) ) { return null; } else { $_CB_fieldIconDisplayed[$field->fieldid] = true; return getFieldIcons( $_CB_framework->getUi(), $required, $field->profile, $fieldHandler->getFieldDescription( $field, $user, $output, $reason ), $fieldHandler->getFieldTitle( $field, $user, $output, $reason ) ); } } } else { return null; } } The basic layout here is this: |inputbox||radio list| But I want: |inputbox| |radio list| $i = 0; while($i < 10) { if ($i == 7) { //Do Function } else { $i++ Go back to beginning of loop } //More if statements here. } Here is my current code to display files from the end to beginning : Code: [Select] <?php function func() { $date = date("Y-m-d"); $picarray = array(); $userarray = array(); $handle = opendir ('pqimages/'.$date.'/'); while (false !==($file = readdir($handle))) { if($file != "." && $file != "..") { $picarray[] = "http://blah.com/pqimages/".$date."/".$file.""; $userarray[]= "pqimages/".$date."/".$file.""; } } sort($picarray); sort($userarray); closedir($handle); $json_array = json_encode($picarray); echo $json_array; } func(); ?> How could I change this from end to beginning for ($picarray)? Cheers, George My first post.
I am trying to import images related to a particular listing ID. Currently, I have to enter the number of available photos into a db table, and run the following loop;
<section id="photos">
<?php
$b = $row['PIX'];
for ( $a = 01; $a <= $b; $a++ ) { echo "<a href=\"../imgs/{ $row[ 'ID' ] }-" . { $a } . ".jpg\" ><img src=\"../imgs/{ $row[ 'ID' ] }-" . { $a } . "_tn.jpg\" /></a> " ; } ?> </section> I would like to find a way to import all the images that begin with the $row[ 'ID' ], but without me having to enter/store { $b } (the number of images recorded in the db). How can I accomplish this? _ Hi, I have two variables: $latest_note and $notes. Whenever I update $latest_note, I also want this (and today's date) to be added to $notes, such that $notes becomes a sort of archive of all of the latest notes, listed by date. I tried creating a third variable called $full_notes and saying $full_notes = $latest_note.$notes; ... then when I run my mysql update, I set notes='$full_notes' but it's not working properly. Is there a way to simply add one variable to the beginning of another in the db directly, concatenating the two? Thanks! Hello guys, im using this code atm and it's working, but the new rows created are put in the end of the table. I want them to stack up from the beginning pushing older rows down. What should i do to make that work? <?php $con = mysql_connect("localhost","*****","*******"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("ananaz_se", $con); $sql="INSERT INTO stuff (adult, namn, url) VALUES ('$_POST[adult]','$_POST[namn]','$_POST[url]')"; if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } echo "1 row added"; mysql_close($con) ?> This is my code: $episodes = mysql_query("SELECT * FROM episode_links WHERE episode_id = '".$episode_id."' AND moderated='1' ORDER BY host ASC"); while ($episode = mysql_fetch_assoc($episodes)) { // code here } and in my host table, I have values like this: Fileserve.com MegaUpload.com Rapidshare.com Torrent And I would like a way to sort this so that only the Fileserve links appear on the top ( the first few results), then all the others. can anyone help me? I keep getting errors that are associated with one-off and one-time occurrences. I want to tell the script to just restart itself from the beginning if it encounters any type of error, whether it by a fatal error, or any other kind. is there a way to do this? Hello, I have this XML file I am parsing and I have hit a small formatting issue that I can't seem to get around.
Here is what the the output of the RSS looks like.
<description><![CDATA[<div style='text-align:left;'>Exit ramp closed. <br/><b>Current Status:</b> Open<br/><b>Affected Lanes:</b> Exit Ramp<br/><b>Dates:</b> Wednesday, May 28 - Thursday, May 29<br/><b>Days Closed:</b> <font color='#808080'>S</font><font color='#808080'>M</font><font color='#808080'>T</font><font color='#FF0000'><b>W</b></font><font color='#FF0000'><b>T</b></font><font color='#808080'>F</font><font color='#808080'>S</font> 20:00 PM - 6:00 AM</div>]]></description>Notice at the first is "Exit ramp closed." There is nothing before it but, for some weird reason when I parse it. It is on a new line like so, notice it should be up there with "Incident" but, it is dropped down below it. Incident: Exit ramp closed. Current Status: Open Affected Lanes: Exit Ramp Dates: Wednesday, May 28 - Thursday, May 29 Days Closed: SMTWTFS 20:00 PM - 6:00 AMThis is how it is formated in the td cell. <td style='{$td2Style}'><strong>Incident:</strong> {$incident_data_desc}</td>\n";So as you can see above, there is nothing before it that would cause it to break to a new line both in the table or in the RSS. So how can I remove that first return only is that is on the same line with it and not below it. I have tried this and a couple of other things like trim with no luck. $description = $item->description; $incident_data_desc = str_replace("\r", '', $description );Note, I only need that first one removed, the others are fine. I can do it but it will remove all the breaks and I only want to remove that first one that is causing the line to be on a new line. Any suggestions? -Thanks Hi, I've always used PHP code in my websites in a procedural manner as I come from a html/css background. Now that I want to do projects with more complexity I'm thinking I need to approach development in a more Object Oriented fashion. My question is more a theoretical one. I'm creating a User class and I'm not sure on what is the best practise for putting my functions etc. and where to call them. My project will have 2 different users (Admin & End User) so is it correct to say that the User class should encapsulate all the functions of both of these users ? By that I mean create/delete/modify user, login & change password/forgotten password functionality rather than having a seperate Login class Should I only call the database functions within these methods of the user class as opposed to calling them on the php page where the form data is posted ? For example, if a user logins in and when the form data is posted I currently open a connection, validate data, run the query. In an OO approach would I have just one User class method thats relevant to a particular page functionality ? Say, in pseudo code, for handling a login request loginRequest.php Code: [Select] include User class try { create new user User(); User::login(); } catch Exception() and should my User class look something like this class.User.php Code: [Select] include DBase class class User { var name, var email, var password, function validateInput (email, password) { if (!valid input) throw Exception else return true } function login (email, password){ try { database connection validateInput(); sql to see if user exists and login } catch Exception } } Apologies for this being a bit long winded! thanks tmfl I have a regex that validates a string.
I want to ensure there is no space in the string.
Thus far I have used the negative look ahead regex construct as shown below to match strings without spaces.
(?!.*(\s))While this prevents space in between a word, all strings with space characters at the end or beginning are getting validated. I do not want that at all. This is the full regex script below: $string = "#JebiamgoOeing0"; if (preg_match('/^.*(?=.{8,})(?!.*([A-Za-z0-9])\1{1})(?=.*[a-z])(?=.*[A-Z])(?!.*(\s))(?=.*[\d])(?=.*[\W]).*$/', $string)) { "do something"; } else { "do something else"; }I need help in resolving this. Thank you. Edited by terungwa, 25 October 2014 - 12:50 PM. I've inherited a website (www.bonniebakerlaw.com) and have found that the previous web developer had left the contact form in quite a shambles. As you can see it attempts to use a Captcha to validate users, but does not in fact work! I can leave the entire form blank (including the captcha) and still get to the "Thank You" page indicating the form was correctly submitted (This does not, in fact, actually generate an email correctly)! So before I delve into "Head First PHP & MySQL" to debug and correct the error, I was wondering if some kind person(s) would be good enough to point me to the relevant sections / documentation highlighting the fundamentals of building this type of form correctly coupled with the use of a Captcha as noted. Some code has been REDACTED to protect the innocent. I won't post the HTML of the form as it's available from the web site and is a fairly simple HTML construct. Form Code: Code: [Select] <?php require_once('recaptchalib.php'); // Get a key from https://www.google.com/recaptcha/admin/create $publickey = "REDACTED PUBLIC KEY"; $privatekey = "REDACTED PRIVATE KEY"; # the response from reCAPTCHA $resp = null; # the error code from reCAPTCHA, if any $error = null; # was there a reCAPTCHA response? if ($_POST["recaptcha_response_field"]) { $resp = recaptcha_check_answer ($privatekey, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]); if ($resp->is_valid) { echo "You got it!"; } else { # set the error code so that we can display it $error = $resp->error; } } echo recaptcha_get_html($publickey, $error); ?> "Thank You" page Code: Code: [Select] <?php $visitor = $_REQUEST['visitor'] ; $visitormail = $_REQUEST['visitormail'] ; $State = $_REQUEST['State:'] ; $Address = $_REQUEST['StreetAddress'] ; $City = $_REQUEST['City:'] ; $Zip = $_REQUEST['Zip:'] ; $Phone = $_REQUEST['Phone:'] ; $Fax = $_REQUEST['Fax:'] ; $Emailed = $_REQUEST['Emailed'] ; $Phoned = $_REQUEST['Phoned'] ; $Faxed = $_REQUEST['Faxed'] ; $Postaled = $_REQUEST['Postaled'] ; $Description = $_REQUEST['IssueDescription'] ; if ($Emailed == "y") { $req1 = " Email \n" ; } if ($Phoned == "y") { $req2 = " Phone \n"; } if ($Faxed == "y") { $req3 = " Fax \n"; } if ($Postaled == "y") { $req4 = " Postal Mail \n"; } $req = $req1 . $req2 . $req3 . $req4 ; $message = "name: $visitor email: $visitormail Address: $Address City: $City State: $State Zip: $Zip Phone: $Phone Fax: $Fax Requested contact by: $req Description: $Description " ; mail("redacted@somedomain.com", "redacted@somedomain.com: contact page", "$message", "From: $visitormail" ) ; ?> Hello, i have two fields. a beginning year and an ending year. How can i make new fields out of the years in between the beginning and ending years. i hope that makes sense. Guys thanks for helping me solve the problem i had but now i have another problem and i am lost. i have included the code below for you to have overview.
This is the code:
<table style="width:100%; margin-left:auto; margin-right:auto"> Hi, i use mysql_real_escape_string() function when insert in db, but when echo i use htmlentities($var, ENT_QUOTES, "UTF-8") Now problem is '\ in that text. In db it write text with single quote with \, example That\'s wrong, and when echo it show just the same like in db.. How can i fix this ? im making a website it works fine on firefox but on ie doesnt work correctly. page looks weird i see the error is <? include("index/index_files/front/php/include.php"); ?> anyone can help me its in a <html> tab. Elo, I'm creating a very simple image list that is function generated which pulls the source from a table in my database, this is my code Code: [Select] $output = "<ul>"; $img_src = get_all_image_src($sel_event['id']); while($src = mysql_fetch_array($img_src)) { for($i=0;$i <= 9; $i++) { $output .= "<li>"; $output .= "<a"; $output .= " class ='album'"; $output .= " rel='group'"; $output .= " href='/images/gallery/'" . $src['img_src'] . $i; $output .= ".jpg"; $output .= " title='sample 1'"; $output .= ">"; //Image Thumb $output .= "<img"; $output .= " src='/images/gallery/'"; $output .= $src['img_thumb_src']. $i . ".jpg"; $output .= "alt='image01' "; $output .= "title='sample title' />"; $output .= "tae"; $output .= "</a>"; $output .= "</li>"; } } $output .= "</ul>"; return $output; and the img src doesnt seems to add up... my folder structure is Sandbox>image>gallery>2011>Mall>Event>Thumbs where Sandbox is the main directory. i tried echoing the $src['img_src'] and it displays correctly the data to be added (which is 2011/Mall/Event/ plus $i and a .jpg) .. sorry noob here... any thoughts? am i missing a simple detail? Hi, im creating a script for a website that will list products, i have the basic construct which lists the products from the database but it lists then vertically, i have set the width of each 'product' to 200px so i could have around 3 colums and many rows. can anybody advise how i would make them run vertically aswell as horizontally? my code below: <?php include_once("include/globals.php"); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> <link href="styles/stylesheet.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="main"> <?php //Get database Results $result = mysql_query("SELECT * FROM Products WHERE is_active = 1") or die(mysql_error()); //keeps getting the next row until no more records while($row = mysql_fetch_array($result)) { //echo results ($result) echo '<div id="holder">'; echo '<div class="title">' . $row['Name'] . '</div>'; //insert image here echo '<div class="image">'; echo '<img src="' . $row['image'] . '" width="100" alt="">'; echo '</div>'; echo '<div class="tag_line">'; echo $row['Tag_Line']; echo '</div>'; echo '<div class="price">Now Only: £'; echo $row['Website_Price']; echo '</div>'; echo '<div class="prod-footer"></div>'; echo '</div>'; } ?> </div> </body> </html> table structu Field Type Null Default Comments MIME ID int(11) No product_code varchar(255) No Name varchar(255) Yes NULL Tag_Line varchar(255) Yes NULL Description varchar(255) Yes NULL Specification varchar(255) Yes NULL Technical_Info varchar(255) Yes NULL Cost_Price_USD decimal(10,2) Yes NULL Cost_Price_GBP decimal(10,2) Yes NULL Built_in_delivery decimal(10,2) Yes NULL Trade_Price decimal(10,2) Yes NULL Trade_Plus_Price decimal(10,2) Yes NULL Website_Price decimal(10,2) Yes NULL Is_active int(1) No image varchar(255) Yes NULL Okay, so i'm using the basic php mysql insert into function but I have a strange (or maybe not so strange, I just don't get it..) problem.. I have two columns (do you call them columns? I don't really know for sure, whatever things that are in a table whatsoever). Name and Trailer. EDIT: they are TEXT's if that matters Name is really nothing important, just the name. But I want to embed trailers.. If I embed the Megavideo code below: Code: [Select] <object width="400" height="300"><param name="movie" value="http://www.megavideo.com/v/8UZFURZQ2b55ada04d73ae65c726a5383b9ee9d9"></param><param name="allowFullScreen" value="true"></param><embed src="http://www.megavideo.com/v/8UZFURZQ2b55ada04d73ae65c726a5383b9ee9d9" type="application/x-shockwave-flash" allowfullscreen="true" width="400" height="300"></embed></object> Everything works fine, no problems and no bullshit. But.. if I for an example try to embed this one (NovaMov): Code: [Select] <iframe style='overflow: hidden; border: 0; width: 400px; height: 300px' src='http://embed.novamov.com/embed.php?width=400&height=300&v=xngq7u8yejwbt' scrolling='no'></iframe> It doesn't work. It just doesn't insert. Is inserting an "iframe" a problem or something? I just don't get why the hell it would do this? Does anyone know anything about this? If so i'd be eager and very thankful to hear why and how to fix it. thanks in advance |