PHP - Foreach Method
I have foreach method. This displays the choices that are selected and the value inside them as 1. The method is shown below. I am printing these with the name(choice1, choice2, choice3, choic4) and the value. If there is a value then it prints 1. Now my problem is I want to INSERT them into my database. if it prints choice1, choice2 then value 1 must be entered into choice1 and choice2 inside the database. I am not sure how to do this. can someone help me.
Code: [Select] foreach ($_POST["choice"] as $question => $answer) { if($answer == NULL) { $val=0; } else{ $val = 1; } echo "choice id: $question. value: $val <br />"; 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. This topic has been moved to Application Frameworks. http://www.phpfreaks.com/forums/index.php?topic=355772.0 I'm not sure if the title explains it very well, but here is an image of it. I am trying to figure out how to access the option selected (equal, not equal, etc.), along with its input box, for each column (the checkboxes on the right) selected. The purpose of this is to allow a non-programming administrator user to create a custom query to access information. I can find out which checkboxes are selected no problem, but finding the accompanying drop-down option and input box is difficult for me. How do I do this? If you have a suggestion on how to change it, I'm very open. Thank you in advance! Code: [Select] if(!isset($_POST['submit'])) { echo " <form method='post'> <table> <tr> <td valign='top'>SELECT</td> <td valign='top'> <table>"; // LIST ALL COLUMNS IN A TABLE $result = mysql_query("SELECT * FROM table_name") or die(mysql_error()); $rowcount=mysql_num_rows($result); $y=mysql_num_fields($result); for ($x=0; $x<$y; $x++) { echo " <tr> <td> <input type='checkbox' name='fields[]' value='".mysql_field_name($result, $x)."'>".mysql_field_name($result, $x)." </td> </tr>"; } echo " </table> </td> <td valign='top'>FROM allocations</td> <td valign='top'>WHERE</td> <td> <table>"; // LIST ALL COLUMNS IN A TABLE $result = mysql_query("SELECT * FROM table_name") or die(mysql_error()); $rowcount=mysql_num_rows($result); $y=mysql_num_fields($result); for ($x=0; $x<$y; $x++) { echo " <tr> <td> <input type='checkbox' name='column[]' value='".mysql_field_name($result, $x)."'>".mysql_field_name($result, $x)." </td> <td> <select name='operator[]'> <option value='='>equals</option> <option value='<>'>does not equal</option> <option value='>'>greater than</option> <option value='<'>less than</option> <option value='>='>greater than or equal to</option> <option value='<='>less than or equal to</option> <option value='LIKE'>is like</option> </select> </td> <td><input type='text' name='criteria[]'></td> </tr>"; } echo " </table> </td> <td valign='top'><input type='submit' value='Process Query' name='submit' class='submit'></td> </tr> </table> </form>"; } else { echo "<b>Fields to edit:</b> "; foreach ($_POST['fields'] as $fields) { echo $fields,", "; } echo "<br><br>"; echo "<b>Columns to query:</b> "; foreach ($_POST['column'] as $columns) { echo $columns," HERE IS THE SPOT, "; } } 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 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 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"); ?> 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"; } ?> Hi all, What is the maximum size of data that we can pass through GET Method? And can we increase its size ? 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? 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... 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. 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 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. 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) 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! |