PHP - Best Method?
The following query code works correctly, however, I'm trying to figure out which is best when working with themes, templates, content pages. My themes are my different versions of the main site designs. As of right now I have the following code plus the database structure.
site_themes - id, theme_name, status_id (only one theme can have a value of 1(active) at any given time) site_templates - id, template_name, header_code, footer_code, status_id (any can have a value of 1(active) at any given time, Code: [Select] <?php require("kowmanager/config/database.php"); $site_variables_query = "SELECT * FROM site_variables WHERE id = '1'"; $site_variables_result = mysqli_query($dbc, $site_variables_query); $row = mysqli_fetch_array($site_variables_result, MYSQLI_ASSOC); $site_theme_query = "SELECT * FROM site_themes WHERE status_id = '1'"; $site_theme_result = mysqli_query($dbc, $site_theme_query); $row2 = mysqli_fetch_array($site_theme_result, MYSQLI_ASSOC); if ($row['site_is_down'] == 'Yes') { } else { echo "site is up"; } ?> Similar Tutorials
My script has 3 classes (that are relevant to this discussion): DB, User and Validate. They are all in independent files and loaded automatically, when required, by an autoloader.
The error messages I am getting a Any pointers as to what I am doing wrong, or what I should be doing, would be most welcome. Hi there, I want to allow the ability for DJ's to turn on and off radio requests. Now obviously I've encorporated a check box and submit button within a PHP login. But I was wanting to know if this can be done with PHP or is a database required as the option will need to be remembered for a period of time. I'd probably look to do it by making it display on a page 'requests enabled' if enabled and a blank page if disabled. therefore I could encorporate: <?php if(!empty($requests)) { //requests template } else { //radio requests disabled template } ?> What's the best method for this? Thanks Hi, I have a problem and can't seem to figure out how to do it.. Basically i have these 2 tables: Quote People Pid Pname Pdateadded Pdeleted And.. Quote Quote: PeopleCon PCid Pid PCorder Pdateadded Pdeleted Now, currently i insert the data into a table "People".. like you guys have helped me with.. But what i need to do is, first check to see if the author already exists in the People table, if so then just INSERT into PeopleCon, ELSE INSERT into both People and PeopleCon... Also if there are 4 authors, and 2 exist in People, and 2 do not. What needs to happen is the first 2 are simply inserted into PeopleCon, but the last 2 are INSERTED into both People and PeopleCon. When the authors are inserted into PeopleCon, the PCorder row needs to increment by the number of authors byt order of author. So this is the logic: Multiple authors are entered in textboxes Fire the script Check to see if author already exists in "People" table IF it does exist, INSERT into PeopleCon table ELSE do the insert into the People AND PeopleCon table, first it will INSERT into the People, and GET the MAX (ID) and insert into the PeopleCon So i currently have this, but as 3 separate methods: class People { public function checkNameExists(){ $query = "SELECT * FROM People WHERE Pname = '". mysql_real_escape_string($_POST['author'])."'"; $result = mysql_query($query); if(mysql_num_rows($result) > 0): $row = mysql_fetch_array($result); return true; else: return false; endif; } public function insertAuthor(){ $callback = create_function('$author','return "(\'".mysql_real_escape_string($author)."\',NOW(),0)";'); $sql = sprintf( 'INSERT INTO People (Pname, Pdateadded, Pdeleted) VALUES %s' ,implode(',',array_map($callback,$_POST['author'])) ); $result = mysql_query($sql); return "Successfully added NEW author"; } public function insertAuthorCon(){ $sql = "INSERT INTO PeopleCon (Pid, PCorder, PCdateadded, PCdeleted) VALUES ( 'MAX ID WILL GO HERE', 'INCREMENT OF ORDER GOES HERE', now(), 0 )"; $result = mysql_query($sql); return "Successfully added existing author"; } But obviously i need to combine these together into one method to match what i am trying to achieve.. Can anyone point me in the right direction? Thanks again... here is what i am trying to do. i have a url in my browser like this: http://localhost/jmla/index.php?option=com_content&view=article&id=1295:sovereign-a-country-risk-workshop as usuall we get elements form the url using the $_GET method, but here when i try to get id from the above url. i can get 1295:sovereign-a-country-risk-workshop. whereas the id is only 1295 and the other part is alias which i want to get seperately. is there a way to do so? I am trying to insert the current Date/Time into mysql database using the following code. I do not understand how $submitDate & $submitTime are to be set. Will this work as coded? Code: [Select] <?php class SubmitDateRecord { const DB_TABLE = 'timesheet'; const DB_FIELD_SUBMIT_TIME = 'submit_time'; private $submitDate; private $submitTime; public function setSubmitDate($submitDate) { $this->submitDate = $submitDate; } public function getSubmitDate() { return $this->submitDate; } public function setSubmitTime($submitTime) { $this->submitTime = $submitTime; } public function getSubmitTime() { return $this->submitTime; } public function addRecord() { $insertTable = "`".self::DB_TABLE."`"; $insertFields[] = "`".self::DB_FIELD_SUBMIT_TIME."`"; $insertValues[] = "'{$this->submitDate} {$this->submitTime}'"; $sqlBuilder = new SQLQBuilder(); $query = $sqlBuilder->simpleInsert($insertTable, $insertValues, $insertFields); $dbConnection = new DMLFunctions(); $result = $dbConnection->executeQuery($query); if ($result) { return true; } else { return false; } } private function _buildRecordObjects($result) { while ($row = mysql_fetch_array($result)) { $submitdateObj = new SubmitDateRecord(); $submitdateObj->setAttendanceId($row['attendance_id']); $submitdateObj->setEmployeeId($row['employee_id']); /* $row['submit_time'] comes in '0000-00-00 00:00:00' format. * We want date in '0000-00-00' format and time in '00:00' format. */ $tmpArr = explode(' ', $row['submit_time']); $submitdateObj->setSubmitDate($tmpArr[0]); $submitdateObj->setSubmitTime(substr($tmpArr[1], 0, 5)); // Omiting 'seconds' part is ok since it is always zero $submitdateObj->setStatus($row['status']); $submitdateArr[] = $submitdateObj; } return $submitdateArr; } } Hi There, I am trying to implement a facebook plugin into my website. When the user posts a link to my site on their wall it will redirect them back to my page with some GET info in the URL eg. www.example.com/download.php?post_id=43221. I don't need to know the Post Id number, I just need to know if they went to the facebook page. So my question is, how would I make it s that if there is a Post ID number it displays the page and if not it directs them to another page? Please help me with this, i'm totally stumped. Thanks George Bates Hi all, What is the maximum size of data that we can pass through GET Method? And can we increase its size ? I know I'm posting this inside the PHP coding board but I'm curious on how most handle this situation. I have a page that uses php to retrieve data from my database and I want to have it place a | in between each of the returned data which it does but it still places one after the last returned row. I'm wondering if I should do this with jquery load and then have it place that character in between each of the data or if there's a way to do it with php or what? Any ideas? Code: [Select] <?php require ("../header.php"); ?> <div id="titlehistory" class="content"> <h1 class="pageheading">Title History</h1> <?php $titlesQuery =" SELECT titles.titleName, titles.shortName FROM titles WHERE titles.statusID = 1 ORDER BY titles.ID"; $titlesResult = mysqli_query($dbc,$titlesQuery); ?> <p><span class="minilinks"> <?php while ( $row = mysqli_fetch_array ( $titlesResult, MYSQLI_ASSOC ) ) { $fieldarray=array('titleName','shortName'); foreach ($fieldarray as $fieldlabel) { ${$fieldlabel} = $row[$fieldlabel]; } echo '<a href="/titlehistory/'.$shortName.'">'.$titleName.'</a> |'; } ?> </span></p> <p class="nohistory">Please select a title to view.</p> </div> <?php require ("../footer.php"); ?> I have written a method that gathers data from several tables in my database and builds a ad out of the information then returns multidimensional array for each ad like this: $ad[0] $ad['title'][0] $ad['price'][0] $ad['description'][0]...etc The method i have looks something like this: function makeAd($id=null){ //if ad id is given then only get that ad if($id != NULL) { $where = "WHERE ad_id = $id"; } else {$where = "";} $sql = "SELECT * FROM ads $where"; $query = mysql_query($sql); //use while loop to make ad while($ret_val = mysql_fetch_array($query, MYSQL_ASSOC)): //get ads category, subcategory and images etc from other tables $cat_query = mysql_query("SELECT cat_name FROM categories WHERE $category_id = ".$ret_val['category_id']); $value = mysql_fetch_array($cat_query,MYSQL_ASSOC); $category = $value['cat_name']; $sub_query = mysql_query("SELECT sub_name FROM categories WHERE $subcategory_id = ".$ret_val['subcategory_id']); $value = mysql_fetch_array($sub_query,MYSQL_ASSOC); $category = $value['sub_name']; $cat_query = mysql_query("SELECT image_name FROM categories WHERE $ad_id = ".$ret_val['ad_id']); while($value = mysql_fetch_array($cat_query,MYSQL_ASSOC)): //loop to get all images for ad $image = $value['image_name']; endwhile; //make ads array $ad = array( 'tilte'=>$ret_val['title'], 'price'=>$ret_val['price]', 'desc'=>$ret_val['description'], 'category'=>$category, 'subcategory'=>$subcategory, 'images'=>$image ); endwhile; //return completes ad(s) return $ad; } Then I loop through the returned array like this... include(myClass.php); $class = new myClass(); $ads = $class->makeAd(); foreach($ads as $ad): echo '<ul>' echo '<li>'.$ad['title'].'</li>'; echo '<ul><li>Price: '.$ad['price'].'</li>'; echo '<li>Category: '.$ad['category'].'</li>'; echo '<li>Subcategory: '.$ad['subcategory'].'</li>'; echo '<li>Description: '.$ad['description'].'</li>'; foreach($ads['images'] as $image): echo '<li>Image: '.$image['image_name'].'</li>'; endforeach; echo '</ul></ul>'; endforeach; I get no errors but I do not get correct results either just random letters and numbers for each item. I am sure it has to do with how I have handled looping through the multidimensional array but can;t sort it out. Any help/coding advice would be greatly appreciated. Please also note that the html in the loop is only there for testing/development and is just thrown together. Thanks. Mike. I have a restricted page for members of a website. This restricted area is within a directory called 'download.' There is a login form on two pages (home and support pages, found in the main menu). These pages are on the site root directory. When the user successfully logs in they are taken inside the download directory to index.php. This index.php has a different look to the site root design. I have since redesigned this page to have the same structure as the site root pages. I would love for the user to able to navigate around the main site if they wanted, and when they clicked support in the menu they would have all the download files there on the page, instead of a login form. My question is how would I implement this login so that when the user logs in the support page changes from the login page to the page with the files. I don't want to to duplicate the site within the download directory, I was hoping for an efficient method, but I am unsure how to go about it. Hi All, hopefully someone can lend me some insight with a problem I'm stuck with. What I have is two tables. TABLE: investmentOfferings id: Unique identifier class: Class of offering (A, or AA) year: Year of offering name: Friendly name of offering units: Amount of units added in this offering dollarPerUnit: Dollar value of one unit in this offering warrant: Boolean for warrant or no (0=no 1=yes) TABLE: actualInvestments id: Unique identifier investor: Identifies investor by referencing investors>id dollarAmount: Dollar amount invested in this offering class: Identifies class by referencing investmentOfferings>id The structure of the application is so. investmentOfferings creates 4 fundraisers. Each year a new one. The actualInvestments table is the investment contributed per offering. Essentially what I need to do is to create a report, per investor(investors have a third separate table) that shows the amount invested per offering. The kicker being: not every investor will invest every offering, but I still needs to show a 0 dollar amount. I understand that I could create separate 0 dollar investments for each investor, but that seems impractical. Especially where there will be more offerings once I'm finished working on this. In terms of the report, here's what I'm doing to output the data to a table. Code: [Select] <?php do {?> <tr> <td><?php echo $row_offerings['name']?></td> <td><?php echo $row_offerings['dollarAmount'];?></td> <?php while ($row_offerings = mysql_fetch_assoc($offerings)); ?> This creates a new column in the table for each part of my array. The issue I think is in my query. Code: [Select] "SELECT * FROM actualinvestments AS a RIGHT JOIN investmentofferings AS i ON i.id=a.offering WHERE class='AA' AND investor=" . $investorID . " OR investor IS NULL"Ive tried variations on this, but cannot seem to find anything that will produce currently entered investments, and placeholders for offerings with no investments. Could anyone steer me in the right direction? Any help would be greatly appreciated. This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=353752.0 I have an error that I seem to find curious. Let me explain what I have. I have a Database class that has a function (the culprit) that is called fetchAll. It is suppose to call the mysqli method mysqli_result::fetch_all(). This method does exist, I have looked it up: The PHP Manual, however do note the last comment on the page, it describes my problem, but does not explain how I can fix it. Now, here is my error: Quote Fatal error: Call to undefined method mysqli_result::fetch_all() in /var/www/core/includes/Database.php on line 36 Here is line 36: $row = $this->result->fetch_all($mode); Here is the entire function, or is it called a method since it is in a class? function fetchAll($mode = 'MYSQLI_ASSOC'){ $row = $this->result->fetch_all($mode); return !empty($row) ? $row : array();//if not empty return row, else return an array? } I could post the entire class, but I think it might be irrelevant so I will spear you guys. Do you guys think you might be able to help me out? Thanks! Hi all. I'm working on a script to handle processing of several forms. The issue I've run into is I cannot figure out how to execute a loop and get all of those results into a variable(query). I can't quite seem to wrap my head around the idea. Here's what I have thus far... $new_post_array = array(); foreach ($_POST as $param) { $new_post_array[] = $param; }; print_r($new_post_array); The following is what I think i may need to do... $new_post_array = array(); foreach ($_POST as $param) { $new_post_array[] = $param; }; $i=1; $sql="INSERT INTO $new_post_array[0]("; //$_new_post_array[0] holds the table name; while($i<count($new_post_array)){ $sql=$sql . $new_post_array[$i]; //concat the first part of the sql with the field names } $sql=$sql . ")values("; while($i<count($new_post_array)){ $sql=$sql . $new_post_array[$i]; //concat the second part of the sql with the values } $sql=$sql . ")"; //close the sql I realize this is a huge mess...but I can't figure out an easier way to do it as of yet. Any help would be MUCH appreciated. (Side note: I just realized that the first portion of the sql statement where I give the field names is incorrect in that it will put the values instead of the field names I need. That's simple enough to fix so please ignore that error. My primary goal is to get the $sql statement constructed as efficiently as possible.) Hi. I am a little confused about PDO, its classes and the general oop aspects of it. If you at the below code:
<?php try { $handler = new PDO('mysql:host=127.0.01;dbname=app', 'root',''); $handlser->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); }catc(PDOException $e) { echo $e->getMessage(): die(); } $query = $handler->query('SELECT * FROM table'); while($r = $query->fetch(PDO::FETCH_OBJ)) { echo $r->message; }What's confusing me is that the fetch method is a method within the PDOSTATEMENT class so how come an object hasn't been created before hand in order to use the method? Furthermore it appears the method is a static method within the PDOSTATEMENT class so how come the double semi colon is being used such as: PDOSTATEMENT::FETCH? Any help would be appreciated. Thanks. I am printing question id and corect answers and incorrect one. Example: Questionid =8 Incorrect Incorrect Incorrect Correct Correct Incorrect This will be repeated for other question id. Now I would like to count total answers. In my example it will be 6. I would like to count the correct one so that will be 2. And print 2 as outcome. So far I have Code: [Select] $sqlll=questionid(); while($infoo = mysql_fetch_array( $sqlll)) { echo "<hr><br><strong>{$infoo['Que_ID']}</strong><br />\n"; $_Session1=$infoo['Que_ID']; $que=question($_Session1); while($infooo = mysql_fetch_array( $que)) { $answer1 = $infooo['Que_Answer1'] == $infooo['Ans_Answer1']; $answer2 = $infooo['Que_Answer2'] == $infooo['Ans_Answer2']; $answer3 = $infooo['Que_Answer3'] == $infooo['Ans_Answer3']; $answer4 = $infooo['Que_Answer4'] == $infooo['Ans_Answer4']; if ( $answer1 && $answer2 && $answer3 && $answer4) { echo ('<b><p style="color: green; text-align: left"> Correct </p></b>'); $scoree = $scoree + 1; } else { echo ('<br><b><p style="color: red; text-align: left"> Incorrect </p></b></br>'); $intt= $intt +1; } } $ error = trim( strip_tags($_GET['error']) ); VS $strip_error = strip_tags($_GET['error']) ; $trim_error = trim($strip_error);Which method is correct way? Also I am first striping and trimming is it wright way. could you please advice me. Thank you Edited by thilakan, 16 October 2014 - 05:50 AM. Hi I am having this error while running my php script using ajax. Everything seems to be fine but I do not know why it is giving this error. Code: [Select] <br /> <b>Notice</b>: Undefined index: amount in <b>C:\wamp\www\...\add_bid.php</b> on line <b>3</b><br /> {"error":"yes","fieldErrors":null} Here is my code here is .php code which contains the form Code: [Select] <?php session_start(); $auctionid = $_POST['auction_id']; include "design/header.php"; include "DB/db.php"; ?> <div class="contents" id="bid_contents"> <?php $q = "SELECT * FROM bids WHERE productid='$auctionid' ORDER BY bidid DESC LIMIT 0,1"; $query = mysql_query($q) or mysql_error(); //echo $q; $row = mysql_fetch_assoc($query) or mysql_error(); $current_bid = $row['current_bid']; $thumbnail = mysql_query("SELECT * FROM products WHERE productid='$auctionid'"); $row_thumb = mysql_fetch_assoc($thumbnail); $thumb = $row_thumb['thumbnail']; $title = $row_thumb['product_title']; ?> <div id="thumb"> <img src='<?php echo $thumb ?>' border='none' /><br /> <?php echo $title."<br />"; echo "<b>Current Bid:</b> Eur ".$current_bid; ?> <form name="bid_form" id="bid_form"> <input type="text" name="amount" size="5" /> <input type="button" name="place_bid_btn" id="bid_btn" value="Place Bid" /> <div id="message"></div> </form> </div><!-- thumb --> </div> <?php include "design/footer.php" ?> here is .js file for ajax Code: [Select] $(function() { $('#bid_btn').click(function() { var url = 'add_bid.php'; var query = $('#bid_form').serialize(); alert(query); $.ajax({ type: 'POST', url: url, query: query, dataType: 'json', success: function(data) { if(data.error == 'no') { $('#message').css('display','none'); } else { $('#message').html(data.fieldErrors).css('display','block'); } } }); }); }); and here is where i get data from previous .php file and the problem seems to be in this page. I guess. Name of this page is add_bid.php Code: [Select] <?php session_start(); $bid = $_POST['amount']; $error = 'yes'; $msg = $bid; $JSON_array = array('error' => $error, 'fieldErrors' => $msg); $JSON_response = json_encode($JSON_array); header('Content-type: application/json'); echo $JSON_response; ?> I am adding jquery library and javascript file in my header.php file so it is fine. Please help I found class on the net, and i am having a bit of a problem to understand how does update method works. Here is the code: Code: [Select] public function update() { global $database; // Don't forget your SQL syntax and good habits: // - UPDATE table SET key='value', key='value' WHERE condition // - single-quotes around all values // - escape all values to prevent SQL injection $attributes = $this->sanitized_attributes(); $attribute_pairs = array(); foreach($attributes as $key => $value) { $attribute_pairs[] = "{$key}='{$value}'"; } $sql = "UPDATE ".self::$table_name." SET "; $sql .= join(", ", $attribute_pairs); $sql .= " WHERE id=". $database->escape_value($this->id); $database->query($sql); return ($database->affected_rows() == 1) ? true : false; } I have form like this to deal with update: Code: [Select] <form action="index.php?page=languages" enctype="multipart/form-data" method="POST"> <?php foreach($language as $lang){ ?> <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max_file_size; ?>" /> <label>Jezik</label><input type="text" size="50" name="language" value="<?php echo $lang->lang; ?>" /><br> <input type="hidden" name="id_lang" value="<?php echo $lang->id_lang; ?>" /> <label>Slika</label><input type="file" name="image"><?php echo "<img src=\"../images/"; echo $lang->image; echo "\">"; ?> <br> <label>Pozicija</label><input type="text" name="pozicija" value="<?php echo $lang->pozicija; ?>" size="2" /></p> <br> <input type="submit" name="submit_update" value="Unesi"> <?php } ?> </form> and code to start the function: Code: [Select] if(isset($_POST['submit_update'])) { $language = new Jezik(); $language->update(); } What next??? I have a massive form (300+ fields) submitting post data that I wish to write to an xml. The hierarchy will vary from node to node ie: Code: [Select] <E02> <E02_02>value</E02_02> <E02_03>value</E02_03> <E02_04_0> <E02_04>value</E02_04> <E02_05>value</E02_05> </E02_04_0> </E02> I'm not sure how necessary that example was, but anyways... The nodes and the data in them will be different all of the time, I plan to deal with the structural differences with a really big switch/case. So my questions a 1) Whats is the advantage of using something like simplexml to write the xml, as apposed to just writing it out in a string, and saving it as a .xml file? 2) If I shouldn't write it out as a string, what method would you guys suggest, keep in mind there will be a lot of values to store, in many different parent elements (xml->emdata->header->record->E02->E02_04_0->E02-02) |