PHP - Keeping It Separately With Object Oriented Programming
I have this image upload script he
<?php if (isset($_POST['submit'])) { $j = 0; //Variable for indexing uploaded image $target_path = $_SERVER['DOCUMENT_ROOT'] . "/ubergallery/multiple_image_upload/uploads/"; //Declaring Path for uploaded images for ($i = 0; $i < count($_FILES['file']['name']); $i++) {//loop to get individual element from the array $validextensions = array("jpeg", "jpg", "png"); //Extensions which are allowed $ext = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.) $file_extension = end($ext); //store extensions in the variable $target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext) - 1];//set the target path with a new name of image $j = $j + 1;//increment the number of uploaded images according to the files in array if (($_FILES["file"]["size"][$i] < 100000) //Approx. 100kb files can be uploaded. && in_array($file_extension, $validextensions)) { if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {//if file moved to uploads folder echo $j. ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>'; } else {//if file was not moved. echo $j. ').<span id="error">please try again!.</span><br/><br/>'; } } else {//if file size and file type was incorrect. echo $j. ').<span id="error">***Invalid file Size or Type***</span><br/><br/>'; } } } ?>This script also uses javascript for multiple uploading of images. I am looking to add a query to this where I am looking to have the image file names stored in the database. The original image file name should get stored as well, yet the file name itself should get a unique id. I may have to build this query inside this upload script. I was wondering if I can keep that separately with Object Oriented Programming, if somebody just could show me "how it could look like", when it comes to having this done with Object Oriented Programming, I would appreciate it a lot. Similar TutorialsHey,
I have really looked around and done the research on books and video tutorials about object oriented programming, though I am having difficulties to find something good which gets myself started.
Could somebody recommend me a good book or video tutorials, where I could get started with when it comes to Object Oriented Programming. I am looking to use Object Oriented Programming for building a blog website.
Hi I am currently mostly learning procedural PHP but had a question about security.
Are hackers able to see connections to databases in procedural programming? Would connections to databases need to be called from classes and methods instead? Or does it not matter that much? Hi all, have constructed a blog through some tutorials which will add and delete messages. I wish to add some form of confirmation box with a yes/no button before deleting but am not sure where to begin. Thanks for any help <?php // Command_BlogDelete.php //############################################################################ // SearchVenueCommand class //############################################################################ class Command_BlogDelete extends Command { //############################################################################ // doExecute //############################################################################ function doExecute(Request $request) { // Get data from request $id = $request->getProperty('id'); // Create manager object $manager = new ManagerMessage(); // Add to database $manager->deleteMessage($id); // Redirect to index header("location:index.php"); } } ?> Hi everyone, It was recommended that I should make the switch from using procedural code to object oriented code with pdo for queries and such. So, I have been doing some reading on both topics, but am finding it rather hard to wrap my head around. I managed to get a PDO query to work with the help of a tutorial that I found online. My next step is to create an object oriented member registration class. I was wondering if anyone on here could provide any advice as far as the setup goes. I will want my member class to be able to: 1) connect to db 2) gather, validate, and send user data to payment processor 3) receive postback data, insert into database, and notify new member. I have already created these functionalities for other websites using procedural coding so once I get pushed in the right direction I should be find to add the other functionalities, which will include 4) Logging a member in 5) Logging a member out 6) Update member information 7) Change password Forgot password 9) Cancel membership Below is my snippet of PDO code that I wrote. Let me know if you guys would do anything differently. I really appreciate your help in this. Code: [Select] <?php // DECLARE DATABASE CONNECTION VARIABLES // $host = 'localhost'; $database = 'database'; $username = 'user'; $password = 'password'; // CONNECT TO DATABASE // try { $connect = new PDO("mysql:host=$host;dbname=$database", $username, $password); } catch(PDOException $e) { echo $e->getMessage(); } $sql = "SELECT siteInfoPage, siteInfoKeywords, siteInfoDescription FROM siteInfo WHERE siteInfoPage = '$page'"; // FETCH INTO A PDOStatement OBJECT // $query = $connect->query($sql); // ECHO THE NUMBER OF COLUMNS // $data = $query->fetch(PDO::FETCH_OBJ); // ASSIGN TO VARIABLES $page_title = $data->siteInfoPage; $keywords = $data->siteInfoKeywords; $description = $data->siteInfoDescription; // CLOSE THE DATABASE CONNECTION // $connect = null; ?> Hello, I have some questions here on PHP Object-Oriented. I started learning PHP Procedural since some months, and I am doing quite well. I want to start with PHP Object-Oriented now, but the problems, I have not found a good easy readable tutorial on it. I have watched some videos on YouTube, but the way they explained it made me confused. I want to know something from you, if you are an experienced PHP programmer. I want to work on CMS like Drupal, WordPress, Magento and Prestashop because I have noticed a rise in job availability in these fields in my country. 1/ Is it necessary to know PHP Object-Oriented to work as Drupal, Magento or Prestashop developers? (Note: I have a blog on WordPress, and I have huge experienced on the Dashboard, configurations and so on...) 2/ Can I start learning frameworks like CodeIgniter without learning PHP Object-Oriented? Thank you.. Perhaps the questions may have not sense for you, but I just want to know your opinions. Please, if you are an experienced programmer, you reply me. This topic has been moved to Miscellaneous. http://www.phpfreaks.com/forums/index.php?topic=306162.0 This topic has been moved to Miscellaneous. http://www.phpfreaks.com/forums/index.php?topic=327921.0 Hi, i am trying to add another propertie to the CDproduct class but everytime i keep coming up with an error: can anybody help please, here is the code below, i know it is something simple but i cannot figure it out, thanks in advance: Code: [Select] <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=windows-1250"> <meta name="generator" content="PSPad editor, www.pspad.com"> <title></title> </head> <body> <?php class ShopProduct { public $title; public $producerMainName; public $producerFirstName; public $price; function __construct($title, $firstName, $mainName, $price) { $this->title = $title; $this->producerFirstName = $firstName; $this->producerMainName = $mainName; $this->price = $price; } public function getProducer() { return "$this->producerFirstName $this->producerMainName"; } public function getProductDetails() { $s = "$this->title ($this->producerFirstName $this->producerMainName)"; return $s; } } class CdProduct extends ShopProduct { public $playLength; // Let's override the constructor function __construct($title, $firstName, $mainName, $price, $playLength) { parent::__construct($title, $firstName, $mainName, $price); $this->playLength = $playLength; } function getPlayLength() { return $this->playLength; } // Let's override getProductDetails function getProductDetails() { $s = parent::getProductDetails(); $s.= " - playing time : $this->playLength"; return $s; } public $starsign; // Let's override the constructor function __construct($title, $firstName, $mainName, $price, $starsign) { parent::__construct($title, $firstName, $mainName, $price); $this->starsign = $starsign; } function getstarsign() { return $this->starsign; } // Let's override getProductDetails function getProductDetails() { $s = parent::getProductDetails(); $s.= " - zodiac sign : $this->starsign"; return $s; } } class BookProduct extends ShopProduct { public $numPages; // Let's override the constructor function __construct($title, $firstName, $mainName, $price, $numPages) { parent::__construct($title, $firstName, $mainName, $price); $this->numPages = $numPages; } function getNumberOfPages() { return $this->numPages; } // Let's override getProductDetails function getProductDetails() { $s = parent::getProductDetails(); $s.= " - number of pages : $this->numPages"; return $s; } } $CD1 = new CdProduct("Back to black", "Amy", "Winehouse", 7.99, 63, leo); $CD2 = new CdProduct("Back to bedlam", "James", "Blunt", 7.99, 51, leo); $Book1 = new BookProduct("1984", "George", "Orwell", 8.99, 352); $Book2 = new BookProduct("Never Let", "Kazuo", "Ishiguro", 7.99, 276); echo $CD1->getProductDetails()."<br>"; echo $CD2->getProductDetails()."<br>"; echo $Book1->getProductDetails()."<br>"; echo $Book2->getProductDetails()."<br>"; ?> </body> </html> I am trying to build an object-oriented interface for a website. My classes include a "Database" class with a constructor method that connects to a database and a destructor method that disconnects from the database, a child class called "Content" that will display content stored in the database, another child class called "User" that handles registration, updating user info, logging in, and logging out, etc., and a "Validator" class that will validate all forms. So far I have the database class, the content class, and the index.php page started. My problem is that I cannot get the data returned from the function (using mysqli prepared statements) to display on the main page. I have read tutorials using MySQL, but I am using MySQLi with prepared statements. Any help is appreciated. Code: [Select] Database.php /* The Database class handles connecting to and disconnecting from the database. All interaction with the database is then extended from this class. The constructor will be run automatically each time a new instance of the Database class (or one of its child classes) is made. */ abstract class Database { // assign variables to use in the constructor private $host = 'localhost'; private $user = ''; private $password = ''; private $database = ''; // define constructor method to connect to database public function __construct() { $this->connect = new mysqli($this->host, $this->user, $this->password, $this->database); // if the connection failed kill the script and display an error if($this->connect->connect_errno) { die('Critical database error: ' . $this->database->error . '. Please contact a site administrator.'); } } // define destructor method to disconnect from the database public function __destruct() { $this->connect->close(); } } Content.php require_once('Database.php'); /* This class will display all website content that is held in the database. Anything that is stored in the database that needs to be shown on the front end of the website will go through this class. */ class Content extends Database { public function pageInfo($page) { $query = $this->connect->prepare('SELECT pageTitle, pageHeading, pageContent FROM pageInfo WHERE pageName = ?'); $query->bind_param('s', $page); $query->execute(); $query->bind_result($title, $heading, $content); return $query->fetch(); // procedurally this returns the values of the bound variables which then I can use just by typing echo $variableName // if i echo the variables out inside this method, they display at the top of index.php // how do i call them into my variables to display where i want // return $query->fetch(); should return that object to main script but then how do i call those values } public function displayUsers() { } public function searchUsers() { } } index.php <?php $page = 'index.php'; require_once('modules/Content.php'); $page = new Content(); list($title, $heading, $content) = $page->pageInfo('index.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> <title><?php echo $title; ?></title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <link href="includes/style.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="scripts/cufon-yui.js"></script> <script type="text/javascript" src="scripts/arial.js"></script> <script type="text/javascript" src="scripts/cuf_run.js"></script> </head> <body> <!--begin main--> <div class="main"> <?php include('header.php'); ?> <?php include('menu.php'); ?> <!--begin content--> <div class="content"> <!--begin content_resize--> <div class="content_resize"> <!--begin mainbar--> <div class="mainbar"> <!--begin article--> <div class="article"> <h2><span><?php echo $heading; ?></span></h2> <div class="clr"></div> <p><?php echo $content; ?></p> </div> <!--end article--> </div> <!--end mainbar--> <?php include('sidebar.php'); ?> <div class="clr"></div> </div> <!--end content_resize--> </div> <!--end content--> <?php include('footer.php'); ?> </div> <!--end main--> </body> </html> I'm trying to create an object oriented PHP poll. I know I'm close but I got stuck. If anyone can help me with this. It's a radio button poll: Code: [Select] <html> <head> <title>Polling</title> <head> <body> <h1>Pop Poll</h1> <p>Who will you vote for in the election?</p> <form method=post action="show_poll.php"> <input type="radio" name="vote" value="John Smith">John Smith<br /> <input type="radio" name="vote" value="Mary Jones">Mary Jones<br /> <input type="radio" name="vote" value="Fred Bloggs">Fred Bloggs<br /><br /> <input type=submit value="Show results"> </form> </body> Here is the show_poll.php <?php /******************************************* Database query to get poll info *******************************************/ // get vote from form $vote=$_REQUEST['vote']; // log in to database if (!$db_conn = new mysqli('localhost', 'poll', 'poll', 'poll')) { echo 'Could not connect to db<br />'; exit; } if (!empty($vote)) // if they filled the form out, add their vote { $vote = addslashes($vote); $query = "update poll_results set num_votes = num_votes + 1 where candidate = '$vote'"; if(!($result = @$db_conn->query($query)))//'@' means not showing error message. { echo 'Could not connect to db<br />'; exit; } } else { echo 'You did not vote!<br />'; exit; } // get current results of poll, regardless of whether they voted $query = 'select * from poll_results'; if(!($result = @$db_conn->query($query))) { echo 'Could not connect to db<br />'; exit; } $num_candidates = $result->num_rows;//how many candidates are = the number of rows // calculate total number of votes so far $total_votes=0; while ($row = $result->fetch_object()) { $total_votes += $row->num_votes; } $result->data_seek(0); // reset result pointer ?> <h2>Result:</h2> <table> <tr> <td>John Smith:</td> <td> <img src="poll.gif" width='<?php echo(100*($num_candidates/$total_votes)); ?>' height='20'> <?php echo(100*($num_candidates/$total_votes)); ?>% </td> </tr> <tr> <td>Mary Jones:</td> <td> <img src="poll.gif" width='<?php echo(100*($num_candidates/$total_votes)); ?>'height='20'> <?php echo(100*($num_candidates/$total_votes)); ?>% </td> </tr> <tr> <td>Fred Bloggs:</td> <td> <img src="poll.gif" width='<?php echo(100*($num_candidates/$total_votes)); ?>'height='20'> <?php echo(100*($num_candidates/$total_votes)); ?>% </td> </tr> </table> the Problem:: When I click a candidate it increments the value in the database it gets recorded well but I have problem with showing the result. It doesn't show the result right. I know that the bug lays he Code: [Select] 100*($num_candidates/$total_votes)). Instead of $num_candidates variable I need to come up with another variable that is the number of votes each candidate gets. I don't know how to come up with that. Any help Please help me with this I'd like to have an object oriented solution the point is that I don't want to use "If else" statements. Thanks any help a lot in advance Hi there, I am starting to learn OO PHP programming. After running math.php, it gives an output 'Use only numbers'. Why? I don't understand this. math.php <?php require('MathClass.php'); $c = new MathClass(); echo $c->add(5,10,15,20); ?> MathClass.php <?php class MathClass{ function add(){ $args = func_num_args(); $sum = 0; $i = 0; for ($i ; $i < $args ; $i++){ is_int(func_get_args($i)) ? $sum += func_get_args($i) : die('Use only numbers'); } return $sum; } } ?> Where would you guys recommend I go to learn and become familiar with writing Object Oriented PHP code? Also what are the advantages of writing object oriented code? Is it better than the 'traditional' coding style? I mean without using Objects, Classes, Methods, etc.. Is one way more efficient than the other? I've been seeing a lot of object oriented php code lately, and I'm just curious and want to learn the concept of OOP, any help is appreciated. Thanks! -CLUEL3SS Hi, I wrote a classFile to handle files that looks like this: class classfile { //path_parths is an array, use it this way //path_parts["filename"] -> filename //path_parts["dirname"] -> directory //path_parts["extension"] //path_parts["basename"] protected $path_parts; private $fullpath; function __construct($filename){ if(file_exists($filename)){ $this->fullpath = $filename; $this->path_parts= pathinfo($this->fullpath); } else{ die("File or Folder doesn't exist"); } } function move($destination){ if (file_exists($destination)){ rename($this->fullpath, $destination . "/" . $this->getfilename()); //Update properties $this->setfullpath($destination . $this->getfilename()); $this->setpath_parts(); } else{ die("The folder specified doesn't exist"); } } function copy($destination){ copy($this->fullpath, $destination); } function getpath(){ return $this->path_parts["dirname"]; } function getfilename(){ return $this->path_parts["basename"]; } function getextension(){ return $this->path_parts["extension"]; } function getfullpath(){ return $this->fullpath; } function setfullpath($path){ $this->fullpath = $path; } function setpath_parts(){ $this->path_parts = pathinfo($this->fullpath); } function __destruct() { ; } } ?> Then I extended it with a class to handle images that looks like this: include 'c:/wamp/www/classfile.php'; class classimage extends classfile{ var $image; var $image_info; var $image_type; function __construct($filename){ parent::__construct($filename); $this->image_info = getimagesize(parent::getfullpath()); $this->image_type = $this->image_info[2]; if( $this->image_type == IMAGETYPE_JPEG ) { $this->image = imagecreatefromjpeg(parent::getfullpath()); } elseif( $this->image_type == IMAGETYPE_GIF ) { $this->image = imagecreatefromgif(parent::getfullpath()); } elseif( $this->image_type == IMAGETYPE_PNG ) { $this->image = imagecreatefrompng(parent::getfullpath()); } } function save($filename, $image_type=IMAGETYPE_JPEG, $compression=80, $permissions=777) { if( $image_type == IMAGETYPE_JPEG ) { imagejpeg($this->image,$filename,$compression); } elseif( $image_type == IMAGETYPE_GIF ) { imagegif($this->image,$filename); } elseif( $image_type == IMAGETYPE_PNG ) { imagepng($this->image,$filename); } if( $permissions != null) { chmod($filename,$permissions); } } function output($image_type=IMAGETYPE_JPEG) { if( $image_type == IMAGETYPE_JPEG ) { imagejpeg($this->image); } elseif( $image_type == IMAGETYPE_GIF ) { imagegif($this->image); } elseif( $image_type == IMAGETYPE_PNG ) { imagepng($this->image); } } function getWidth() { return $this->image_info[0]; } function getHeight() { return $this->image_info[1]; } function resizeToHeight($height) { $ratio = $height / $this->getHeight(); $width = $this->getWidth() * $ratio; $this->resize($width,$height); } function resizeToWidth($width) { $ratio = $width / $this->getWidth(); $height = $this->getheight() * $ratio; $this->resize($width,$height); } function scale($scale) { $width = $this->getWidth() * $scale/100; $height = $this->getheight() * $scale/100; $this->resize($width,$height); } function resize($width,$height) { $new_image = imagecreatetruecolor($width, $height); echo "resized to:\n"; echo $width . "\n"; echo $height . "\n"; echo "imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight())\n"; imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight()); $this->image = $new_image; } function format(){ $width = $this->getWidth(); $height = $this->getHeight(); if ($width > $height){ return "landscape"; } if ($height > $width){ return "portrait"; } if ($height == $width){ return "square"; } } function isTooBig($maxsize){ $width = $this->getWidth(); $height = $this->getHeight(); if ($width > $maxsize || $height > $maxsize){ return true; } else{ return false; } } function __destruct() { ; } } ?> Now that I got this, I loop through images located in a folder that way: if ($handle = opendir($directory)) { while (false !== ($file = readdir($handle))) { //Instantiate the object $image = new classimage($directory . "/" . $file); //And do quite a lot of verification and particularly this: if ($image->format() == "landscape") { echo "width: " . $image->getWidth() . "\n"; echo "height: " . $image->getHeight() . "\n"; if ($image->isTooBig($maxsize_mini)) { $image->resizeToWidth($maxsize_mini); $image->save($directory . "/mini_" . $image->getfilename()); } } } And now to the problem: I echo'ed the resize function to see what's being run and I got that: picture1 imagecopyresampled(Resource id #26, Resource id #25, 0, 0, 0, 0, 608, 405.65, (), ()) picture2 imagecopyresampled(Resource id #27, Resource id #26, 0, 0, 0, 0, 250, 166.796875, (), ()) It looks like it's reusing an instantiation of the previous object and so on and so forth. In my mind, the way it should look is: picture1 imagecopyresampled(Resource id #2, Resource id #1, 0, 0, 0, 0, 608, 405.65, (), ()) picture2 imagecopyresampled(Resource id #2, Resource id #1, 0, 0, 0, 0, 250, 166.796875, (), ()) The previous object is destructed, the new one has the old id. how does that work? The reason I ask and wonder about this is because I'm having weird result for the resize such as a ridiculously small picture mini size in the actual mini size picture (250 px) except whatever is left is filled with black. $date=2010-11-01 23:45:09 How do I create one variable to output Monday November 1 and another variable to display 11:45:09 PM from the above variable. I need my code to generate the following HTML: Code: [Select] div id="wowslider-container1"> <div class="ws_images"> <span><img src="https://alaskapac.centertix.net/UPLImage/aca_beauty.jpg" alt="Disney's Beauty & the Beast" title="Disney's Beauty & the Beast" id="wows0" /></span> <span><img src="https://alaskapac.centertix.net/UPLImage/ss_scaredscriptless.jpg" alt="Scared Scriptless" title="Scared Scriptless" id="wows1" /></span> <span><img src="https://alaskapac.centertix.net/UPLImage/aysc_worldcupofwines.jpg" alt="World Cup of Wines" title="World Cup of Wines" id="wows2" /></span> <span><img src="https://alaskapac.centertix.net/UPLImage/aso_outofthisworld.jpg" alt="Anchorage Symphony's Out of This World" title="Anchorage Symphony's Out of This World" id="wows3" /></span> <span><img src="https://alaskapac.centertix.net/UPLImage/aca_mikegarson.jpg" alt="Mike Garson" title="Mike Garson" id="wows4" /></span> <span><img src="https://alaskapac.centertix.net/UPLImage/ctc_pinkalicious.jpg" alt="Pinkalicious!" title="Pinkalicious!" id="wows5" /></span> <span><img src="https://alaskapac.centertix.net/UPLImage/aso_silentfilm.jpg" alt="Anchorage Symphony's Silent Film Double Feature" title="Anchorage Symphony's Silent Film Double Feature" id="wows6" /></span> <span><img src="https://alaskapac.centertix.net/UPLImage/aca_rockofages.jpg" alt="Rock of Ages" title="Rock of Ages" id="wows7" /></span> <span><img src="https://alaskapac.centertix.net/UPLImage/pdc_concert.jpg" alt="Pulse Dance Company in Concert" title="Pulse Dance Company in Concert" id="wows8" /></span> <span><img src="https://alaskapac.centertix.net/UPLImage/aca_mannheimsteamroller.jpg" alt="The Christmas Music of Mannheim Steamroller" title="The Christmas Music of Mannheim Steamroller" id="wows9" /></span> <span><img src="https://alaskapac.centertix.net/UPLImage/alex_zlatkovski.jpg" alt="Alexander Zlatkovski" title="Alexander Zlatkovski" id="wows10" /></span> <span><img src="https://alaskapac.centertix.net/UPLImage/wsp_joshritter.jpg" alt="Josh Ritter" title="Josh Ritter" id="wows11" /></span> <span><img src="https://alaskapac.centertix.net/UPLImage/z_acpa_giftcertificates.jpg" alt="Gift Certificates" title="Gift Certificates" id="wows12" /></span> <span><img src="https://alaskapac.centertix.net/UPLImage/adp_fireice.jpg" alt="New Year's Eve Celebration" title="New Year's Eve Celebration" id="wows13" /></span> </div><div class="ws_bullets"><div> <a href="#wows0" title="Disney's Beauty & the Beast"><img src="https://alaskapac.centertix.net/UPLImage/aca_beauty.jpg" alt="Disney's Beauty & the Beast" />1</a> <a href="#wows1" title="Scared Scriptless"><img src="https://alaskapac.centertix.net/UPLImage/ss_scaredscriptless.jpg" alt="Scared Scriptless" />2</a> <a href="#wows2" title="World Cup of Wines"><img src="https://alaskapac.centertix.net/UPLImage/aysc_worldcupofwines.jpg" alt="World Cup of Wines" />3</a> <a href="#wows3" title="Anchorage Symphony's Out of This World"><img src="https://alaskapac.centertix.net/UPLImage/aso_outofthisworld.jpg" alt="Anchorage Symphony's Out of This World" />4</a> <a href="#wows4" title="Mike Garson"><img src="https://alaskapac.centertix.net/UPLImage/aca_mikegarson.jpg" alt="Mike Garson" />5</a> <a href="#wows5" title="Pinkalicious!"><img src="https://alaskapac.centertix.net/UPLImage/ctc_pinkalicious.jpg" alt="Pinkalicious!" />6</a> <a href="#wows6" title="Anchorage Symphony's Silent Film Double Feature"><img src="https://alaskapac.centertix.net/UPLImage/aso_silentfilm.jpg" alt="Anchorage Symphony's Silent Film Double Feature" />7</a> <a href="#wows7" title="Rock of Ages"><img src="https://alaskapac.centertix.net/UPLImage/aca_rockofages.jpg" alt="Rock of Ages" />8</a> <a href="#wows8" title="Pulse Dance Company in Concert"><img src="https://alaskapac.centertix.net/UPLImage/pdc_concert.jpg" alt="Pulse Dance Company in Concert" />9</a> <a href="#wows9" title="The Christmas Music of Mannheim Steamroller"><img src="https://alaskapac.centertix.net/UPLImage/aca_mannheimsteamroller.jpg" alt="The Christmas Music of Mannheim Steamroller" />10</a> <a href="#wows10" title="Alexander Zlatkovski"><img src="https://alaskapac.centertix.net/UPLImage/alex_zlatkovski.jpg" alt="Alexander Zlatkovski" />11</a> <a href="#wows11" title="Josh Ritter"><img src="https://alaskapac.centertix.net/UPLImage/wsp_joshritter.jpg" alt="Josh Ritter" />12</a> <a href="#wows12" title="Gift Certificates"><img src="https://alaskapac.centertix.net/UPLImage/z_acpa_giftcertificates.jpg" alt="Gift Certificates" />13</a> <a href="#wows13" title="New Year's Eve Celebration"><img src="https://alaskapac.centertix.net/UPLImage/adp_fireice.jpg" alt="New Year's Eve Celebration" />14</a> </div></div> </div> So I assumed that it would be something similar to the following: Code: [Select] while ($Row = mysqli_fetch_assoc($carouselResult)){ $EventName = $Row['EventTitle']; $image = $Row['eImage']; /* $big_image = LISTING OF ALL IMAGES */ $big_image = array('<span><img src="https://alaskapac.centertix.net/UPLImage/' . $image . '" alt="' . $EventName. '" title="' . $EventName . '" id="wows'. $i .'" /></span>'."\n"); $i2 = $i; $i = $i+1; /* $nav_image = TINY BOXES TO NAVIGATE THROUGHOUT CAROUSEL */ $nav_image = array('<a href="#wows' . $i2 . '" title="'.$EventName.'"><img src="https://alaskapac.centertix.net/UPLImage/' . $image . '" alt="' . $EventName. '" />'.$i.'</a>'."\n"); $i2 = $i2+1; } echo '<div id="wowslider-container1">'."\n".'<div class="ws_images">'."\n"; echo array($big_image); echo '</div><div class="ws_bullets"><div>'."\n"; echo array($nav_image); echo '</div></div>'."\n".'</div>'; But array($big_image) and array($nav_image) do not work as I expected and it just produces the following HTML code: Code: [Select] <div id="wowslider-container1"> <div class="ws_images"> Array</div><div class="ws_bullets"><div> Array</div></div> </div> Can anyone help out a beginner in PHP? Hi guys, I really hope this will make sense. I am creating a dynamic field on a button click for Pickup Location. That works fine and submitting the form to the database works fine. However, instead of one entry, each time I submit the form with multiple Pickup Locations, it creates multiple separate database entries. Here is the PHP for submitting: if(isset($_POST['new']) && $_POST['new']==1){ $pickups = ''; foreach($_POST['pickups'] as $cnt => $pickups) $pickups .= ',' .$pickups; $locations = count($_POST["pickups"]); if ($locations > 0) { for ($i=0; $i < $locations; $i++) { if (trim($_POST['pickups'] != '')) { $name = mysqli_real_escape_string($con, $_POST['name']); $price = mysqli_real_escape_string($con, $_POST['price']); //$origin = $_POST['origin']; $pickups = $_POST["pickups"][$i]; $destination = mysqli_real_escape_string($con, $_POST['destination']); $dep_date = mysqli_real_escape_string($con, $_POST['dep_date']); $ret_date = mysqli_real_escape_string($con, $_POST['ret_date']); $fleet_number = mysqli_real_escape_string($con, $_POST['fleet_number']); $driver = mysqli_real_escape_string($con, $_POST['driver']); $itinerary = mysqli_real_escape_string($con, $_POST['itinerary']); $submittedby = mysqli_real_escape_string($con, $_SESSION["username"]); $trn_date = mysqli_real_escape_string($con, date("Y-m-d H:i:s")); $query="insert into tours (`name`, `price`, `pickups`, `destination`, `dep_date`, `ret_date`, `fleet_number`, `driver`, `itinerary`, `submittedby`, `trn_date`)values ('$name', '$price', '$pickups', '$destination', '$dep_date', '$ret_date', '$fleet_number', '$driver', '$itinerary', '$submittedby', '$trn_date')"; mysqli_query($con,$query) or die(mysqli_error($con)); if(mysqli_affected_rows($con)== 1 ){ $message = '<i class="fa fa-check"></i> - Record Inserted Successfully'; } } } } } Here is the HTML form: <form role="form" method="post" name="add_tour" id="add_tour" action""> <input type="hidden" name="new" value="1" /> <div class="modal-body"> <div class="row form-group"> <div class="col-6"> <div class="form-group"><label for="name" class=" form-control-label">Name</label><input type="text" id="name" name="name" placeholder="Tour Name" class="form-control"> </div> </div> <div class="col-6"> <div class="form-group"><label for="price" class=" form-control-label">Price</label><input type="text" id="price" name="price" placeholder="0.00" class="form-control"> </div> </div> </div> <div class="row form-group"> <div class="col-6"> <div class="form-group origin" id="pickupsfield"><label for="pickups" class=" form-control-label">Pickup Location</label><input type="text" id="pickups" name="pickups[]" placeholder="Start Typing..." class="form-control"></div> <button type="button" class="btn btn-success add-field" id="add" name="add">Add New Location <span style="font-size:16px; font-weight:bold;">+ </span> </button> </div> <div class="col-6"> <div class="form-group"><label for="destination" class=" form-control-label">Destination</label><input type="text" id="destination" name="destination" placeholder="Start Typing..." class="form-control"></div> </div> </div> <div class="row form-group"> <div class="col-6"> <div class="form-group"><label for="dep_date" class=" form-control-label">Departure Date</label><input type="date" id="dep_date" name="dep_date" placeholder="" class="form-control"></div> </div> <div class="col-6"> <div class="form-group"><label for="ret_date" class=" form-control-label">Return Date</label><input type="date" id="ret_date" name="ret_date" placeholder="" class="form-control"></div> </div> </div> <div class="row form-group"> <div class="col-6"> <div class="form-group"><label for="fleet_number" class=" form-control-label">Fleet Number</label> <select class="form-control" id="fleet_number" name="fleet_number"> <option value="Select">== Select Fleet Number ==</option> <?php $sql = "SELECT fleet_number FROM fleet"; $result = $con->query($sql); while(list($fleet_number) = mysqli_fetch_row($result)){ $option = '<option value="'.$fleet_number.'">'.$fleet_number.'</option>'; echo ($option); } ?> </select> </div> </div> <div class="col-6"> <?php ?> <div class="form-group"><label for="driver" class=" form-control-label">Driver</label> <select class="form-control" id="driver" name="driver"> <option value="Select">== Select Driver ==</option> <?php $sql = "SELECT name FROM drivers"; $result = $con->query($sql); while(list($driver) = mysqli_fetch_row($result)){ $option = '<option value="'.$driver.'">'.$driver.'</option>'; echo ($option); } ?> </select> </div> </div> </div> <div class="form-group"><label for="itinerary" class=" form-control-label">Itinerary</label> <textarea class="form-control" id="itinerary" name="itinerary"></textarea> </div> <div class="modal-footer"> <button type="reset" class="btn btn-warning">Clear Form</button> <button type="submit" name="submit" id="submit" class="btn btn-primary">Confirm</button> </div> </form> And the Javascript for adding the new fields: <script> $(document).ready(function(){ var i = 1; $("#add").click(function(){ i++; $('#pickupsfield').append('<div id="row'+i+'"><input type="text" name="pickups[]" placeholder="Enter pickup" class="form-control"/></div><div><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></div>'); }); $(document).on('click', '.btn_remove', function(){ var button_id = $(this).attr("id"); $('#row'+button_id+'').remove(); }); $("#submit").on('click',function(){ var formdata = $("#add_tour").serialize(); $.ajax({ url :"", type :"POST", data :formdata, cache :false, success:function(result){ alert(result); $("#add_tour")[0].reset(); } }); }); }); </script> Anyone have any idea where I am going wrong? Before you say it, Yes, I know, Use Prepared statements 😷 Edited February 6 by DanEthicalAdded tags Hi there. I have this simple code which displays 5 results. How can i grab each element separately instead of displaying all the results at once. Thanks:) Code: [Select] <?php $query = mysql_query("SELECT product_name, product_price FROM products WHERE product_type = 'laptop' LIMIT 5"); $numrows = mysql_num_rows($query); if ($numrows != 0) { while ($row = mysql_fetch_assoc($query)) { $product_name = $row['product_name']; $product_price = $row['product_price']; echo $product_name . '<br />'; echo $product_price . '<br /><br />'; } } ?> Hey all, I want to have an object that has a property which is an object containing instances of other objects. I try this: Code: [Select] class Blog extends Posts { public $has_posts; public function __construct($a,$b,$c){ $has_posts = (object) array_merge((array) $a, (array) $b, (array) $c); } } class Posts { public $b; public function __construct($b){ $this->b = $b; } } $post1 = new Posts(1); $post2 = new Posts(2); $post3 = new Posts(3); $blog = new Blog($post1,$post2,$post3); var_dump($blog->has_posts); //null foreach($blog->has_posts as $post){ //Invalid argument supplied for foreach() echo $post->b; } But as you see, has_posts is null, not an object containing other objects. Thanks for response. hello, im trying to read the database and store values into an array list. when i run the script it says undefined variable prodcode, name, price in the function prod details. any help pliz. appreciate the help. thnaks! require("dbfunctions.inc.php"); $count; class Product { // The following are the attributes of the Product class, that is, var $prodcode = array(); var $name = array(); var $price = array(); /* CONSTRUCTOR Every class has at least one constructor method. We create an instance of a class using the class's constructor */ function AllProducts() { $qry = "Select ProdCode, Name, Price, Image from products"; //execute query $products = execute_query($qry); if (!$products) {die('query failed.'); } $i = 0; global $count; $count= mysql_num_rows($products); while ($line = mysql_fetch_array($products, MYSQL_ASSOC)) { $prodcode =array ($line['ProdCode']); //$name[$i] = $line['Name']; //$desc[$i] = $line['Desc']; //$price[$i] = $line['Price']; //$category[$i] = $line['Category']; $i++; } } // Method to print the Shopping Cart details to the screen function ProdDetails() { global $count; echo $count; echo $count; for ($i = 0; $i <= $count; $i++) { //echo "<tr><td>"; echo "<br>Product Code: <a href=DisplayProduct.php?prodcode=" . $prodcode[$i]. ">" .$prodcode[$i]. "</a>"."<br>"; echo "Product Name: ".$name[$i]." <br>". "Price: FJD$ " .$price[$i]."<br>"; } } // Method to print the Shopping Cart details to the screen function getProdCode() { echo "Product Code: " . $this->prodcode . "<br>"; } } // END OF CLASS Hii.... I simply want to know the answer of a simple question "Is it possible to do Window Programming in PHP?", like C++, .net, etc.....and if so then where I can find links for the tutorials..... |