PHP - Updating More Then One Row
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 Similar TutorialsHi, 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? $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. $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 Hi all, for my website ive got a fuel station which ive coded so users can fill up there there car fuel tanks, but the code all works part from one part of it. The code: The part of the code which isnt working: <?php $usermoney = $fetch->money; $costs2 = $fetch_fuelstation->price * $fueldiff; if ($costs2 > $usermoney){ echo "You dont have enouth money."; } elseif ($costs2 <= $usermoney){ $nmoney = $usermoney - $costs2; mysql_query("UPDATE users SET money='$nmoney' WHERE username='$username'") or die (mysql_error()); } ?> Ive got a varibal called $usermoney which selects the users current money from the database, but what im trying todo is take the fuel price away from there current money, but its not subtracting the money as it should. Anyone see why its not taking the money? Thanks. again my tables are movies| ID(PK) - Titles - Category(FK) - URL 0 Name 1 www.xyz.com categories| ID(PK) - Category 1 Comedy say i create a query SELECT * FROM movies WHERE Category="1" and it gave me all the movies from my table that is in the comedy category which should look like this: ID - Title - Category - URL 0 Name Comedy www.xyz 1 xyz Comedy www.abc etc.. How can i add a drop down menu beside each movie listed in that result that would let me change the category for it and save it ? like this, ID - Title - Category - URL 0 Name Comedy www.xyz [Dropdown] 1 xyz Comedy www.abc [Dropdown] [Save Button] being a newbie im going to guess that i will need a INSERT in here somewhere and not really sure how i would write my result echos. i have been trying all kinds of "update records" forms and cant get them right so i figured it may be easier to just try and create my own. if i could get some example or if you have more simple suggestions so my database table already exists but i need to add new columns to the table so this is how the table looks now
CREATE TABLE IF NOT EXISTS `users` ( `id` int(255) NOT NULL AUTO_INCREMENT, `birthday` varchar(10) COLLATE utf8_unicode_ci NOT NULL DEFAULT '1-1-1990', `comment_privacy` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'everyone', `confirm_followers` int(11) NOT NULL DEFAULT '0', `current_city` text COLLATE utf8_unicode_ci NOT NULL, `follow_privacy` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'everyone', `gender` varchar(6) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'male', `hometown` text COLLATE utf8_unicode_ci NOT NULL, `message_privacy` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'everyone', `post_privacy` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'everyone', `timeline_post_privacy` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'everyone', PRIMARY KEY (`id`), UNIQUE KEY `id` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;and this is what I need it to look.... but every time I insert in the sql to do the update but it does not do it as the table already there... CREATE TABLE IF NOT EXISTS `users` ( `id` int(11) NOT NULL AUTO_INCREMENT NOT NULL, `job_title` mediumtext COLLATE utf8_unicode_ci NOT NULL, `job_at` mediumtext COLLATE utf8_unicode_ci NOT NULL, `birthday` varchar(10) COLLATE utf8_unicode_ci NOT NULL DEFAULT '1-1-1990', `comment_privacy` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'everyone', `confirm_followers` int(11) NOT NULL DEFAULT '0', `current_city` text COLLATE utf8_unicode_ci NOT NULL, `relationship` varchar(15) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'Not Applicable', `relationship_to` mediumtext COLLATE utf8_unicode_ci NOT NULL, `follow_privacy` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'everyone', `gender` varchar(6) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'male', `hometown` text COLLATE utf8_unicode_ci NOT NULL, `message_privacy` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'everyone', `post_privacy` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'everyone', `timeline_post_privacy` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'everyone', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;how can I do this update>? its ok i know how to do this.. but the code i sell needs this update but i cant get them to delete there table as there mybe data already in the table This executes with no errors but it is not updating the db. I have previously verified that the record exists. <?php // update database // Connect to database ===================================================== include("connect_db.php"); // retrieve form data from form2.html ========================================== $id = $_POST['id']; // do not change $id = $_POST['ama']; // do not change $id = $_POST['model_name']; $id = $_POST['model_mfg']; $id = $_POST['wingspan']; $id = $_POST['engine']; $id = $_POST['decibels']; // Send query =========================================================== $query = "UPDATE airplanes SET model_name = '$model_name' WHERE id = '$id'"; //if (!mysql_query($query)){ //die('Error :' .mysql_error()); //} echo '<p>Return to <a href="members_menu.html">Members Menu</a></p>'; ?> Thanks Hey all, I've recently been coding a Bank for my game in which users can desposit there money into. But while coding it I've came though a few errors in which I carn't seem to sort <?php session_start(); include_once ("includes/functions.php"); include ("includes/config.php"); require ("crewtop.php"); logincheck(); ini_set ('display_errors', 1); error_reporting (E_ALL); $username = $_SESSION['username']; $getuser = mysql_query("SELECT * FROM users WHERE username='$username'"); $user = mysql_fetch_object($getuser); $themembers = mysql_query("SELECT * FROM users WHERE crew = '$user->crew'"); $ammoutmembers = mysql_num_rows($themembers); $crew = mysql_query("SELECT * FROM crews WHERE name = '$user->crew'"); $crewstuff = mysql_fetch_object($crew); // Got everything needed.... if ($_POST['desposit']){ $desposit = strip_tags($_POST['desposit']); if ($desposit > $user->money){ // *** This Line *** echo ("You haven't got that much Money to Desposit!"); }elseif ($desposit <= $user->money){ if (ereg('[^0-9]',$desposit)){ echo ("Invalid Numbers Posted!"); }elseif(!ereg('[^0-9]',$desposit)){ mysql_query("UPDATE crews SET bank=bank+$desposit WHERE name='$user->crew'"); mysql_query("UPDATE users SET money=money-$desposit WHERE username='$username'"); echo ('You successfully Deposited £".number_format($desposit)."!'); } } } /* Deposit done - Now Withdraw... */ if ($_POST['withdraw']){ $withdraw = strip_tags($_POST['withdraw']); if ($withdraw > $crewstuff->bank){ // *** This Line *** echo ("You don't have that much Money in the Bank!"); }elseif ($withdraw <= $crewstuff->bank){ if (ereg('[^0-9]',$withdraw)){ echo "Invalid Numbers Posted!"; }elseif(!ereg('[^0-9]',$withdraw)){ $leftinbank = $crewstuff->bank - $withdraw; mysql_query("UPDATE crews SET bank=bank-$withdraw WHERE name='$user->crew'"); mysql_query("UPDATE users SET money=money+$withdraw WHERE username='$username'"); echo ('£".number_format($withdraw)." has been Withdraw from the Crew Bank!'); } } } // Withdraw done! ?> <html> <head> <title>Crew Bank || SD</title> <link rel="stylesheet" href="style.css" type="text/css"> </head> <body class='body'> <form action='' method='POST' name='crewbank'> <?php echo ("$username , $user->money"); ?> <?php if ($username != $crewstuff->boss || $username != $crewstuff->coowner || $username != $crewstuff->underboss || $username == $crewstuff->recruiter || $username == $crewstuff->recruiterone || $crewstuff->boss == $username || $crewstuff->coowner == $username || $crewstuff->underboss == $username){ ?> <table width='50%' cellpadding='0' cellspacing='0' border='1' class='table' colspan='2' align='center'> <tr> <td class='header' align='center' colspan='2'>Crew Bank</td> </tr> <tr> <td class='omg' colspan='2' align='center'>You Have <strong>£<?php echo "".number_format($crewstuff->bank).""; ?></strong> in the Crew Bank!</td> </tr> <tr> <td align='center' width='50%'>Deposit:</td><td align='center' width='50%'><input type='text' name='desposit' class='input' id='desposit'></td> </tr> <tr> <td align='center' colspan='2' align='center'><input type='submit' name='desposit' class='button' id='despositmoney' Value='Deposit!'></td> </tr> <?php } // Boss ?> </table> <br /> <?php if ($crewstuff->boss == $username || $crewstuff->coowner == $username || $crewstuff->underboss == $username){ ?> <table width='50%' cellpadding='0' cellspacing='0' border='1' class='table' colspan='2' align='center'> <tr> <td class='header' align='center' colspan='2'>Crew Bank - Withdraw</td> </tr> <tr> <td class='omg' align='center' colspan='2'>You carn't Withdraw more Money then there is in your Bank!</td> </tr> </tr> <tr> <td align='center' width='50%'>Withdraw:</td><td width='50%' align='center'><input type='text' name='withdraw' class='input' id='withdraw'></td> </tr> <tr> <td align='center' colspan='2' align='center'><input type='submit' name='withdraw' class='button' id='withdrawmoney' Value='Withdraw!'></td> </tr> </table> <?php } // Boss .. Underboss ?> </form> </body> </html> The two lines with the Comments on " // *** This Line *** " are the parts I've got a problem with. When a User is either despositing or Withdrawing there money it says there isn't enouth Money in the Bank, or that they don't have enouth Money, even when they have enouth. Anyone see why its saying the Error? Thanks in advance 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. Okay, I have a useredit page in where a user can manage their account info. All the text field and SQL connections work fine, and they all update perfectly. But when I go ahead and add my own text field (first name) and hit submit, it says success - but in my SQL it hasn't actually updated ... What the Ef? Here are my snippets of my codes: --useredit.php-- <form action="process.php" method="POST"> <input type"text" name"firstname" value="<? if($form->value("firstname") == ""){ echo $session->userinfo['firstname']; }else{ echo $form->value("firstname"); } ?>"> <input type="hidden" name="subedit" value="1"> <input type="submit" value="Edit Account"> --process.php-- function procEditAccount(){ global $session, $form; /* Account edit attempt */ $retval = $session->editAccount($_POST['curpass'], $_POST['newpass'], $_POST['email'], $_POST['firstname']); /* Account edit successful */ if($retval){ $_SESSION['useredit'] = true; header("Location: ".$session->referrer); } --session.php-- function editAccount($subcurpass, $subnewpass, $subemail, $subfirstname){ global $database, $form; if($subfirstname){ $database->updateUserField($this->username,"firstname",$subfirstname); } --database.php-- function updateUserField($username, $field, $value){ $q = "UPDATE ".TBL_USERS." SET ".$field." = '$value' WHERE username = '$username'"; return mysql_query($q, $this->connection); } If you need to see more code, let me know. Would appreciate the help, thanks! Ollie! Hi, Apologies to keep going on about this but I have hit a brick wall over updating my database with XML. I have spent around 100 hours on this and so far I can only copy the file, I am unable so far to update my database with the information from the XML file. I would be very grateful for any help you can offer to fix this. Code: [Select] ----Code so far----> $xmlReader = new XMLReader(); $filename = "datafeed_98057.xml"; $url = "http://www.domain.co.uk/datafeed.xml"; 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)); $prod = new SimpleXMLElement($domString); $id = $prod->prod['id']; $description = $prod->name; $image = $prod->awImage; $fulldescription = $prod->desc; //insert query if(strlen($prod) > 0) { $query = mysql_query("REPLACE INTO productfeed (id, description, fulldescription, image) VALUES ('$id','$description','$image','$fulldescription') "); echo $id . "has been inserted </br>"; } else{echo ("This does not work </br>");} } This is an outline of the XML feed I am using, it only includes one item which I am using as a test: Code: [Select] - <merchant id="1829" name="Pinesolutions.co.uk"> - <prod id="39920873" pre_order="no" web_offer="no" in_stock="yes" hotPick="no" adult="no"> - <text lang="EN"> <name>Oakleigh Wall Mirror 60x90</name> <desc>Mirrors are useful anywhere in the house. Not only are they functional allowing you to see your reflection in order to look your best, they also add elegance to any room theyre placed in. We offer a variety of mirrors to fit your decorating tastes as well as wall space. The Oakleigh Wall Mirror radiates an elegant simplistic style, while offering a generous size glass. The Oakleigh Wall Mirror s frame is crafted from solid hardwood and is lacquered with a protective finish to guard against dust and unexpected stains. The Oakleigh Wall Mirror is versatile and can be hung portrait style at the top of a staircase or landscape. The Oakleigh Wall Mirrors light colour means it also complements all of the furniture in our Camden Painted Range because the range has ash tops. The Oakleigh Wall Mirror has fewer knots than traditional oak wood, but is built just as sturdy so you can be certain it will last you through the generations to come.</desc> </text> - <uri lang="EN"> <awTrack>http://www.awin1.com/pclick.php?p=39920873&a=98057&m=1829</awTrack> <awImage>http://images.productserve.com/preview/1829/39920873.jpg</awImage> <mLink>http://www.pinesolutions.co.uk/bedroom-furniture/mirrors/wall-mirrors/oakleigh-wall-mirror-60x90/</mLink> <mImage>http://media.pinesolutions.co.uk/images/products/903.333.3.4.jpg</mImage> </uri> - <price curr="GBP"> <buynow>40.00</buynow> </price> - <cat> <awCatId>424</awCatId> </cat> <brand /> </prod> </merchant> I can't get my form to update the database with user personal information. Any help greatly appreciated. Upon submitting the form, it just reloads the page, no information added to the DB. I used the update statement because I want the users to be able to update the info at a later date. Not sure if that was the right thing to do. thank you. Code: [Select] <?php ini_set ("display_errors", "1"); error_reporting(E_ALL); include('bouncer.php'); $host = ""; $database = ""; $username = ""; $password = ""; $tbl_name = "users"; $conn = mysql_connect($host, $username, $password) or die("Could not connect: " . mysql_error()); if($conn) { mysql_select_db($database); } else { echo "failed to select database"; } $currentUser = $_SESSION['myusername']; // get user from login and make it current user to use for update statement echo "Login success!<br/>"; echo "Please fill out the form below to add your personal information to the database<br/>"; ////////////////////////////////////////////////////////////////////////////////////////////////// if(isset($_POST['submit'])) { $firstname = mysql_real_escape_string( $_POST['first']); $lastname = mysql_real_escape_string( $_POST['last']); $dob = mysql_real_escape_string( $_POST['dob']); $gender = mysql_real_escape_string( $_POST['gender']); $result= mysql_query ( "UPDATE users SET firstname = '$firstname', lastname = '$lastname', dob = '$dob', gender='$gender' WHERE username='$currentUser'") or die(mysql_error()); if($result) { echo "your information was updated in the database and is as follows <br/>"; //put the results on the screen echo "<br/> $firstname <br/>"; echo "<br/>$lastname <br/>"; echo "<br>$dob <br/> "; echo ">$gender <br>"; } else { echo "error, could not update your info to the database </br>";//end if result } }//end if sumbit post statement at top ?> <html> <body> <p> </p> <p> </p> <p> <form action="login_successERROR.php" method="post"> <p> <input type="text" name="first" size="20" /> First name<br /> <input type="text" name="last" size="20" /> Last name<br /> <input name="dob" type="text" size="20" id="dob" /> Date of Birth<br /> <input type="text" name="gender" size="20" id="gender" /> Gender <br /> <input type="submit" value="Add personal information to database" /> <input type="reset" value="Reset fields" /> </p> </p> </form> <p><a href="index.php">HOME</a></p> <p> </p> </body> </html> 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 } ?> 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 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. Hi there im going a little bit mad now.... i spent a while trying to work out why my form didnt update or redirect... After head scratching i remade a test form... That also doesnt update or redirect?? I must be missing something here?? So basically when the user clicks submit nothing happens, why?? Code: [Select] <?php require_once('Connections/swb.php'); ?> <?php session_start(); if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } $editFormAction = $_SERVER['PHP_SELF']; if (isset($_SERVER['QUERY_STRING'])) { $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']); } if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "form1")) { $updateSQL = sprintf("UPDATE player SET `Day`=%s WHERE PlayerName=%s", GetSQLValueString($_POST['days'], "int"), GetSQLValueString($_POST['playername'], "text")); mysql_select_db($database_swb, $swb); $Result1 = mysql_query($updateSQL, $swb) or die(mysql_error()); $updateGoTo = "logout.php"; if (isset($_SERVER['QUERY_STRING'])) { $updateGoTo .= (strpos($updateGoTo, '?')) ? "&" : "?"; $updateGoTo .= $_SERVER['QUERY_STRING']; } header(sprintf("Location: %s", $updateGoTo)); } ?> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Untitled Document</title> </head> <body> <form action="<?php echo $editFormAction; ?>" id="form1" name="form1" method="POST"> <input type="button" value="End Turn" /> <input name="days" type="hidden" id="days" value="1"/> <input name="playername" type="hidden" id="playername" value="<?php echo $_SESSION['MM_Username']; ?>"> <input type="hidden" name="MM_update" value="form1"> </form> </body> </html> Thanks 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? 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>"; ?> 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); } }
|