PHP - I Need To Add Product Attributes
I cant get my head around this. I m trying to add product attributes into this script.
I have products tables and product_extras product.id and product_extras.id are same. How can I add this to cart. Is there any easy way to do this. Any help would be much appreciated! Quote cart.php Code: [Select] <?php // Include MySQL class require_once('inc/mysql.class.php'); // Include database connection require_once('inc/global.inc.php'); // Include functions require_once('inc/functions.inc.php'); // Start the session session_start(); // Process actions $cart = $_SESSION['cart']; $action = $_GET['action']; switch ($action) { case 'add': if ($cart) { $cart .= ','.$_GET['id']; } else { $cart = $_GET['id']; } break; case 'delete': if ($cart) { $items = explode(',',$cart); $newcart = ''; foreach ($items as $item) { if ($_GET['id'] != $item) { if ($newcart != '') { $newcart .= ','.$item; } else { $newcart = $item; } } } $cart = $newcart; } break; case 'update': if ($cart) { $newcart = ''; foreach ($_POST as $key=>$value) { if (stristr($key,'qty')) { $id = str_replace('qty','',$key); $items = ($newcart != '') ? explode(',',$newcart) : explode(',',$cart); $newcart = ''; foreach ($items as $item) { if ($id != $item) { if ($newcart != '') { $newcart .= ','.$item; } else { $newcart = $item; } } } for ($i=1;$i<=$value;$i++) { if ($newcart != '') { $newcart .= ','.$id; } else { $newcart = $id; } } } } } $cart = $newcart; break; } $_SESSION['cart'] = $cart; ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>products</title> <link rel="stylesheet" href="css/styles.css" /> </head> <body> <div id="shoppingcart"> <h1>Your Shopping Cart</h1> <?php echo writeShoppingCart(); ?> </div> <div id="contents"> <h1>Please check quantities...</h1> <?php echo showCart(); ?> <p><a href="index.php">Back to products...</a></p> </div> </body> </html> Quote functions.php Code: [Select] <?php function writeShoppingCart() { $cart = $_SESSION['cart']; if (!$cart) { return '<p>You have no items in your shopping cart</p>'; } else { // Parse the cart session variable $items = explode(',',$cart); $s = (count($items) > 1) ? 's':''; return '<p>You have <a href="cart.php">'.count($items).' item'.$s.' in your shopping cart</a></p>'; } } function showCart() { global $db; $cart = $_SESSION['cart']; if ($cart) { $items = explode(',',$cart); $contents = array(); foreach ($items as $item) { $contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1; } $output[] = '<form action="cart.php?action=update" method="post" id="cart">'; $output[] = '<table>'; foreach ($contents as $id=>$qty) { $sql = 'SELECT * FROM products WHERE id = '.$id; $result = $db->query($sql); $row = $result->fetch(); extract($row); $output[] = '<tr>'; $output[] = '<td><a href="cart.php?action=delete&id='.$id.'" class="r">Remove</a></td>'; $output[] = '<td>'.$title.'</td>'; $output[] = '<td>£'.$price.'</td>'; $output[] = '<td><input type="text" name="qty'.$id.'" value="'.$qty.'" size="3" maxlength="3" /></td>'; $output[] = '<td>£'.($price * $qty).'</td>'; $total += $price * $qty; $output[] = '</tr>'; } $output[] = '</table>'; $output[] = '<p>Grand total: <strong>£'.$total.'</strong></p>'; $output[] = '<div><button type="submit">Update cart</button></div>'; $output[] = '</form>'; } else { $output[] = '<p>You shopping cart is empty.</p>'; } return join('',$output); } ?> Similar TutorialsHi there, I'm trying to get the full Product Name in the <title> of each of the product pages - I can't seem to figure out what to put in the product_info.php... I've tried a few different options but I'm not great with php Here's what I have currently but it creates errors... <script language="javascript"><!-- document.write('<title><?php echo TITLE; ?> : <?php echo $product_info['products_name']; ?> </title>'); //--></script> Hope someone can help - thanks so much! Context. Class AbstractTenantEntity's purpose is to restrict access to data to the tenant (i.e. account, owner, etc) that owns the data. Any entity which extends it will have the TenantId added when created and the TenantId in the WHERE clause for all other requests. Tenant typically does not have collections of the various entities which extend AbstractTenantEntity, but does for a few of them do. When using annotation, I handled it by applying Doctrine's AssociationOverride annotation to the extended classes which should have a collection in Tenant. use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity() */ class Tenant { /** * @ORM\OneToMany(targetEntity=Asset::class, mappedBy="tenant") */ private $assets; // Other properties and typical getters and setters }
use Doctrine\ORM\Mapping as ORM; abstract class AbstractTenantEntity implements TenantInterface { /** * inversedBy performed in child where required * @ORM\ManyToOne(targetEntity=Tenant::class) * @ORM\JoinColumn(nullable=false) */ protected ?Tenant $tenant = null; // Typical getters and setters }
use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity() * @ORM\AssociationOverrides({ * @ORM\AssociationOverride(name="tenant", inversedBy="assets") * }) */ class Asset extends PublicIdTenantEntity { // Various properties and typical getters and setters }
So, now I am changing from annotations to attributes, and modified AbstractTenantEntity as follows: use Doctrine\ORM\Mapping\ManyToOne; use Doctrine\ORM\Mapping\JoinColumn; abstract class AbstractTenantEntity implements TenantInterface { /** * inversedBy performed in child where required */ #[ManyToOne(targetEntity: Tenant::class)] #[JoinColumn(nullable: false)] protected ?Tenant $tenant = null; // Typical getters and setters } Next I went to modify Asset and realized that there didn't appear to be an attribute for AssociationOverride. I found a little discussion on the topic on github but couldn't find any resolution. Question Can inheritance be used with PHP 8 attributes where the property is defined in the parent class and the attribute is applied in the child class? Googling php 8 attributes inheritance didn't provide anything and thus I expect the answer is no but thought I'd ask. Thanks
EDIT. Maybe Doctrine does have an attribute version: https://github.com/doctrine/orm/blob/2.9.x/lib/Doctrine/ORM/Mapping/AttributeOverride.php EDIT2. Actually don't think so Edited July 30 by NotionCommotionI have a site that allows members to create pages. These pages consist of small sections some of which HTML can be entered. To keep visitors from straying away from the site, any outside urls are brought up in a modal window. Using inline attributes, a class has to be created (or added to), and the title tag requires some special characters. I can probably get around this by inserting an onclick or something, but there must be a way to replace attributes, and I am at a loss. The text segments are stored in a database. What I want to do is change the <a> tag attributes as the page is created. So I have a segment of text "$TheText" and I want to change or replace the attribute values. For instance, If $TheText contains an 'a' tag that looks like this: Code: [Select] <a class="MyClass" title="Godzilla" href="http://www.godzillaslair.com">Godzilla</a>I would want to change it to Code: [Select] <a class="MyClass Lightview" title="Godzilla :: {Lightview's parameters}">Godzilla</a>Or even just replace the attributes entirely, so it would look like Code: [Select] <a class="Lightview" title="{Inserted Title} :: {Lightview's parameters}">Godzilla</a> In other words, just replacing the attribute values. Of course, I need to see if the attributes exist. I know how to do that and how to get their values. But all that tells me is that I have an 'a' tag in the text with those values for those attributes. I cannot, for example, then do a str_replace in the first example, because there may be another tag in the text with the "MyClass" class. I can iterate character by character between <a and </a> but there must be a better way. I'm no good at regex, so I haven't even attempted that. Any suggestions would certainly be appreciated. $_POST['select'] permits me access to the selected value of my combo box named 'select'. are any other attributes of the box accessible? in particular, index # ... etc.? thanks in advance for any light you might shed on the topic. I am making a project by designing my own MVC model. In this the user accesses controller class which further calls model class which accesses the database by $dbh attiribute defined public. My View is a script which calls different pages. In the constructor of model I'm establishing connection with the database. Firstly I construct the model object when the user accesses i.e. in the controller class to check in the databse then if the username is not present in the dtaabse I want to insert his info in the database for that I again calla model class but this time I again have to establish connection. Is the $dbh firstly constructed is lost like dangling pointers in C++. Do I have to worry about it. If yes how can I solve this problem. Hi all, I'm sure I'm making this far more difficult than I need to... I've got an xml document... <library id="1"> <lname>Lib1</name> <book id="1"> <title>book 1</title> <author>Author 1</author> </book> <book id="2"> <title>book 2</title> <author>Author 2</author> </book> </library> I can access the nested elements using xpath like : $result = $xml->xpath('//book'); foreach($result as $books) { echo $books->title; } How would I do this for the attributes? If I specify I want the attributes in the xpath query I can't get at the elements... I'm trying to turn this xml file into a simple relational database... A library table and a book table. So I need the library id (attribute) and the name(nested element) for one insert query - and the book id, title, author and the library id for the other. Anyone got any idea? Cheers John Hi, Im trying to grab some data from a XML generated by an external server. I know how to grab from XML without attributes, but I cant seem to wrap my head around the structure of this file. What would be easiest way to get the value of the "dbnr" field? Part of the XML file: Code: [Select] <data> <location> <field name="id" format="Long">xxxxxx</field> <field name="dbnr" format="Long">xxxxxx</field> <field name="jobnr" format="Long">xxxxxx</field> <field name="job_type" format="String" maxlen="50">xxxxxx</field> <field name="job_category" format="String" maxlen="50">xxxxxx</field> </location> </data> Hi, I am new to xml parsing and I just want to know how to check whether a node has attributes: Here is my xml file to use: ================= Code: [Select] <?xml version="1.0" encoding="ISO-8859-1"?> <email> <message> <to> <toFirstName>Tove</toFirstName> <toLastName toType="common" style="swag">Smith</toLastName> </to> <from> <fromFirstName>Jani</fromFirstName> <fromLastName fromType="unique">Dravison</fromLastName> </from> <heading>Reminder</heading> <body> <prologue>Tis the night before Xmas...</prologue> <paragraph1>Don't forget me this weekend!</paragraph1> <paragraph2>Jump the gun!</paragraph2> <epilogue>The end of the world.</epilogue> </body> </message> <message> <to>employees</to> <from>CEO</from> <heading>Power Lunch</heading> <body> <prologue></prologue> <paragraph1>Year over year data</paragraph1> <paragraph2>Downsizing</paragraph2> <epilogue>The end.</epilogue> </body> </message> </email> Here the simple script that I cannot get to work: ================================== Code: [Select] <?php $simpleXMLObj=simplexml_load_file("email.xml"); if($simpleXMLObj->to[0]->toLastName[0]->attributes()->getName) print "YES: this node has attributes!"; else print "NO:"; ?> Please I really need help, it is simple I know but I am new to xml parsing and mixed up. How can I print the attributes of a child node? I have been trying and looking and cant get it. I need the attributes of subfield printed after datafield so a line would look like datafield plus attributes plus subfield attributes plus subfield =906 __$a0$bcbc$corignew etc... <?php //child nodes http://www.w3schools.com/php/php_xml_dom.asp //http://books.google.com/books?id=ygQRKDEsLecC&pg=PA196&lpg=PA196&dq=print+php+xml+child+node+attributes&source=bl&ots=TCAhH4kpCt&sig=yJUPXesIkRUrNXdNE9Yr5ul7Wdw&hl=en&ei=U51kTeKQKsL48AbN4MDTBg&sa=X&oi=book_result&ct=result&resnum=10&ved=0CF4Q6AEwCQ#v=onepage&q=print%20php%20xml%20child%20node%20attributes&f=false //http://stackoverflow.com/questions/4598409/printing-content-of-a-xml-file-using-xml-dom $doc = new DOMDocument(); $doc->preserveWhiteSpace = FALSE; $doc->load( 'loc.xml' ); $root = $doc->documentElement; $type = $root->nodeType; //print $doc->nodeName."\n"; //print $root->nodeName."\n"; //print $doc->nodeValue."\n"; //print $root->nodeValue."\n"; $librecords = $doc->getElementsByTagName( "record" ); foreach( $librecords as $record ){ $leader = $record->getElementsByTagName( "leader" ); $controlfields = $record->getElementsByTagName( "controlfield" ); $datafields = $record->getElementsByTagName( "datafield" ); $subfields = $record->getElementsByTagName( "subfield" ); $leader = $leader->item(0)->nodeValue; echo '=LDR '.$leader.'<BR>'; foreach( $controlfields as $controlfield ){ $tag = $controlfield->getAttribute('tag'); $cf_value = $controlfield->firstChild->nodeValue; echo "=".$tag." ".$cf_value.'<BR>'; } foreach( $datafields as $datafield ){ $tag = $datafield->getAttribute('tag'); $ind1 = $datafield->getAttribute('ind1'); $ind2 = $datafield->getAttribute('ind2'); if ($ind1 ==" ") {$ind1 = "_";} if ($ind2 ==" ") {$ind2 = "_";} echo "=".$tag." ".$ind1.$ind2; //if($datafield->hasChildNodes()){echo 'This node has children!<br />';} foreach ($datafield->childNodes AS $item) { // $arr = $item->attributes; print $arr; print 'nodeName '.$item->nodeName . " = " . $item->nodeValue." | " ;} //. "<br />"; } // foreach ($datafield->children() as $node) { // $arr = $node->attributes(); // returns an array // print ("code=".$arr["code"]); // get the value of this attribute // print (" Company=".$node->subfield); // print ("<p><hr>"); //} // foreach( $subfields as $subfield){ // foreach($subfield->attributes as $attr){ // $attributes = $subfield->attributes; // print $attr->nodeName; // print $attr->nodeValue; // //print $attributes->nodeName; //print $attributes->nodeValue; // print $subfield->nodeName; // print $subfield->nodeValue; //}} // print $item->nodeValue ; // print $item->attributes("code"); // $valueID = $item->getAttribute('code'); // print $item->nodeName->attributes("code"); // echo $item->nodeValue.getAttribute("code"); // print $item->getAttribute('code') //http://www.devshed.com/c/a/PHP/Accessing-Attributes-and-Cloning-Nodes-with-the-DOM-XML-Extension-in-PHP-5/1/ echo '<BR>'; } foreach( $subfields as $subfield ){ $code = $subfield->getAttribute('code'); $sf_value = $subfield->firstChild->nodeValue; echo '$'.$code.$sf_value.'<BR>'; } echo '<BR>'; } ?> Code: [Select] <leader>01026ngm a22002773a 4500</leader> <controlfield tag="001">16429180</controlfield> <controlfield tag="005">20100823131409.0</controlfield> <controlfield tag="007">vffcjaho|</controlfield> <controlfield tag="008">100823s2010 xxu060 mleng </controlfield> <datafield tag="906" ind1=" " ind2=" "> <subfield code="a">0</subfield> <subfield code="b">cbc</subfield> <subfield code="c">orignew</subfield> <subfield code="d">u</subfield> <subfield code="e">ncip</subfield> <subfield code="f">20</subfield> <subfield code="g">y-movingim</subfield> </datafield> <datafield tag="955" ind1=" " ind2=" "> <subfield code="b">qm12 2010-08-23</subfield> </datafield> I have the following code below: The following script came from using-custom-paths. It appears that these are PHP 8's new attributes, correct? <?php // api/src/Entity/Question.php #[ApiResource( subresourceOperations: [ 'api_questions_answer_get_subresource' => [ 'method' => 'GET', 'path' => '/questions/{id}/all-answers', ], ], )] class Question { }
I currently am using PHP7 and will need to convert them. Does the following look correct? Thanks /** * @ApiResource( * subresourceOperations = { * "api_questions_answer_get_subresource" = { * "method" = "GET", * "path" = "/questions/{id}/all-answers" * } * } * ) */
<league name="italy" id="1"> <match name="AC Milan v Palermo" time="15/02/2011 20:45"> <bettype name="Versus (with Draw)"> <bet outcome_name="AC Milan" odd="1.87"> <bet outcome_name="X" odd="3.40"> <bet outcome_name="Palermo" odd="4.00"> </bettype> </match> <match name="Juventus v Torino" time="15/02/2011 20:45"> <bettype name="Versus (with Draw)"> <bet outcome_name="Juventus" odd="2.00"> <bet outcome_name="X" odd="3.00"> <bet outcome_name="Torino" odd="2.00"> </bettype> <bettype name="Half Time"> <bet outcome_name="1" odd="2.40"> <bet outcome_name="X" odd="3.40"> <bet outcome_name="2" odd="1.40"> </bettype> </match> </league> <league name="Spain" id="2"> <match name="Barcelona v Real Madrid" time="15/03/2011 21:45"> <bettype name="Versus (with Draw)"> <bet outcome_name="Barcelona" odd="1.87"> <bet outcome_name="X" odd="3.40"> <bet outcome_name="Real Madrid" odd="4.00"> </bettype> </match> </league> im trying to parse attributes of above xml with using xpath functions. what i want to output is this: ( <bettype name="Half Time"> this will be ignored ) Italy AC Milan v Palermo 1.87 3.40 4.00 Juventus v Torino 2.00 3.00 2.00 spain Barcelona v Real Madrid 1.87 3.40 4.00 im trying do this with below xpath codes $xml=simplexml_load_file('http://xml.gamebookers.com/sports/football.xml_attr.xml'); $league=$xml->xpath("//league"); $matches=$xml->xpath('//bettype[@name="Versus (with Draw)"]/..'); $odds=$xml->xpath('//match/bettype[@name="Versus (with Draw)"]/bet'); i searched and tried lots of tutorials. i need help in writing the correct code thanks I am trying to write a more elegant solution to be able to check an object, find only the properties in an object that have values, and update those values in a database with a matching ID. I am extending a class from a generic user class here is an example of my code Code: [Select] <?php require_once('User.php'); require_once('Database.php'); class Vendor extends User { protected static $vendor_attributes = array('id', 'nothing' , 'tagline' , 'bio'); protected static $table_name = "user_vendors"; public $tagline; }//close class ?> Hi, I have been trying to improve my PHP programming skills by following the Lynda.com Beyond the basics tutorial and they came to a section where they were building common database methods inside a database class. Since they did not have PHP 5.3 (Where late static bindings is introduced) they had to place code referring to self:: inside of each class that needs this functionality. It seems that not having late static binding was binding self to the database class and not to other classes that call it statically. I will insert some code to explain this better. Long story short, I was really interesting in getting an attributes function working and as I do not have late static bindg either, I cannot figure out how to call it from inside a class to make it function correctly. Here is some code. Below is the attribute class they wrote. Each class declared an array of attributes for each of the classes that want to call this method like protected static $db_fields = array('id', 'email', 'password', 'etc'); Code: [Select] protected function attributes() { // return an array of attribute names and their values $attributes = array(); foreach(self::$db_fields as $field) { if(property_exists($this, $field)) { $attributes[$field] = $this->$field; } } return $attributes; } They planned on moving this code to a DatabaseObject class after they get LSB but until then, have to include it in every class that wants use this. Is there any way to write this as a function, include it in a class, and call the method without late static binding.. or even place this inside a database class and call it from another class without LSB? Forgive me if I am not explaining this correctly, again, I am still learning. My version of PHP is 5.2.6. hi, baiscally i have a products that go into the products mysql and get called by php but with each product there are different options, e.g. mens jumper - comes in sizes m,l,xl,xxl mens jeans might only come in s, m, l shoes are in 6,7,8,9,10,11 my question is how do i make a drop down list different for each product, when there all in the same db, if some one can reccomend a tutorial or a concept, i would really appreciate it thank you Hello. I am rolling my first-ever e-commerce site, and could use some help on designing a product gallery. My site will be selling books and guides, and similar to what you might see on Amazon or Barnes & Noble, I want to create a product gallery which displays all products for a given category. For simplicity, let's say that I am only selling paper books, and that is what I want to display - so for the purposes of this conversation, no need to filter on product type. When a user clicks on the product catalog, I was thinking of simply displaying all products (e.g. eBooks) in gallery containing thumbnails in a grid arrangement. The user would click on the thumbnail - which would be the cover of the book - and then be taken to a product page which would have all of the details, including: a larger thumbnail of the book, book title, description, price, author, etc. I suppose I could have a test title and description below each thumbnail? Anyways, I am a little uncertain of how all of this would work from a technical standpoint?! I guess I was thinking that each thumbnail would have a link behind it, which would then load my "product_details.php" page AND pass along something like a "ProductID" in the URL, so that my product_details.php" script could query my database and pull up the book's details. How does that sound? I look forward to hearing what you PHP gurus have to say!! 🙂
Hello. I just created a product gallery containing thumbnails of items that I will be selling. When a user click on on of the thumbnails, I want a product details page to appear with more details about the chosen product Could use some feedback if I am going about things the right way... Step 1: User goes to my gallery located he www.mysite.com/store/product-gallery.php Step 2: System displays a page of thumbnails representing items that I am selling. Step 3: User click on a given thumbnail which is a hyperlink to: www.mysite.com/store/products/4571 Step 4: System rewrites the URL as such: www.mysite.com/store/products.php?sku=4571 Step 5: System queries MySQL and retrieves record for sku 4571 Step 6: System displays product details for the chosen item in Step 3 which is sku 4571
How does that sound?
i have shopping cart i need to make the related product section in which i can show the related product when user view the product details. do i need to create any table for it ? please guide me about it. thanks I have a task that seems to be complex.
Short Description: currently users of the application I am hired to develop have two steps to do when using the app:
1. Select a Product Line (A, B, C, D)
2. Select input parameters for that product line - all product lines have simlar "Main" input parameters, but also each line has its own special features that can be selected.
3. Selections for that product line are shown - the result is a long table or options for that particular product line. Things like price, discounts, product specifications, etc.
What the users want now is this:
1. Select input parameters (not sure how to handle individual product lines special parameters yet)
2. Selections for all product lines are shown
The code base is legacy code, with code thrown around everywhere. One idea me and my coworkers have been considering is a complete rewrite, since it will help us with writing tighter code, and do what the customer wants. But that will also take time, and there is no spec. The spec is in the code mess.
Another one is I am considering now is a "merge". Somehow merge the product lines, since we have the separate product modules (A, B, C, D), there must be a way to consider maybe extending one to include the others, or somehow get me to the end result -- allow users to see selections for all product lines.
Do you have any experience, any suggestions on how to do this? I know this needs details, and details are in my code that you don't see, and most likely won't have the time to read and understand anyway.
But I am looking for any ideas or encouragement though that may help. And my question is -- is there any kind of procedure or technique or something to deal with the problem I am facing -- merging several separate yet similar modules into one single merged module. How do I approach this, what are some things that could help, etc. That's what I'm looking for.
My table looks like this.. `guns_id` int(255) NOT NULL auto_increment, `guns_name` varchar(255) collate latin1_general_ci NOT NULL, `guns_price` int(255) NOT NULL, PRIMARY KEY (`guns_id`) I want to add a product key that is unique through out the whole database as I have other products other than guns aswell. |