PHP - One Form For Inserts And Updates
Is it possible - and reasonable - to have one Form which allows Users to create a new record (i.e. do an INSERT) and which also allows Users to modify an existing record (i.e. do an UPDATE)?
When a User registers at my website, not only do they create a record in the "member" table, but one of the required fields is "First Name". What that means is that when I allow Users to edit details in their Profile - most of which were not included in registration to streamline the process - I don't have to worry about doing an INSERT, because I already created a "member" record and on the "Edit Details" page the first field is "First Name" so that is a hook so to speak where they can enter more info about themselves like... Code: [Select] - Location - Date of Birth - Interests - Bio and so on... So here is my problem which I just discovered... Also in my User Profile, I allow Users to answer several open-ended questions like... Code: [Select] 1.) Why did you decide to start your own business? 2.) What advice would you share with others on what NOT to do? The problem is that these questions exist in the "bio_question" table and the answers that I am trying to get from Users will be stored in the "bio_answer" table but no record currently exists?! So do I need both an "INSERT Answers Form" *and* an "UPDATE Answers Form", or can I combine things into one form?! Hope that all makes sense?! Debbie Similar TutorialsHi all. Im trying to insert from one form 3 items of data into to different tables. I will post the code as most of my notes are in there but first....... What is happening is the form is filled in then the first part of the form where it updates my clubs table with category ID's works fine. Nothing in the if ($result) { } seems to run. I have create some fake groups so the drop down is populated with groups already created and I have tried to select one of these groups so it can be entered into the clubs table and nothing. No errors just no answers. Does anybody no what I am doing wrong? first Ill post the form and the querys that make fields in the form... Querys //gets $validation = $_GET['new_club']; //Querys $qGetClub = "SELECT * FROM clubs WHERE validationID = '$validation'"; $rGetClub = mysql_query($qGetClub); $Club = mysql_fetch_array($rGetClub); //Query for category by name $qGetCat = "SELECT * FROM club_category WHERE catID = ".$Club['cat'].""; $rGetCat = mysql_query($qGetCat); $CatName = mysql_fetch_array($rGetCat); //query for related sub categorys. $qGetSub = "SELECT * FROM sub_categorys WHERE catID =".$Club['cat'].""; $rSubCat = mysql_query($qGetSub); // query for groups created $Groupq = mysql_query("SELECT * FROM groups WHERE memberID = '".$User['memberID']."'"); then we have the form <form action="" method="post" id="insert_clubfrm"> <tr valign="baseline"> <td colspan="2" valign="top"><br/><p>Your Chosen category was <strong><?php echo $CatName['categorys'];?></strong> Please select a sub category.</p><br></td> </tr> <tr valign="baseline"> <td width="132" valign="top" >Club Sub Category:</td> <td width="256" valign="top" ><select name='subcat'> <option value="None">Please Select One</option> <?php while ($New_SubCat = mysql_fetch_assoc($rSubCat)) { ?> <option value="<?php echo $New_SubCat['subID']; ?>"><?php echo $New_SubCat['sub_categorys']; ?></option>"<?php } ?> </select> </td> </tr> <tr valign="baseline"> <td colspan="2" valign="top" ><br/><p>If your sub category does not exist in the list please select "none" above and enter your new sub categroy below.</p><br></td> </tr> <tr valign="baseline"> <td valign="top" class="left_padding">New Sub Category</td> <td valign="top" class="left_padding"><input type="text" name="newSubCat" id="new_cat" value="" /></td> </tr> <tr valign="baseline"> <td colspan="2" valign="top" class="left_padding"><br/> If you had/have more than one site and you had to give your group of companies a name what would that name be? <br/></td> </tr> <tr valign="baseline"> <td valign="top" class="left_padding">Group Name:</td> <td valign="top" class="left_padding"><label for="other_groups"></label> <select name="other_groups" id="other_groups"> <option>None</option> <?php while ($group = mysql_fetch_assoc($Groupq)) { ?> <option value="<?php echo $group['groupID']; ?>"><?php echo $group['group']; ?></option>"<?php } ?> </select></td> </tr> <tr valign="baseline"> <td valign="top" class="left_padding">Group Name:</td> <td valign="top" class="left_padding"><label for="new_groups"></label> <input type="text" name="new_group" value=""> </td> </tr> <tr valign="baseline"> <td valign="top" nowrap="nowrap"> </td> <td valign="top"><div align="left"> <input type="submit" id="insert_clubbtn1" name="insert_clubbtn1" value="Insert record" /> </div></td> </tr> </table> </form> now the code to make the form work... if(isset($_POST['insert_clubbtn1'])){ //Process data for validation $subcat = trim($_POST['subcat']); $NewSubCat = trim($_POST['NewSubCat']); $otherg = trim($_POST['other_groups']); $newg = trim($_POST['new_groups']); //Prepare data for db insertion $newg = mysql_real_escape_string($newg); $subcat = mysql_real_escape_string($subcat); //find the new category //insert $result = mysql_query("UPDATE clubs SET `sub_category` = '$subcat' WHERE validationID ='$validation'") or die(mysql_error()); if ($result) { //if an item other than none from the list is selected then update the club with an ID relating to the group it belongs to if ($otherg !=='None') { $groupsq = mysql_query("UPDATE `clubs` SET groupID ='$otherg' WHERE validationID ='$validation')") or die (mysql_error()); } // If none is selected then $newg must have a value so create a new group in the groups table and then on the next page I will add the group in the club table if ($otherg == 'None') { $groupsq = mysql_query("INSERT INTO `groups` (memberID, group, clubID) VALUES ('".$User['memberID']."', '$newg', ''".$Club['clubID']."')"); } } if ($NewSubCat !="") { mail("email","New Sub Category Request","Dear Owner, \n\nThe club in the name of $name with a validation code of $validationID would like a new sub category called $new_cat\n\n \nTeam Me\n\n\n\n"); } $url = "/create/create_clubp3.php?new_club=$validation"; header("Location: $url"); Hi, I m doing some work for my self an because of that i been reading a lot arround about PHP, and theres something that i would like to ask a bit of enlightenment. So my question is as the title says about html form's using php to insert data into mysql, i been reading tutorials arround the interwebs and even made afew successful tests, but pretty much all tutorials use 2 files to accomplish this the html file with the form and an insert.php where the actual code is stored so this made me think is this how usually it's done? in over all you will have 1 file for the form, 1 for the insert, 1 for the edit php code and 1 for delete. How do you guys usually do it? PS: one of the tests i did was making 1 single file with all these using an switch. My interest in making this question is solo to learn how other people do it to see if i m in the right way. Thanks in advance. Hi all,
Its been a long time since last help request from real professional from here but I'm again in trouble with a much more spectacular plan I'm working on. For those who are interested in the plan then here it is: My Idea was to make a new build starting from scratch and make it as dynamical as possible. So my goal is not to make almost anything fixed in the code. I have made a decision to make a one supper large table for multiple different entries so no more joining and no more views for me.! In this help request I'm having trouble with Posting values to a page processing page lets call it record_changer.php The sole purpose of this file is to get form posts and decide what to do. Either update, delete, or insert. record_changer.php <?php include '../../config/config.inc.php'; if(is_ajax()){ # Checks if action value exists if(isset($_POST["action"]) && !empty($_POST["action"])){ $action = $_POST["action"]; # Switch case for value of action switch($action){ case "insert": datatable_insert_function(); break; case "update": datatable_update_function(); break; case "delete": datatable_delete_function(); break; } } } # Function to check if the request is an AJAX request function is_ajax(){ return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'; } function datatable_insert_function(){ } function datatable_update_function(){ } function datatable_delete_function(){ } ?>The problem. The problem is that the $insert places two entries to the DB. I cant seem to understand why.? # Test _POST values $_POST['UserID'] = '2'; $_POST['WorkID'] = '22'; $_POST['Status'] = '1'; $_POST['Code'] = '1'; $_POST['Title'] = '1'; $columns = array(); foreach(array_keys($_POST) as $name){ # Exclude Action and ID if($name == 'Action' || $name == 'ID' || $name == 'submit' ){ continue; } $columns[] = $name; } print_r($columns); echo "<br>"; $data = array_fill_keys($columns, 'NULL'); print_r($data); foreach($data as $key => $value){ $data[$key] = empty($_POST[$key]) ? 'NULL' : "'".mysql_real_escape_string($_POST[$key])."'"; } echo "<br>"; print_r($data); $insert = mysql_query('INSERT INTO datatable (ID, '.implode(', ',$columns).')VALUES (null, '.implode(',',$data).')') or die(mysql_error());No errors no nothing. Just two entries of correct data. PS. Sorry for a lot of prints in the code it is work and idea in the progress. The posts at the moment are fixed in the code so it is easier to refresh and debug. Please help if you spot the problem. Im really out of ideas. Some fresh eyes might make a difference. And Please for those who want to say it is a bad idea and why and why and so on.. Move a long.!!! Im not interested in whinging i have a great use for this and just having trouble with the two entries. Thanks. Edited by ztimer, 14 January 2015 - 03:27 PM. If one inserts acute letters, grave letters, ampersands and accented letters in xhtml they show perfectly on the page. However if one uses insert or rss feed they show as � or a square. How does one make them show correctly. If I am running a query like this: INSERT INTO `cam_locations` (`id`, `datacenter`, `address1`, `address2`, `city`, `state`, `zip`, `country`, `phone`) VALUES (1, 'Austin Data Center', '', '', 'Austin', 'Texas', '', 'United States', ''), (2, 'Sunnyvale Date Center', '', '', 'Sunnvale', 'California', '', 'United States', ''), (4, 'BoxBorough Data Center', '', '', 'Boston', 'Massachusetts', '', 'United States', '') It it possible to use mysql_insert_id() and get all the id's inserted? Maybe like an array of them or something? Thanks Hi Everyone, I have a code that stores an ID to a cookie named "cookieuser" and inserts it to a table named "cookieuser" wheneven someone new to my site visited. When someone revisits, it should only access the cookie in the computer and retrieve data in the table based on the cookie. The problem is, the code inserts multiple rows with different IDs (which is autoincremented). The codes works for returning visitors which only reads the cookie ID value. I noticed that the error reacts differently with different browsers: When in localhost, mozilla works as expected, ie inserts 4 rows, and chrome inserts 2 rows. In live server, mozilla creates 4 rows as well. The code I used is shown below. Hope someone knows the problem. Thank you in advance. Code: [Select] if (isset($_COOKIE['cookieuser'])) { $cookieuserx = $_COOKIE['cookieuser']; $sql = "SELECT userid FROM cookieuser WHERE userid = $cookieuserx"; $res = mysql_query($sql) or die(mysql_error()); if(mysql_num_rows($res) == 0){ $date = date("Y-m-d H:i:s",time()); $sqlcookie = "INSERT INTO cookieuser (userid,lastgood,lastbad,lastneutral,lastvisit,hitcount,date_registered) VALUES('','$date','$date','$date','$date','1','$date')"; $rescookie = mysql_query($sqlcookie) or die(mysql_error()); $newcookieuser = mysql_insert_id(); $expire=time()+60*60*24*360; setcookie("cookieuser", $newcookieuser, $expire,"/"); $cookieuser = $newcookieuser; }else{ $cookieuser = $_COOKIE['cookieuser']; } }else{ $date = date("Y-m-d H:i:s",time()); $sqlcookie = "INSERT INTO cookieuser (userid,lastgood,lastbad,lastneutral,lastvisit,hitcount,date_registered) VALUES('','$date','$date','$date','$date','1','$date')"; $rescookie = mysql_query($sqlcookie) or die(mysql_error()); $newcookieuser = mysql_insert_id(); $expire=time()+60*60*24*360; setcookie("cookieuser", $newcookieuser, $expire,"/"); $cookieuser = $newcookieuser; } I am trying to make a simple CMS, the table is created with this command(using php): Code: [Select] private function buildDB() { $sql = <<<MySQL_QUERY CREATE TABLE IF NOT EXISTS newcore ( id MEDIUMINT NOT NULL AUTO_INCREMENT, title VARCHAR(128), menutitle VARCHAR(128), bodytext TEXT, json VARCHAR(1024), children VARCHAR(128), template INTEGER, created VARCHAR(100), PRIMARY KEY (id) ) ENGINE=MyISAM; MySQL_QUERY; return mysql_query($sql); } everything works fine, insert, delete, select, etc. But when I update a row, the update is also done, but another row is created with the same values, but of course a new id. I do the update this way: Code: [Select] $created = time(); $sql = 'UPDATE newcore SET title="'.$title.'", menutitle="'.$menutitle.'", bodytext="'.$bodytext. '", json="'.$json.'", children="'.$children.'", template="'.$template.'", created="'.$created.'" WHERE id='.$req['id']; mysql_query($sql); All the values are entered by myself, so there is no possibility of problem in values to make it function like that. Please help me, It's driving me insane! Thanks in advance. how do i stop multiple duplications in database on my PHP script? ok i have attached a screenshot of what the database looks like after a few runs of my script. the script is designed to pull api information, input into 1 database and update another user table. i have made it run as a cron job every 60 minutes. here is my code: <?php /* You need multiple instances of this script. Each instance runs once every hour so 6 instances means one runs every 10 mins. Remember to change the API URL to reflect the different accounts or characters.*/ include "connect.php"; $columns = "`date` , `refID`, `refType`, `ownerName1`, `ownerName2`, `argName1`, `amount`, `balance`, `reason`"; //Live URL is //Assumeing that they are only donating at this time and no one is being paid to reduce the balance. Balance reduction can be done in the prize claim script so its not API delayed. if ( ($data[2] == "Player Donation") && ($data[4] == "Ship Lotto")){ $reUsed = mysql_query("SELECT * FROM bank WHERE refID='$data[1]';"); if(!empty($reUsed)){ $import="INSERT into bank($columns) values('$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]','$data[6]','$data[7]','$data[8]')"; mysql_query($import) or die(mysql_error()); } /*check to see if the player has already been credited. It checks the last recorded reference # and checks to see if the new ref # is greater, else skips the processing. You need to check since the API gives you the last 1000 journal entries or 1 week, what ever is shorter. Not just what is new since last check. Check is performed by seeing if the record in the database for the user is less then or equal to the new once. This works only because CCP's reference #s are auto increasing so they only go up if they are newer, never down.*/ $name = $data[3]; //echo "Updating account of ".$name."<br />"; $queryLastRef = mysql_query("SELECT lastRef FROM users WHERE username='$name';") or die(mysql_error()); //echo $queryLastRef; $arraylastRef = mysql_fetch_assoc($queryLastRef); $lastRef = $arraylastRef["lastRef"]; //echo "The last reference # was: ".$lastRef."<br />"; $currentRef = $data[1]; //echo "The current reference # is: ".$currentRef."<br />"; if($lastRef<$currentRef){ $amount = $data[6]; //echo "Player deposited ISK in the amount of: ".$amount."<br />"; $queryBal = mysql_query("SELECT user_iskbalance FROM users WHERE username='$name';") or die(mysql_error()); //echo "Executing the SQL command to query balance ID#: ".$queryBal."<br />"; $getBal = mysql_fetch_assoc($queryBal); //echo "Executing the SQL command to get balance amount: ".$getBal["user_iskbalance"]."<br />"; $deposit = $amount+$getBal["user_iskbalance"]; //echo "Depositing ISK in the ammount of: ".$deposit."<br />"; $importBal= "UPDATE users SET user_iskbalance=$deposit WHERE username='$name';"; //echo "Executing the SQL command to desposit: ".$importBal."<br />"; mysql_query($importBal) or die(mysql_error()); $importRefID= "UPDATE users SET lastRef='$currentRef' WHERE username='$name';"; //echo "Executing the SQL command to set the new reference: ".$currentRef."<br />"; mysql_query($importRefID) or die(mysql_error()); //echo "Success!"."<br />"; //For the sake of stats tracking update the total isk on deposit. The payout script will subtract. $queryiskDeposit = mysql_query("SELECT iskDeposit FROM stats;") or die(mysql_error()); //echo "Executing the SQL command to query the ISK deposited : ".$queryiskDeposit."<br />"; $arrayiskDeposit = mysql_fetch_assoc($queryiskDeposit); $getiskDeposit = $arrayiskDeposit["iskDeposit"]; //echo "Got total isk on deposit of: ".$getiskDeposit."<br />"; $iskDeposit = $getiskDeposit+$deposit; //echo "Inserting: ".$iskDeposit." ISK"."<br />"; $importiskDeposit= "UPDATE stats SET iskDeposit='$iskDeposit';"; //echo "Executing the SQL command to desposit: ".$importBal."<br />"; mysql_query($importiskDeposit) or die(mysql_error()); //echo "<br />"; //echo "<br />"; //echo "NEXT!<br />"; //echo "<br />"; } else{ //echo "There is no update for ".$name." because ".$lastRef." is not less then or equal to ".$currentRef."<br />"; //echo "<br />"; //echo "<br />"; //echo "NEXT!<br />"; //echo "<br />"; } //echo "DEBUG for ".$name." lastRef ".$lastRef." and currentRef ".$currentRef."<br />"; //update the time that last update ran $today = date("Ymd G:i"); mysql_query("UPDATE stats SET iskLastUpdate='$today';") or die(mysql_error()); //echo "Updating Date to: ".$today; //echo "<br />"; //echo "<br />"; //echo "NEXT!<br />"; //echo "<br />"; } } ?> can anyone help me stop it duplicating the entries in the database please? I tried inserting a town into my database but only the first word gets inserted?! eg: Abbots Langley only Abbots gets inserted?! Code: [Select] if(isset($_POST["register"])) { // Your code here to handle a successful verification $RSTOWN = $_POST['rsTown']; $rsGender = $_POST['rsGender']; $RSUSER = $_POST['RSUSER']; $RSPASS = $_POST['RSPASS']; $rsEmail = $_POST['rsEmail']; $rsMobile = $_POST['rsMobile']; $rsAge = $_POST['rsAge']; $to = 'info@mypubspace.com, '.$rsEmail; //define the subject of the email $subject = 'Welcome '.$RSUSER.' to My Pub Space'; // message $message = ' <html> <head> <title>'.$subject.'</title> </head> <body> <table> <tr> <td>Name:</td> <td>'.$RSUSER.'</td> </tr> <tr> <td>Email:</td> <td>'.$rsEmail.'</td> </tr> <tr> <td>Town:</td> <td>'.$rsTown.'</td> </tr> <tr> <td>Telephone:</td> <td>'.$rsMobile.'</td> </tr> <tr> <td>Age:</td> <td>'.$rsAge.'</td> </tr> <tr> <td>Password:</td> <td>'.$RSPASS.'</td> </tr> </table> </body> </html> '; // To send HTML mail, the Content-type header must be set $headers = 'MIME-Version: 1.0' . "\r\n"; $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; // Additional headers $headers .= 'To:' .$to. "\r\n"; $headers .= 'From:' .$rsEmail. "\r\n"; // Mail it mail($to, $subject, $message, $headers); $sql = "INSERT INTO members_copy (RSTOWN, RSGENDER, RSUSER, RSPASS, RSEMAIL, RSMOBILE, RSAGE) VALUES ('$rsTown', '$rsGender', '$RSUSER', '$RSPASS', '$rsEmail', '$rsMobile', '$rsAge');"; //echo $sql; mysql_query($sql); hi, i made my own page, but when i do an insert using mysql, jquery and php, the arabic text does not show properly it is a comments page. here is the DB structure Code: [Select] CREATE TABLE IF NOT EXISTS `app_comments` ( `comment_id` int(20) NOT NULL auto_increment, `comment` text NOT NULL, `user_id` int(20) NOT NULL, `comment_date` date NOT NULL, `app_id` int(20) NOT NULL, PRIMARY KEY (`comment_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=35 ; here is the jquery piece that transfers to php code. Code: [Select] function submit_comment(){ $(".post_comments_button").click(function() { var post_comments = $('.post_comments').val(); var app_id = $('#app_id').val(); //alert (app_id); if(confirm('Add Comment?')) { var string = "task=add_comment&app_id=" + app_id + "&comment="+post_comments; $.ajax({ url : "appajax.php", type : "POST", data : string, success : function(data) { alert(data); window.location.reload(true); } }); } /**/ }); }and here is the acutal insert code in php $new_appquery = 'INSERT INTO app_comments (comment, user_id, app_id,comment_date) VALUES ("' . $comment . '",' . $user_id . ', ' . $app_id . ',NOW());'; and the actual problem is, the arabic text shows like this in my application: Quote بالتوفيق للريال how can i solve this issue? Hi i have a drop down menu for date which is meant to insert all 3 values into a date column bt is only sending the year how can i fix it <select name="date_of_birth"> <option value="1">January <option value="2">February <option value="3">March <option value="4">April <option value="5">May <option value="6">June <option value="7">July <option value="8">August <option value="9">September <option value="10">October <option value="11">November <option value="12">December </select> <select name="date_of_birth"> <option value="1">1 <option value="2">2 <option value="3">3 <option value="4">4 <option value="5">5 <option value="6">6 <option value="7">7 <option value="8">8 <option value="9">9 <option value="10">10 <option value="11">11 <option value="12">12 <option value="13">13 <option value="14">14 <option value="15">15 <option value="16">16 <option value="17">17 <option value="18">18 <option value="19">19 <option value="20">20 <option value="21">21 <option value="22">22 <option value="23">23 <option value="24">24 <option value="25">25 <option value="26">26 <option value="27">27 <option value="28">28 <option value="29">29 <option value="30">30 <option value="31">31 </select> <select name="date_of_birth" id="year"> <?php $year = date("Y"); for($i=$year;$i>$year-50;$i--) { if($year == $i) echo "<option value='$i' selected>Current Year</option>"; else echo "<option value='$i'>$i</option>"; } ?> Hi, I am new to PHP and mySQL. I am working on a golf site where it will need to have the user update info through text boxes. There are two things: 1) It will need to keep an average of the last 6 rounds. The user will need to be able to input the current round score and have it bump the oldest score of the database. 2) Also, i have a database of players that will populate a <select>. Is there a way to have the user be able to add/delete player names from this database? My question is what functions are needed to get this done. And how does one go about implementing them. Thanks in advance! Taylor i dont know why it doesnt update the db..someone help?? $connection=mysql_connect("$server", "$username", "$password") or die("Could not establish connection"); mysql_select_db($database_name, $connection) or die ("Could not select database"); $strEditProfile = "UPDATE tblemployee SET EmployeeName='".$_POST["edit_thename"]."', Address1 = '".$_POST[edit_address1]."', Address2 = '".$_POST[edit_address2]."', DesignationID = '".$_POST[edit_des]."', Postcode = '".$_POST[edit_postcode]."', State = '".$_POST[edit_state]."', Country = '".$_POST[edit_country]."', Tel1 = '".$_POST[edit_contact]."' WHERE EEmail='".$_POST["edit_email"]."'"; $resEditProfile = mysql_query($strEditProfile); if($resEditProfile) echo "<img src=\"images/valid.jpg\" /> Profile updated!"; else echo "><img src=\"images/warning.jpg\">Error!"; I have a script that has a foreach loop. The script ususally runs for VERY VERY long time ( i have set_time_limit(0) Now what I need it to do is to echo some string at the end of each loop. However it doesn't. The script displays everything after its finished. That's not acceptable for me. I'm running xampp for windows. Would there be any feasible way of combining the two Update statement below into one? The Members Table has id, username, password, and application_id The Application Table has the application id, the users application information and whether or not the application is approved. if($_GET['approved']=="update"){ $approved=$_GET['approved']; $approved=sanitize($approved); if($approved=="y"){ $id=(int)$_GET['id']; $username=$_GET['username']; $username=sanitize($username); $password=$_GET['password']; $password=sanitize($password); $approved_sql='UPDATE members SET username="$username" password="$password" application_id="$id"'; $approved_result=mysql_query($approved_sql); $approved_rows=mysql_affect_rows(); $update_approved_sql='UPDATE application SET approved="y" WHERE id="$id"'; $update_approved_result=mysql_query($update_approved_sql); $update_approved_rows=mysql_affect_rows(); if($approved_rows==1 && $update_approved_rows==1{ header("Location: ./index.php??admincp=investors&view=applications&id=1&approved=updated"); } } } I got to thinking late last night (which generally leads to trouble), so please be gentle if some educating is in order, as I suppose I will touch a few related issues. As I develop my database, I will include two seperate columns. One for the time/date that an order was placed. A second for the time/date that an order is updated (unless there's a better way, please inform me). I pressume that if a record is updated several times, it will continually overwrite the time/date to the point that I will only see the latest update. Now I was wondering if I could create a third column to keep count of the number of times a record had been updated, so if it were altered 16 times, I would know when the last update occurred, and have the count number also. Will something like this coding work? SELECT updates FROM myTable WHERE id="$id" $updates =n if n<1, n=1 }else{ n++
So basically I am still starting off when it comes to learning PHP/MySQLi... I am looking to make a script that can do the following:
If I update say my homepage by just my normal cPanel editor plus another page named "News" but through an Admin section on my site (so basically inserting a new row into the database instead of manually doing it through my cPanel) - I would like it to display in a section on my homepage that days date along with the list of pages that were updated underneath it within that date, but with names I give the pages so instead of just saying index.php updated, I want it do say "Home Page Updated." I did have an attempt at this but just couldn't get it right. I would like to set a limit on how many different dates can be shown also.
Example:
July 12, 2014
Home Page Updated.
News Headlines Updated.
Staff Members Updated.
July 11, 2014
Home Page Updated.
July 10, 2014
Home Page Updated.
Contact Us Updated.
and so on...
Thank you to anyone who replies with some input, I have been going crazy trying to get this right and I just can't get it but badly want it.. Ok this has been driving me crazy for days now. I need to update my DB with multiple data parsed from an XML feed. I need some help in putting together the query. Currently I have: Code: [Select] $xml= 'test-feed.xml'; // URL for feed. try{ $feed = new SimpleXMLElement($xml, null, true); }catch(Exception $e){ echo $e->getMessage(); exit; } $sqlxml = ""; $arr = array(); foreach($feed->property as $property) { $propertyid = (string)$property->id; foreach($property->images->image as $image) { $i = 0; $url = (string)$image->url; $arr[] = "UPDATE property SET url = '$url' WHERE prop_id = '$propertyid', "; $i++; } } foreach($arr as $result) $sql .= $result; $sql = rtrim($sql, ","); echo $sql; if(!mysql_query($sql)){ echo '<h1 style="color: red;">Error</h1><p>', mysql_error(), '</p>'; } else { echo '<h1 style="color: red;">Property data successfully added to database!</h1>'; } This structures the query correctly for a single update but repeats it which then throws a MYSQL Syntax error. I am not sure of the correct syntax to use for multiple inserts?? What I get returned at the moment is: Code: [Select] UPDATE property SET url = 'ImageId=X1000245' WHERE prop_id = 'A1234', UPDATE property SET url = 'ImageId=X1000296' WHERE prop_id = 'A1234', UPDATE property SET url = 'ImageId=P3&ImgId=X1000237' WHERE prop_id = 'ABC1234', Need some intervention guys Thanks in advance GT Hi guys, I'm developing a website which allows people to connect and follow each other's activity (like Twitter, for example). To simplify everything, let's say I only have 2 tables: 1. Followers id | follower_id | id_to_follow ------------------------------------ 2. Activity id | member_id | message | time ----------------------------------------- Let's say John is following Jane and Bob. I want to create a "news" page and display the last 20 messages from Bob and Jane, chronologically. For small numbers, I'd do something like this: Select everything from the Activity table, check for every entry if the member is a friend of John's (in the Followers table) and, if so, display the message, ORDER BY `id` DESC. But, this is very inefficient, I guess, for larger numbers (I can't even think about how many queries would take to do this on a site like Twitter...). Any ideas of how to do the same thing more efficiently? Thank you. I have a form which shows products ordered from a catalog, it used to work fine when I had individual change buttons for each item, now I have to have multiple check boxes for removing items and the ability to change the quantities of multiple items with a single button. I know you have to use foreach and arrays for this but I am confusing myself trying to make the changes for it to update the correct items. Attached is a pic of what the form looks like and is how it is supposed to function here is the form part Code: [Select] <?php for ($basket_counter=0;$basket_counter<$_SESSION['ses_basket_items'];$basket_counter++) { $price=sprintf("%01.2f",$ses_basket_price[$basket_counter]); $quantity=$ses_basket_amount[$basket_counter]; $code=$ses_basket_stockcode[$basket_counter]; $itemID=$ses_basket_id[$basket_counter]; $name=$ses_basket_name[$basket_counter]; $image=$ses_basket_image[$basket_counter]; if ($country='AU') { $price=sprintf("%01.2f",($price*1.1)); $unit=sprintf("%01.2f",($price/$quantity)); } else { $unit=sprintf("%01.2f",($price/$quantity)); } ?><form method='post' action='' target="_self"> <tr> <td align='center' class='rescon' style="border-bottom:solid #330000 1px;"><input type="checkbox" name="remove[]" value="<?php echo $itemID; ?>" /></td> <td align='left' class='rescon' style="border-bottom:solid #330000 1px;"><img src="product_images/<?php echo $image; ?>" width="60" alt="<?php echo $name; ?>" title="<?php echo $name; ?>" /></td> <td align='left' class='rescon' style="border-bottom:solid #330000 1px;"><font size="+1"><?php echo $name; ?></font><br/><?php echo $code; ?></td> <td align='left' class='rescon' style="border-bottom:solid #330000 1px;"> </td> <td align='center' class='rescon' style="border-bottom:solid #330000 1px;"><input name="price" type="hidden" value="<?php echo $unit; ?>"><input type="hidden" name="pageLink" value="<?php echo $pageLink; ?>" /><input name="basket[]" type="hidden" value="<?php echo $itemID; ?>"><input name="quantity[]" style="vertical-align:middle;" type="text" value="<?php echo $quantity; ?>" size="2" maxlength="5"> </td> <td align='center' class='rescon' style="border-bottom:solid #330000 1px;">$<?php echo $unit; ?></td> <td class='rescon' align='right' bgcolor="#FFFF00" style="border-bottom:solid #330000 1px;">$<?php echo $price; ?> </td> </tr> <?php } if ($country='AU') { $totalprice=sprintf("%01.2f",array_sum($ses_basket_price)); $totalprice=sprintf("%01.2f",($totalprice*1.1)); } else { $totalprice=sprintf("%01.2f",array_sum($ses_basket_price)); } $totalitems=array_sum($ses_basket_amount); ?> <tr><td align='left' colspan='4' valign="top" class='cartbot'> </td> <td align='left' valign="top" class='cartbot'><?php echo $totalitems; ?> Items</td> <td align='right' colspan='2' class='cartbot'><?php echo "<b>Subtotal: $".$totalprice." </b>"; ?></b></td> </tr> <tr> <td align='left' colspan='5' valign="top"><input type="submit" id="change" name="change" style="vertical-align:middle;" value="Change"></td> <td align='right' colspan='2'> </td> </tr></form> and here is the processing part at the top of the page which I have sorta shagged, could use some help getting it to update the correct items for remove and quantity changes // cart application if (isset($_POST['change'])) { $basket = $_POST['basket']; // check faor AU to include GST if ($country='AU') { $itemprice = sprintf("%01.2f",(($_POST['price']/11)*10)); } else { $itemprice = $_POST['price']; } $itemqty = $_POST['quantity']; $newprice = ($itemprice*$itemqty); if (($basket!="") && (isset($_POST['change']))){ if ($_SESSION['ses_basket_items']){ // basket position $basket_position_counter=0; // double entry flag set to NO $double=0; // Check for existing basket id if ($_SESSION['ses_basket_items']>0){ foreach ($ses_basket_id as $basket_item){ if ($basket_item==$basket){ // If exist flag for update $double=1; $basket_position=$basket_position_counter; } // Add new basket position $basket_position_counter++; } } // Update basket with new quantity and price if ($double==1){ $ses_basket_amount[$basket_position]=$itemqty; $ses_basket_price[$basket_position]=$newprice; } } // Delete Item when set to 0 if ($itemqty == "0") { array_splice ($ses_basket_name, $basket_position, 1); array_splice ($ses_basket_amount, $basket_position, 1); array_splice ($ses_basket_price, $basket_position, 1); array_splice ($ses_basket_stockcode, $basket_position, 1); array_splice ($ses_basket_image, $basket_position, 1); array_splice ($ses_basket_id, $basket_position, 1); $_SESSION['ses_basket_items']--; } if (isset($remove) && ($remove!='')) { $remove = $_POST['remove']; if(count($remove) > 0){ foreach($remove AS $removed){ array_splice ($ses_basket_name, $basket_position, 1); array_splice ($ses_basket_amount, $basket_position, 1); array_splice ($ses_basket_price, $basket_position, 1); array_splice ($ses_basket_stockcode, $basket_position, 1); array_splice ($ses_basket_image, $basket_position, 1); array_splice ($ses_basket_id, $basket_position, 1); $_SESSION['ses_basket_items']--; } } } } if ($_SESSION['ses_basket_items']==0){ unset($_SESSION['ses_basket_items']); unset($_SESSION['ses_basket_name']); unset($_SESSION['ses_basket_amount']); unset($_SESSION['ses_basket_price']); unset($_SESSION['ses_basket_stockcode']); unset($_SESSION['ses_basket_image']); unset($_SESSION['ses_basket_id']); header("Location: $pageLink"); } } the array variables I have here are $basket, $remove and $quantity. |