PHP - Self Updating Forms
Hi everyone,
I need a little help on making forms that automatically update as you select stuff, For example if you was to select something from a drop down menu, The page will update, And show a new drop down box that will list products compatible with the fiirst product, I could easily add these to arrays, Then the script could just pull from each array. Also I don't know if this will need any javascript... I am no good at that so please warn me if it does! Any kind of help would be highly appreciated, Thanks, Gergy. Similar TutorialsHello, I'm having a little trouble getting my head around my code here. Basically, I have a table based PHP form in my html page that loops and adds a new row to the table depending on my variables The table itself displays the amount of 'squads' you have, the name of the individual squads, how many people are in your squad, and an 'add button': Your Squads: | People | Form Button Squad 'name' | 2/5 | Add More? Squad 'name' | 3/5 | Add More? Squad 'name' | 1/5 | Add More? Etc ..... Code for this table: Code: [Select] <p><strong> Add Soliders To Squads:</strong> <br />Soliders avalible: <? echo $solidersToAdd ?> <form action="<?php echo $_SERVER['PHP_SELF']?>" method="post"> <table width="500" border="0" cellspacing="0" cellpadding="0"> <?PHP $max = $squadNumbers - 1; $i = 0; while($i <= $max){ $print = $i + 1; echo"<tr>"; echo"<td width=\"200\" height=\"30\"><strong>Squad: ".$names_split[$i]."</strong></td>"; echo"<td width=\"200\" height=\"30\">".$content_split[$i]."/5</td>"; if($content_split[$i] != 5){ echo"<td height=\"30\">"; echo"<input name=\"submitAdd\" type=\"submit\" class=\"SquadWeaponSelector\" id=\"submitAdd_".$i."\" value=\"Add (".$solidersToAdd.")\" /></td>"; } else{ echo"<td height=\"30\">Squad is full</td>"; } $i++; } ?> </table> </form> This all works fine, but its the action form I'm struggling with, what I want is to be able to add a person to the specific squad the user pushed the button for and add to the database. NOTE: my database stores the content (players in squad) like so: 2,3,1 as a varchar and I use explode to split it into an array (this is the same with my squad names too). So here is a snippet of what I got at the top of my document, the form action: Code: [Select] $squadNumbers = $info['squadNumbers']; // = 3 $squadNames = $info['squadNames']; // = Alpha,Beta,Oscar $squadContent = $info['squadContent']; // = 2,3,1 // split the squad content \\ $content_split = explode(",", $squadContent); // split the squad names \\ $names_split = explode(",", $squadNames); $solidersToAdd = 3; // will soon be retrieving off DB if (isset($_POST['submitAdd']) && $solidersToAdd != 0) { $i = 0; $max = $squadNumbers - 1; $newContentArray = array(); while($i <= $max){ $print = $i + 1; $newContentArray[whatever button was pressed] = 1 + $squadContent[whatever button was pressed]; $i++; } //$solidersToAdd--; $glueContent = $_POST['submitAdd_1']; //implode(",",$newContentArray); $result = mysql_query("UPDATE users SET squadContent='$glueContent' WHERE username = '$username'") or die(mysql_error()); } First of, I dont know how to have a button actually pass on a value such as '+1', and I need it to talk specifically to that squad. I would appreciate any help, many thanks in advance. I have the following code, (I'm sorry it's so long an it does more that the question asks.) It's ment to edit, delete and make new links in a mysql database, by also using a link header to home all the links (Like a dropdown menu) And thig manages the links. However then the update, or when the new form is submitted it leaves then titlereg field blank. (The titlereg is the id of the main link, it's called reg in the title_reg database) I know this is complicated and i'm not too good at explaining the problem but any help would be great. I have commented on anything that could help. <?php include "../includes/mysql_connect.php"; include "../includes/info_files.php"; echo "<strong>Links</strong><br />"; echo "Currect links:<br /><br />"; if($_POST['submit']){ $name = mysql_real_escape_string($_POST['name']); $titlereg = mysql_real_escape_string($_POST['titlereg']); $url = mysql_real_escape_string($_POST['url']); $id = mysql_real_escape_string($_POST['id']); mysql_query("UPDATE nav_sub SET name='$name', SET titlereg='$titlereg', SET url='$url' WHERE reg='$id'"); ////////////////////////////////// Here will help, the update MY SQL thingie echo "Link Changed.<br /><br />"; } elseif($_POST['remove']){ $id = mysql_real_escape_string($_POST['id']); mysql_query("DELETE FROM nav_sub WHERE reg='$id'"); echo "Link deleted.<br /><br />"; } else{ $result = mysql_query("SELECT * FROM nav_sub"); while($row = mysql_fetch_array($result)) { echo '<strong>' . $row['name'] . '</strong>'; echo '<form action="" method="post">'; echo 'Name: <input type="text" name="name" value="' . $row['name'] . '" /><br />'; echo 'Link: <input type="text" name="text" value="' . $row['url'] . '" /><br />'; echo 'Navigation title: <select name="titlereg">'; $resultabc = mysql_query("SELECT * FROM nav_title"); while($rowabc = mysql_fetch_array($resultabc)) { echo '<option value="' . $rowabc['reg'] . '">' . $rowabc['name'] . '</option>'; ////////////////////////////////// Here is the option } echo '</select>'; echo '<input type="hidden" name="id" value="' . $row['reg'] . '" />'; echo '<input type="submit" name="submit" value="Change" /> <input type="submit" name="remove" value="Remove" /><br />'; echo '</form>'; } } echo "New link:<br /><br />"; if($_POST['new_submit']){ ////////////////////////////////// Here!!!!!!!!!!!!!!! $result = mysql_query("SELECT * FROM nav_sub"); $new_titlereg = $_POST['new_titlereg']; $new_name = mysql_real_escape_string($_POST['new_name']); $new_url = mysql_real_escape_string($_POST['new_url']); mysql_query("INSERT INTO `nav_sub` (`titlereg` ,`reg` ,`name` ,`url`)VALUES ('$new_titlereg', '', '$new_name', '$new_url')"); ////////////////////////////////// here is the MY SQL statement... echo "Link added.<br /><br />"; } echo '<form action="" method="post">'; echo 'Name: <input type="text" name="new_name" value="" /><br />'; echo 'Url: <input type="text" name="new_url" value="" /> \\\\ If your linking to a page you made, then the url is index.php?catt=(The categrory you put)&page=(The page you put)<br />'; echo 'Navigation title: <select name="new_titlereg">'; $resultab = mysql_query("SELECT * FROM nav_title"); while($rowab = mysql_fetch_array($resultab)) { echo '<option value="' . $rowab['reg'] . '">' . $rowab['name'] . '</option>'; ////////////////////////////////// Here isn't submitting the value in the option } echo '</select>'; echo '<input type="submit" name="new_submit" value="Insert" /><br />'; echo '</form>'; ?> By the way, explain simply as I'm only 13 I'm back, I have a code that based on my understanding should work, but needless to say doesn't <?php $sql ="select * from `piprice`"; $result = mysql_query($sql); $count = mysql_num_rows($result); echo "<table border=1><tr><td>Product Name</td><td>Item ID</td><td>Price</td><td>Enabled</td>"; echo "<form action=main.php?id=test1.php method=post>"; while ($row = mysql_fetch_array($result)) { echo "<tr><td>".$row['product name']."</td>"; echo "<td>".$id[] = $row['item id'];$row['item id']."</td>"; echo "<td>".$row['price']."</td>"; $enabled[] = $row['enabled']; echo"<td><select name=".$enabled.">< <option Value=".$row['enabled'].">".$row['enabled']."</option> <option Value=Yes>Yes</option> <option Value=No>No</option> /select></td</tr>"; } echo "<input name=submit type=submit value=Update>"; echo "</form></table>"; if(isset($_POST['submit'])) { for($i=0;$i<$count;$i++){ $sql1="UPDATE `piprice` SET `enabled` = '$enabled[$i]' WHERE `item id` ='$id[$i]'"; $result1=mysql_query($sql1) or die (mysql_error()); } } ?> Basically I want to be able to pick yes/no and have it update in the database. One a side note is there a good site for me to learn php on (I just know the basics) besides asking 101 questions here $sqld = "SELECT * FROM orders WHERE `id`='$delete' AND `name`='$inf2[name]' AND `email`='$inf2[email]' LIMIT 1"; $csql = $db->query($sqld); $ccheck = $csql->fetch(PDO::FETCH_NUM); $cinf = $csql->fetch(PDO::FETCH_ASSOC); $quantity = $cinf[quantity]; $code = $cinf[code]; $stmt11 = $db->prepare('UPDATE feeds SET quantity=quantity-:quantity WHERE code=:code'); $stmt11->bindValue(':quantity', $quantity, PDO::PARAM_STR); $stmt11->bindValue(':code', $code, PDO::PARAM_STR); $stmt11->execute(); $id = $delete; $name = $inf2[name]; $stmt2 = $db->prepare("DELETE FROM orders WHERE id=:id AND name=:name"); $stmt2->bindValue(':id', $id, PDO::PARAM_STR); $stmt2->bindValue(':name', $name, PDO::PARAM_STR); $stmt2->execute();OK, i have just been told i should start using PDO instead of mysql to update my tables. This code works to delete the order but doesn't update the feeds section. All this is new to me so far and i think i am getting the hang of it. Should i still be using the quantity=quantity-:quantity or is there another way to do it with PDO? Sorry, i posted this in the wrong forum. Hope someone here can help until it's moved Edited by Self_Taught_Still_Learning, 30 May 2014 - 03:30 PM. Hi, I'm using php to access the mysql database using mysqli and I have a field on my table called "timestamp" and it's set as a timestamp and has current_time (I think in phpmyadmin it was a tick option so I clicked it) and when I update that row in my table the field "timestamp" doesn't update with the timestamp from when it was last updated/modified. I thought the field option timestamp automatically did that? I'm guessing not.. is there a way I can update the timestamp with the current time in my query? $query1 = "select * from movies where title = '".$title."' ;"; $result1 = mysql_query($query1) or die('Could Not Execute The Query'); while ($row = mysql_fetch_assoc($result1) ) { for($f=0; $f<$parts[$current_k]; $f++ ) { touch("$base_folder/{$hos}/".$linking[$sum].".php"); $old_part_href = $row['href_parts']; $updated_part = $old_part_href.$new; $query_href = 'update movies set href_parts = \''.$updated_part.'\''; mysql_query($query_href) or die('COULD NOT EXECUTE THE QUERY FOR PARTS HREF'); $new = "{$base_folder}/{$hos}/".$linking[$sum].".php"; $sum++; } } what i am trying to do is take the value of href_parts and add the new href of the page to the existing value on the href_parts and update the href_parts field in my db.. but i am not getting the desired results.. all i am getting in the db is the last value that is passed in the loop in the db.. i want to save the values which are exisiting in the db and add the newly created values to itt.. can anyone help please.. So, I am making a CMS for my school and I am having some trouble. It's a magazine sort of CMS and what I want is that when you click on a certain thing it continues onto the next page. Through the CMS you can create pages - when you do this each page gets a unique PID. To access the pages you have to enter the PID on the end of the URL, e.g. : http://www.myschool.com/magazine/index.php?pid=x. What I need is a code that when an image gets clicked the PID number in the URL goes up by one. Thanks Hey i have this code that should update database on submit of a form. i have multiple rows selected from a database and i need to be able to update each row individually...however currently as the code stands it updates all rows with the data entered into the bottom row. i dont know how to solve this its very frustrating could someone take a look and help me? here is the code <?php session_start(); ?> <a href="adminlogout.php">Logout</a><br /> <?php $id = $_GET['id']; if(!isset($_SESSION['myusername'])) { header("location:adminlogin.php"); } $dbhost = 'localhost'; $dbuser = 'root'; $dbpass = ''; $db = 'bank'; $conn = mysql_connect($dbhost,$dbuser,$dbpass); mysql_select_db($db); if(isset($_POST['submit'])){ $select = mysql_query("SELECT * FROM accounts WHERE cusid=$id"); $row3 = mysql_fetch_array($select); $update = mysql_query("UPDATE accounts SET balance='".$_POST['balance']."', type='".$_POST['type']."', name='".$_POST['name']."', active='".$_POST['active']."' WHERE cusid=$id"); } $result = mysql_query("SELECT * FROM customer WHERE cusid=$id"); $row2 = mysql_fetch_array($result); echo $row2['name'] . "'s bank accounts" . "<br><br>"; $result2 = mysql_query("SELECT * FROM accounts WHERE cusid=$id"); echo "<form method='post' action='accounts.php?id=$id'>"; while($row = mysql_fetch_array($result2)) { echo "<input type='text' name='accno' style='background-color:lightgrey;' readonly='readonly' value='$row[accno]'>" . "<input type='text' name='name' value='$row[name]'>"; if($row['type'] == "Current"){echo"<select name='type'>" . "<option selected='Selected'>Current</option>" . "<option>Savings</option>" . "</select>";} else{echo"<select name='type'>" . "<option selected='Selected'>Savings</option>" . "<option>Current</option>" . "</select>";} echo"<input type='text' name='balance' value='$row[balance]'>"; if($row['active'] == "No"){ echo "<select name='active'>" . "<option value='No' selected='selected'>No</option>" . "<option value='Yes'>Yes</option>" . "</select>";} elseif($row['active'] == "Yes"){echo "<select name='active'>" . "<option value='Yes' selected='selected'>Yes</option>" . "<option value='No'>No</option>" . "</select>";} echo "<input type='submit' name='submit' value='Update'>" . "<br>"; } echo "</form>"; ?> Hi, Does anyone have any experience of using PHP to transfer data from an XML file to a MySQL database? For the last 5 weeks I have been trying to get the following code to work but I am still unable to do it. The code does copy the file from my root folder into another (I eventually plan to use external download onto my server). However, it comes up with the following error: "Cannot instantiate non-existent class: xmlreader in" which refers to this: $xmlReader = new XMLReader(); Does anyone have any experience of transferring data from an XML file to a database? I am using PHP 5 so I dont know why this doesn't work. <?php ini_set('display_errors', 1); error_reporting(-1); $host="hostname"; // $username="username"; // $password="password"; // $db_name="db"; // $tbl_name="productfeed"; // // Connect to server and select database. mysql_connect("$host", "$username", "$password")or ("no connection"); mysql_select_db("$db_name")or die("Database Connection Error"); $xmlReader = new XMLReader(); $filename = "datafeed_98057.xml"; $url = "[url=http://www.ukhomefurniture.co.uk/datafeed.xml]http://www.ukhomefurniture.co.uk/datafeed.xml[/url]"; file_put_contents($filename, file_get_contents($url)); $xmlReader->open($filename); while ($xmlReader->read()) { switch ($xmlReader->name) { case'prod': $dom = new DOMDocument(); $domNode = $xmlReader->expand(); $element = $dom->appendChild($domNode); $domString = utf8_encode($dom->saveXML($element)); $product = new SimpleXMLElement($domString); $product_code = $product->prod['id']; $image = $product->awImage; //insert query if(strlen($product) > 0) { $query = mysql_query("REPLACE INTO productfeed (image) VALUES ('$awImage')"); echo $awImage . "has been inserted </br>"; die('yes it works'); error_reporting(E_ALL); if (ini_get('display_errors')) { ini_set('display_errors', 1); } } break; } } ?> MOD EDIT: DB credentials removed. ok it updates the posts table , but not the notifications table , helP! Code: [Select] <?php include("../includes.php"); $session =$logOptions_id; if($session) { $id = $_POST['id']; if(!$id) { $id = $session; } $post = mysql_real_escape_string($_POST['post']); $date = mktime(); $action_type = 0; mysql_query("INSERT INTO posts SET to_id='$id',from_id='$session',post='$post',type='$action_type',date='$date'"); $post_id = mysql_insert_id(); $query = mysql_query("SELECT id,to_id,from_id,post,type,state,date FROM posts WHERE id='$post_id' AND state='0' ORDER BY id DESC LIMIT 15"); print posts($query, "newPost"); if($id!=$session) { mysql_query("INSERT INTO notifications SET user_id='$id', from_id='$session', post_id='$post_id', action_type='$action_type', date='$date'"); } } ?> Hey guys, I've been doing a little bit of exerementing with PDO's and it seems I can't get it to update the database... I don't know why... Anyway here is the code: index.php Code: [Select] <?php /** * @author Jragon * @copyright 2011 */ require_once('includes/include.php'); $user = new user(); $user->newUser('Jragon', 'blenders', $DBH); echo '=D'; ?> /includes/connect.inc.php Code: [Select] <?php /** * @author Jragon * @copyright 2011 */ //Define connection details //host define('HOST', 'localhost'); //DataBase define('DB', 'rankometer'); //Username define('USER', 'root'); //Password define('PASS', ''); ?> /includes/connect.php Code: [Select] <?php /** * @author Jragon * @copyright 2011 */ //Include connection crap require_once('connect.inc.php'); //connect try { //new PDO $DBH = new PDO("mysql:host=" . HOST . ";dbname=" . DB, USER, PASS); //check for errors } catch(PDOException $e) { echo $e->getMessage(); } ?> /classes/user.class.php Code: [Select] <?php /** * @author Jragon * @copyright 2011 */ class user{ private $username; private $password; private $newPassword; private $salt; private $DBH; public function newUser($user, $pass, $DBH){ //name varibles $this->password = $pass; $this->username = $user; $this->DBH = $DBH; $this->getSalt(); $this->hashPass(); $this->createUser(); } private function getSalt(){ //pick random number $a = rand(1, 100); $b = rand(1, 100); $this->salt = rand($a, $b) * 5; } private function hashPass(){ //encrypt $this->password with md5 and a salt $plainPass = $this->password . $this->salt; $this->newPassword = md5($plainPass); } private function createUser(){ //prepare statement $STH = $this->DBH->prepare(" INSERT INTO `users` ( `user` , `pass` , `salt` ) VALUES ( '$this->username', '$this->newPassword', '$this->salt' ); "); //execute statement $STH->execute(); //prepare statement $STH = $this->DBH->prepare(" INSERT INTO `ranks` ( `rank` ) VALUES ( ); "); //execute statement $STH->execute(); } } ?> SQL dump Code: [Select] -- phpMyAdmin SQL Dump -- version 3.3.9 -- http://www.phpmyadmin.net -- -- Host: localhost -- Generation Time: Jun 02, 2011 at 06:05 PM -- Server version: 5.5.8 -- PHP Version: 5.3.5 SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO"; -- -- Database: `cakes` -- -- -------------------------------------------------------- -- -- Table structure for table `cakes` -- CREATE TABLE IF NOT EXISTS `cakes` ( `UID` int(11) NOT NULL AUTO_INCREMENT, `cake` int(11) NOT NULL, PRIMARY KEY (`UID`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; -- -- Dumping data for table `cakes` -- -- -------------------------------------------------------- -- -- Table structure for table `users` -- CREATE TABLE IF NOT EXISTS `users` ( `UID` int(11) NOT NULL AUTO_INCREMENT, `userName` varchar(11) NOT NULL, `passWord` varchar(32) NOT NULL, `salt` int(11) NOT NULL, PRIMARY KEY (`UID`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ; -- -- Dumping data for table `users` -- I have no idea what is going wrong... I don't get an error. All the output I get is '=D'. Thanks -Jragon Sorry maybe a stupid question but Ive made a cron and its not updating the players cash as it should, can anyone spot why? I've looked but just cannot see it, Thanks appreciate your time for looking. Code: [Select] <?php include("server.php"); $sql = "SELECT * FROM players"; $que = mysql_query($sql); while($res=mysql_fetch_array($que)) { $sql2 = "SELECT * FROM players WHERE id = '$res[id]'"; $que2 = mysql_query($sql2) or die(mysql_error()); $res2 = mysql_fetch_array($que2); $hoes = $res2['Hoes']; $hobedding = $res2['MaxHoes']; $incomemod = $res2['HoIncome']; $morale = $res2['HoesMorale']; if ($hoes < $hobedding) { $income = (250 * $hoes * $incomemod * $morale); } else { if ($hoes > $hobedding) { $income = (250 * $hobedding * $incomemod * $morale) + (125 * ($hoes - $hobedding) * $incomemod * $morale); } $sql5 = "UPDATE players SET cash = cash + '$income' WHERE id = '$res[id]'"; mysql_query($sql5) or die(mysql_error()); } } ?> Hey Guys, Im slowly updating our website to php/mysql, im getting there slowly but stuck at the minute. Im try to create a form where we can edit one of the pages text and then update the text in the database if that makes sense Basically at the moment i have a form where you can see the pages text like so: <table width="400" border="0" align="center" cellpadding="3" cellspacing="1"> <tr> <td><strong>Edit About Us English </strong></td> </tr> </table> <table width="400" border="0" align="center" cellpadding="0" cellspacing="1"> <tr> <td><form name="form1" method="post" action="send_update_english.php"> <table width="100%" border="0" cellspacing="1" cellpadding="3"> <tr> <td>Detail</td> <td>:</td> <td><textarea name="detail" cols="50" rows="4" id="detail"> [b]<?php mysql_connect("localhost", "web148", "123") or die(mysql_error()); mysql_select_db("web148") or die(mysql_error()); mysql_query("SET names 'utf8'"); $result = mysql_query("SELECT body FROM aboutenglish WHERE ID = '1'"); $row = mysql_fetch_array( $result ); echo nl2br($row['body']); ?>[/b] </textarea></td> </tr> <tr> <td> </td> <td> </td> <td><input type="submit" name="Submit" value="Submit"> <input type="reset" name="Submit2" value="Reset"></td> </tr> </table> </form> </td> </tr> </table> Ive got that php bit in the middle to pull out the text thats on that page but not sure if thats correct or not. But anyways on the 'send form' page i have: <?php // Details [b]$message="$detail";[/b] mysql_connect("localhost", "web148", "123") or die(mysql_error()); mysql_select_db("web148") or die(mysql_error()); mysql_query("SET names 'utf8'"); $result = mysql_query("UPDATE aboutenglish SET body = '$message' where ID = '1'"); ?> the update query works if i put text in there, but when i use '$message' the database is left blank. This is only my second week doing all this stuff, so bare with me I appreciate your answers. I'm just trying to get suggestions on what people think would be the best way to go with this. With the bottom part of this card where it s tarts working with the foreach loop its taking what was a UL and for each of each LI's and updating a table with its new data however this way isn't going to work as this is editing a user. Because there could be 5 in the database but the new edit user has only 4 lis so I'm sure you could all see the issue here. What I'm thinking would be best is to have it DELETE the existing characterIDs that have WHERE handler_ID = $handlerID and then just do a new INSERT statement. Anyone else think this would be the best way to go about this? Code: [Select] if (mysqli_num_rows($Qresult) == 0) { $query = "UPDATE `handlers` SET `userName` = '".$userName."', `password`='".$password."', `firstName`='".$firstName."', `lastName`='".$lastName."', `statusID`='".$statusID."', `isAdmin`='".$admin."', `defaultCharID`='".$defaultCharID."', `email`='".$email."' WHERE `ID` = '".$handlerID."'"; mysqli_query($dbc, $query); foreach ($characterIDs as $cID) { $query2 = "UPDATE `handler_characters` SET `handler_id` = '".$handlerID."', `characterID` = '".$cID."'"; mysqli_query($dbc, $query2); } $result = "good"; } Hi, I'm a beginner at PHP and am I'm trying to update an array but cant get it to work: This is my 'rates' page, There are 6 boxes that are the headings, and 6 boxes per line below for the data, I can get the headings to save but not the data lines below: rates-edit.php Code: [Select] <?php error_reporting(E_ALL); ini_set('display_errors', 2); // Include the necessary files include_once '../inc/db.inc.php'; // Open a database connection $db = new PDO(DB_INFO, DB_USER, DB_PASS); // Extract details from database $sql = "SELECT title1, title2, title3, title4, title5, title6 FROM rates WHERE id=1"; $stmt = $db->prepare($sql); $stmt->execute(); $e = $stmt->fetch(); $sql2 = "SELECT 1, 2, 3, 4, 5, 6 FROM ratestable ORDER BY id ASC"; $stmt2 = $db->prepare($sql2); $stmt2->execute(); $e2 = $stmt->fetch(); ?> <!DOCTYPE html> <html lang="en"> <head> <h3>Rates Table</h3> <form method="post" action="rates-editupdate.php" enctype="multipart/form-data"> <input type="text" name="title1" maxlength="10" value="<?php echo $e['title1'] ?>" class="rates" /> <input type="text" name="title2" maxlength="10" value="<?php echo $e['title1'] ?>" class="rates" /> <input type="text" name="title3" maxlength="10" value="<?php echo $e['title3'] ?>" class="rates" /> <input type="text" name="title4" maxlength="10" value="<?php echo $e['title4'] ?>" class="rates" /> <input type="text" name="title5" maxlength="10" value="<?php echo $e['title5'] ?>" class="rates" /> <input type="text" name="title6" maxlength="10" value="<?php echo $e['title6'] ?>" class="rates" /> <?php while($e2 = $stmt2->fetch()) { ?> <input type="text" name="1" maxlength="10" value="<?php echo $e2['1'] ?>" class="rates" /> <input type="text" name="2" maxlength="10" value="<?php echo $e2['2'] ?>" class="rates" /> <input type="text" name="3" maxlength="10" value="<?php echo $e2['3'] ?>" class="rates" /> <input type="text" name="4" maxlength="10" value="<?php echo $e2['4'] ?>" class="rates" /> <input type="text" name="5" maxlength="10" value="<?php echo $e2['5'] ?>" class="rates" /> <input type="text" name="6" maxlength="10" value="<?php echo $e2['6'] ?>" class="rates" /> <?php } ?> <input id="button-upload" class="button" type="submit" name="submit" value="Save Changes" /> <input id="button-upload" class="button" type="submit" name="submit" value="Add New Row" /> </form> </body> </html> This is the page that updates the database, I cant get the loop/foreach to work... rates-editupdate.php Code: [Select] <?php error_reporting(E_ALL); ini_set('display_errors', 2); // Include the necessary files include_once '../inc/db.inc.php'; // Open a database connection $db = new PDO(DB_INFO, DB_USER, DB_PASS); // Check if coming from a POST command and Save Changes // THIS BIT WORKS :) if($_SERVER['REQUEST_METHOD']=='POST' && $_POST['submit']=='Save Changes') { $sql = "UPDATE rates SET title1=?, title2=?, title3=?, title4=?, title5=?, title6=? WHERE id=1 LIMIT 1"; $stmt = $db->prepare($sql); $stmt->execute( array( $_POST['title1'], $_POST['title2'], $_POST['title3'], $_POST['title4'], $_POST['title5'], $_POST['title6'] ) ); $stmt->closeCursor(); // // THIS IS THE BIT THAT DOES NOT UPDATE: // $sql = "UPDATE ratestable SET 1=?, 2=?, 3=?, 4=?, 5=?, 6=? WHERE id=?"; $stmt = $db->prepare($sql); if(count($_POST['1']) > 0) { foreach($_POST AS $key => $val) { $stmt->execute(array( ($key), ($_POST['2'][$key]), ($_POST['3'][$key]), ($_POST['4'][$key]), ($_POST['5'][$key]), ($_POST['6'][$key]), ($val) ) ); } $stmt->closeCursor(); } // once updated return to rates page header('Location: rates-edit.php?success=1'); exit; } ?> thanks in advance I am trying to update a tiny int i have the if statement which says when tiny int is 1 echo closed and when tiny int 0 echo open. The problem is i am trying to query the result in a drop down but the option of status Closed doesnt appear. Code: [Select] <?php //connect to database $con=mysql_connect("localhost","root","15AE@ea27") or die("couldn't connect to mysql"); //select database $db=mysql_select_db("ac_res",$con) or die("database not found"); //get ID to Edit $id = $_GET['id']; //Query Fields to edit $sql = 'SELECT * FROM `ac_reservation` WHERE `id` = "'.$id.'"'; $query = mysql_query($sql) or die("Couldn't execute query. ". mysql_error()); $results = mysql_fetch_array($query); $status = 'status'; //Query the waiter table $waiter=mysql_query("SELECT fname FROM waiter") or die("query error"); ?> <form id="edituser" name="edituser" method="post" action="editresexec.php"> <table width="300" border="0" align="center" cellpadding="2" cellspacing="0"> <tr> <th> </th> <td><input name="id" type="hidden" class="textfield" value= <?php echo $results[id]?> /> </td> </tr> <tr> <th>First Name </th> <td><input name="fl_name" id="keyboard2" type="text" class="textfield" value= <?php echo $results[fl_name]?> /> </td> </tr> <tr> <th>Number of People</th> <td><input name="n_people" id="keyboard3" type="text" class="textfield" value= <?php echo $results[n_people]?> /> </td> </tr> <tr> <th>Table Number</th> <td><input id="t_number"name="t_number" type="text" class="textfield" value= <?php echo $results[t_number]?> /></td> </tr> <tr> <th>Waiter</th> <td><?php echo "<select name=waiter>"; while($r=mysql_fetch_array($waiter)) { //echo waiter name echo "<option value='".$r['fname']."'>".$r['fname']."</option>"; } echo "</select>"; ?> </td> </tr> <tr> <th>Status</th> <td><?php //If statement if($rows['status'] == 1) { $status = "Close"; } else $status = "Open"; //Drop Down Menu For Status echo "<select>"; echo "<option value='".$status."'>".$status."</option>"; echo "</select>"; ?> </td> </tr> <tr> <td> </td> <td><input type="submit" name="Update" value="Update" /></td> </tr> </table> </form> well here my page i tryed and tryed to get it working but it shows the data but it dont update it Code: [Select] [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><?php include "../config.php"; $id = $_GET['id']; $con = database_connect(); $sql = "SELECT * FROM anime1 WHERE animeid ='$id'"; $result = mysql_query($sql); while ($row = mysql_fetch_assoc($result)) { $title = $row['title']; $type = $row['type']; $episode = $row['episode']; $year = $row['year']; $genre = $row['genre']; $status = $row['status']; $summary = $row['summary']; $pictures = $row['pictures']; }mysql_query($sql) or exit(mysql_error()); mysql_close($con); ?> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript"> $(document).ready(function(){ $(".flip").click(function(){ $(".panel").slideToggle("slow"); }); }); </script> <style type="text/css"> </style> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Transdmin Light</title> <!-- CSS --> <link href="style/css/transdmin.css" rel="stylesheet" type="text/css" media="screen" /> <!--[if IE 6]><link rel="stylesheet" type="text/css" media="screen" href="style/css/ie6.css" /><![endif]--> <!--[if IE 7]><link rel="stylesheet" type="text/css" media="screen" href="style/css/ie7.css" /><![endif]--> <!-- JavaScripts--> <script type="text/javascript" src="style/js/jquery.js"></script> <script type="text/javascript" src="style/js/jNice.js"></script> </head> <body> <div id="wrapper"> <!-- h1 tag stays for the logo, you can use the a tag for linking the index page --> <h1><a href="#"><span>Transdmin Light</span></a></h1> <!-- You can name the links with lowercase, they will be transformed to uppercase by CSS, we prefered to name them with uppercase to have the same effect with disabled stylesheet --> <ul id="mainNav"> <li><a href="#">DASHBOARD</a></li> <!-- Use the "active" class for the active menu item --> <li><a href="./anime.php" class="active">Anime</a></li> <li><a href="#">DESIGN</a></li> <li><a href="#">OPTION</a></li> <li class="logout"><a href="#">LOGOUT</a></li> </ul> <!-- // #end mainNav --> <div id="containerHolder"> <div id="container"> <div id="sidebar"> <ul class="sideNav"> <li><?php echo $lbox1 ?></li> <li><?php echo $lbox2 ?></li> <li><?php echo $lbox3 ?></li> <li><?php echo $lbox4 ?></li> <li> <?php echo $lbox5 ?></li> <li><?php echo $lbox6 ?></li> </ul> <!-- // .sideNav --> </div> <!-- // #sidebar --> <!-- h2 stays for breadcrumbs --> <h2><a href="#">Anime</a> » edit » <?php echo "$title"; ?></h2> <div id="main"> <form action="<?php echo $_SERVER['PHP_SELF']."?id=$id" ; ?>" method="post" class="jNice"> <h3>Editing <?php echo "$title"; ?>, when finished click submit</h3> <fieldset> <p> <label>Series Title -- (Put the Title of the Series you are adding into here)</label> <input name="title" type="text" class="text-long" id="title" value="<?php echo $title ?>" /> </p> <p> <label>Type -- (Put what type of anime is it?)</label> <select name="type" id="type"> <option selected="selected">Select one</option> <option>TV Series</option> <option>OVA</option> <option>TV Special</option> <option>Movie</option> <option>Web</option> <option>DVD Special</option> <option>Other</option> </select> </p> <p> <label>Episodes -- (How many Episode are there?)</label> <input name="episode" type="text" class="text-long" id="episode" value="<?php echo $episode ?>" /> </p> <p> <label>Year -- (What year was the anime release in?)</label> <input name="year" type="text" class="text-long" id="year" value="<?php echo $year ?>" /> </p> <p> <label>genre <a href="./genre">(click this for the list and FAQ for adding in genre)</a></label> <input name="genre" type="text" class="text-long" id="genre" value="<?php echo $genre ?>" /> </p> <p> <label>status -- (What Is the status of the anime, Completed, Ongoing or Stalled)</label> <select name="status" id="status"> <option selected="selected">Select one</option> <option>Complete</option> <option>Ongoing</option> <option>Stalled</option> </select> </p> <p> <label>Summary -- (Put in the Summary for the anime)</label> <textarea name="summary" cols="1" rows="1" id="summary"><?php echo $summary ?></textarea> </p> <p> <label>Pictures -- (link to the Anime Pictures you upladed)</label> <input name="pictures" type="text" class="text-long" id="pictures" value="<?php echo $pictures ?>" /> </p> <?php $con = database_connect(); $sql="UPDATE anime1 SET title='$title', type='$type', episode='$episode', year='$year', genre='$genre', status='$status', summary='$summary', pictures='$pictures' WHERE animeid = '$id'"; $con = database_connect(); $title = $_POST['title']; $type = $_POST['type']; $episode = $_POST['episode']; $year = $_POST['year']; $genre = $_POST['genre']; $status = $_POST['status']; $summary = $_POST['summary']; $pictures = $_POST['pictures']; $title = mysql_real_escape_string($title); $type = mysql_real_escape_string($type); $episode = mysql_real_escape_string($episode); $year = mysql_real_escape_string($year); $genre = mysql_real_escape_string($genre); $status = mysql_real_escape_string($status); $summary = mysql_real_escape_string($summary); $pictures = mysql_real_escape_string($pictures); error_reporting(-1); if (!mysql_query($sql,$con)) { die('Error adding anime database: ' . mysql_error()); } ?> <h3> </h3> <?php $con = database_connect(); $sql1 = "SELECT * FROM episodea WHERE animeid = '$id' UNION ALL SELECT * FROM episodeb WHERE animeid = '$id'"; $result1 = mysql_query($sql1); while ($row = mysql_fetch_assoc($result1)) { $ep = $row['ep']; $epname = $row['epname']; $animeid = $row['animeid']; $video = $row['video']; $video2 = $row['video2']; $video3 = $row['video3']; mysql_query($sql) or exit(mysql_error()); echo " <div class=\"panel\">\n"; echo "<p>\n"; echo " <label>Episodes -- (When this box says Anime episode finished, you have added in all the episodes)</label>\n"; echo " <input name=\"ep\" type=\"text\" class=\"text-long\" id=\"ep\" value=\" $ep\" readonly=\"readonly\" />\n"; echo " </p>\n"; echo " <p>\n"; echo " <label>Episodes Name-- (What is the name of the episode you are adding? --- If the episodes has no name enter episode number)</label>\n"; echo " <input name=\"epname\" type=\"text\" class=\"text-long\" id=\"epname\" value=\" $epname\" />\n"; echo " </p>\n"; echo " <p>\n"; echo " <label>Viewable -- (Is the episode your are adding in SUBBED or DUBBED or RAW?)</label>\n"; echo " <select name=\"viewable\" id=\"viewable\">\n"; echo " <option selected=\"selected\">Select one</option>\n"; echo " <option>SUBBED</option>\n"; echo " <option>DUBBED</option>\n"; echo " <option>RAW</option>\n"; echo " </select>\n"; echo " </p>\n"; echo " <p>\n"; echo " <label>Video 1 -- (enter the embed code for the episode you are adding in)</label>\n"; echo " <textarea name=\"video\" cols=\"1\" rows=\"1\" id=\"video\"> $video</textarea></p>\n"; echo " <p>\n"; echo " <label>Video 2 -- ( If you have a 2ed embed code </label>\n"; echo " <textarea name=\"video1\" cols=\"1\" rows=\"1\" id=\"video1\"> $video2</textarea>\n"; echo " </p>\n"; echo " <p>\n"; echo " <label>Video 3 --( If you have a 3ed embed code </label>\n"; echo " <textarea name=\"video4\" cols=\"1\" rows=\"1\" id=\"video4\"> $video3</textarea>\n"; echo "<h3>\n"; echo "<a href=\"#submit\">IF you finished editing ep, click me to go to submit button</a></h3>\n"; echo " </p>\n"; echo "</div>\n"; echo " \n"; echo " <br />"; echo "<br />"; echo "<p class=\"flip\">Click here to edit all Episodes For $title </p>\n"; echo " <br />"; echo "<br />"; } ?> <h3> remember to click submit before changing the page</h3> <h3> </h3> <h3> <a name="submit" id="submit"></a> <input type="submit" value="Submit Query" /> </h3> </fieldset> </form> </div> <!-- // #main --> <div class="clear"></div> </div> <!-- // #container --> </div> <!-- // #containerHolder --> <p id="footer">Feel free to use and customize it. <a href="http://www.perspectived.com">Credit is appreciated.</a></p> </div> <!-- // #wrapper --> </body> </html> [/php] The client provides name/value pairs which are used to update something and I am currently using switch statements to direct the action based on the provided name, however, it is becoming increasingly more complicated. Are there any standard approaches to doing so? I am thinking of doing the following. Any concerns? Thanks $c['fooService'] = function ($c) { return new Foo\FooService( new Foo\FooMapper(), new ApiConnector(), new Foo\FooNameValueUpdater(), ); }; $app->put('/foo/{id:[0-9]+}', function (Request $request, Response $response, $args) { return $this->fooResponder->update($response, $this->fooService->update($args['id'], $request->getParsedBody())); }); Class FooService extends BarService { public function __construct($mapper, $updater, $apiConnector) { $this->mapper = $mapper; $this->apiConnector = $apiConnector; $this->updater = $updater; } public function update($id, $params) { //$params=['name'=>'property1name', 'value'=>123] $this->updater->$params['name']($id, $params['value'], $this); } public function updateSomeStandardAction($id, $value, $propertyName) { //some code... $this->mapper->bla($id, $value, $propertyName); } public function updateSomeOtherStandardAction($id, $value, $propertyName) { //some code... $this->apiConnector->bla($id, $value, $propertyName); } } Class FooNameValueUpdater extends BarNameValueUpdater { public function property1name($id, $value, $service) { $this->updateSomeStandardAction($id, $value, $service, 'property1name'); } public function property2name($id, $value, $service) { $this->updateSomeStandardAction($id, $value, $service, 'property2name'); } public function property3name($id, $value, $service) { $this->updateSomeStandardAction($id, $value, $service, 'property3name'); } public function property4name($id, $value, $service) { $this->updateSomeStandardAction($id, $value, $service, 'property4name'); } protected function updateSomeStandardAction($id, $value, $service, $propertyName) { //some code... $service->updateSomeStandardAction($id, $value, $propertyName); } protected function updateSomeOtherStandardAction($id, $value, $service, $propertyName) { //some code... $service->updateSomeOtherStandardAction($id, $value, $propertyName); } }
i have this small problem trying to update the database.... what i have is a members site in which they can view a variety of topics, however i want the user to be able to say delete a topic they are not interested in but still keep that topic open to other users who have not blocked it I'm tying to figure out how to do this, i initially had the following code: $update_db = mysql_query("UPDATE topics SET view='2' WHERE topicID='$topicID'") or die(mysql_error()); I had it set to to 2 meaning that all the topics that were set to 1 were visible to the user, only those they blocked were set to 2 and only be blocked to those users who blocked them not everyone The problem with that was that it blocked it to everyone Can anyone help me? do you see anything wrong with this update code? i am having trouble setting the acntStatus=1. Code: [Select] <?php mysql_select_db($database_uploader, $uploader); $query = "SELECT * FROM members WHERE uname='$_SESSION[user]'"; $result = mysql_query($query) or die(mysql_error()); if (mysql_num_rows($result) > 0) { $row = mysql_fetch_array($result) or die(mysql_error()); $usedSpace = $row['bandwhitch']; $acntType = $row['acntType']; if ($acntType == 1) { $totalSpace = 500; } else { $totalSpace = 250; } if($usedSpace > $totalSpace) { echo "There is something wrong with your account. Please contact us!"; $usageError = true; mysql_query(sprintf("UPDATE members SET acntStatus='%s' WHERE uname='%d'", mysql_real_escape_string(1), $_SESSION['user'])) or die(mysql_error()); mysql_close($con); } $usagePercent = (round(($usedSpace/$totalSpace), 2)) * 100; // Convert to percentage } ?> |