PHP - Update Works, But Inserts Another Row
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. Similar TutorialsI created this code to upload a member's main picture on his member page on website. I'll only include the query part of the code since that's what is relevant to my problem. The idea is basically to upload a new picture onto the database if no picture already exists for that member and display the picture on the page. If a picture already exists, then the script replaces the old picture with the new one upon upload. But for whatever reason I don't understand, when I try to replace the old pic, it gets inserted in a new row on the database instead of replacing the old row, and the new pic gets displayed on the web page alongside the old. Code: [Select] $query = "SELECT username FROM images WHERE member_id = '".$_SESSION['id']."' AND image_cartegory = 'main'"; $result = @mysql_query($query); $num = @mysql_num_rows($result); if ($num> 0) { //Update the image $update = mysql_query("UPDATE images SET image = '" . $image['name'] . "' WHERE member_id = '".$_SESSION['id']."' AND image_cartegory = 'main'"); $_SESSION['error'] = "File updated successfully."; //really should be session success message. header("Location: member.php"); exit; } else { // NOTE: This is where a lot of people make mistakes. // We are *not* putting the image into the database; we are putting a reference to the file's location on the server $sql = "insert into images (member_id, image_cartegory, image_date, image) values ('{$_SESSION['id']}', 'main', NOW(), '" . $image['name'] . "')"; $result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error()); $_SESSION['error'] = "File uploaded succussfully."; //really should be session success message. header("Location: member.php"); } So can anyone tell me what the problem is? Could the fact that my insert script actually uploads the image onto a folder on my server and only stores the path name in the database have anything to contribute to the mixup? Appreciate your responses in advance. I am moving my website to a new Service Provider. The script I use for multiple updating worked on the older server but not on the new one. It shows the information but does not update the records. Any help would be greatly appreciated. Old Server : PHP 5.2.11 MYSQL: 5.0.92-community New Server : PHP 5.2.17 MYSQL: 5.1.47-community Script: <?php include("head.php"); $host="localhost"; // Host name $username="xxxxxxx"; // Mysql username $password="xxxxxxx"; // Mysql password $db_name="xxxxxxx"; // Database name $tbl_name="xxxxxxx"; // Table name // Connect to server and select databse. mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); $sql="SELECT * FROM $tbl_name limit 20"; $result=mysql_query($sql); // Count table rows $count=mysql_num_rows($result); ?> <title>PowerMan South Africa</title> <META HTTP-EQUIV="Pragma" CONTENT="no-cache"> <META HTTP-EQUIV="Expires" CONTENT="-1"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link rel="stylesheet" href="style.css" type="text/css" media="screen" /> <style type="text/css" media="screen,projection"> @import url(calendar.css); </style> </head> <table width="500" border="0" cellspacing="1" cellpadding="0"> <form name="form1" method="post" action=""> <tr> <td> <table width="500" border="0" cellspacing="1" cellpadding="0"> <tr> <td align="center"><strong>ID</strong></td> <td align="center"><strong>Company</strong></td> <td align="center"><strong>contact</strong></td> <td align="center"><strong>Email</strong></td> <td align="center"><strong>Telephone</strong></td> <td align="center"><strong>Type</strong></td> </tr> <?php while($rows=mysql_fetch_array($result)){ ?> <tr> <td align="center"><? $id[]=$rows['id']; ?><? echo $rows['id']; ?></td> <td align="center"><input name="company[]" type="text" id="company" value="<? echo $rows['company']; ?>"></td> <td align="center"><input name="contact[]" type="text" id="contact" value="<? echo $rows['contact']; ?>"></td> <td align="center"><input name="email[]" type="text" id="email" value="<? echo $rows['email']; ?>"></td> <td align="center"><input name="telephone[]" type="text" id="telephone" value="<? echo $rows['telephone']; ?>"></td> <td align="center"><input name="type[]" type="text" id="type" value="<? echo $rows['type']; ?>"></td> </tr> <?php } ?> <tr> <td colspan="4" align="center"><input type="submit" name="Submit" value="Submit"></td> </tr> </table> </td> </tr> </form> </table> <?php // Check if button name "Submit" is active, do this if($Submit){ for($i=0;$i<$count;$i++){ $sql1="UPDATE $tbl_name SET company='$company[$i]', contact='$contact[$i]', email='$email[$i]',type='$type[$i]', telephone='$telephone[$i]' WHERE id='$id[$i]'"; $result1=mysql_query($sql1); } } if($result1){ header("location:update_multiple.php"); echo "<meta http-equiv=Refresh content=0;url=update_multiple.php>"; } mysql_close(); ?> 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. Hi 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 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; } 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 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 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 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. Hi i have this simple update form and scrip but somehow it doesnt seem to be update the field on the database can someone help out please. The html form is the second form bellow where the action send to status_update.php HTML FORM Code: [Select] <?php include("../header.html"); ?> <?php include("header_news.html"); extract($_REQUEST,EXTR_SKIP); ?><?php /* print("sfilm_refnum = $sfilm_refnum<BR>"); print("sfilm_addr01 = $sfilm_addr01<BR>"); print("sfilm_postcode = $sfilm_postcode<BR>"); print("Film Client = $fclient<BR>"); */ ?> <form id="search" action="list.php" method="post" name="search"> <table width="780" border="0" cellspacing="0" cellpadding="4" bgcolor="#eeeeee"> <tr> <td align="right" width="140"></td> <td width="320"><span class="hofblack10"> </span> </td> <td align="center" width="100"><input type="hidden" name="lstart" value="<?php print("$lstart"); ?>" /><input type="hidden" name="lend" value="<?php print("$lend"); ?>" /><input type="hidden" name="lamount" value="<?php print("$lamount"); ?>" /></td> <td align="center" width="100"></td> <td align="right"></td> </tr> </table> </form> <table width="780" border="0" cellspacing="0" cellpadding="4" bgcolor="#4050c4"> <tr> <td width="60" class="hofwhite10">action</td> <td width="140"><span class="hofwhite14">DATE</span></td> <td width="80"><span class="hofwhite14">ID</span></td> <td><span class="hofwhite14">News Titile</span></td> <td width="100"><span class="hofwhite14">Status</span></td> </tr> <tr height="0"> <td bgcolor="white" width="60"></td> <td bgcolor="white" width="140" height="0"></td> <td bgcolor="white" width="80" height="0"></td> <td bgcolor="white" height="0"></td> <td bgcolor="white" width="100" height="0"></td> </tr> </table><table width="780" border="0" cellspacing="0" cellpadding="4"><tr> <td width="60"></td> <td width="80"></td> <td><a class="blueullrg" href="add.php">Add News</a></td> <td align="right" width="120"></td> </tr> <tr height="0"> <td width="60" height="0"></td> <td width="80" height="0"></td> <td height="0"></td> <td align="right" width="120" height="0"></td> </tr> </table> <?php //get the DB connection variables include("../../../includes/config.php"); //connect to DB $connection = @mysql_connect($db_address,$db_username,$db_password) or die("Couldn't CONNECT."); $db = @mysql_select_db($db_name, $connection) or die("Couldn't select DATABASE."); $query2="SELECT * FROM news WHERE !(news_status='deleted')"; $result2 = mysql_query($query2) or die("Couldn't execute QUERY - Select NEWS Qty"); $fqty = mysql_num_rows($result2); //SELECT or FIND the same USERNAME $query3="SELECT * FROM news WHERE !(news_status='deleted') ORDER BY news_id DESC"; $result3 = mysql_query($query3) or die("Couldn't execute QUERY - Select NEWS"); while ($row = mysql_fetch_array($result3)) { $news_id = $row['news_id']; $news_title = $row['news_title']; $news_story = $row['news_story']; $news_image = $row['news_image']; $news_image_caption = $row['news_image_caption']; $news_image_link = $row['news_image_link']; $news_date_day = $row['news_date_day']; $news_date_month = $row['news_date_month']; $news_date_year = $row['news_date_year']; $news_status = $row['news_status']; $news_website = $row['news_website']; $news_date_created = $row['news_date_created']; $news_date_modified = $row['news_date_modified']; ?> <table width="780" border="0" cellspacing="0" cellpadding="4" bgcolor="#eeeeee"> <tr> <td width="60"><span class="hofblack10"> <?php if($news_status=="deleted"){ print("<a class='hifblack10'>deleted</span>"); }ELSE{ print("<a class='blueul' href='edit.php?id=$news_id'>edit</a>"); } ?> </span></td> <td width="140"><span class="titlegrey12"> <?php if(!$news_date_day) { echo "00"; } else{ echo $news_date_day; } echo "/"; if(!$news_date_month) { echo "00"; }else{ echo $news_date_month; } echo "/"; if(!$news_date_year) { echo "0000"; }else{ echo $news_date_year; } ?> </span></td> <td width="80"><span class="titlegrey12"><?php print("$news_id"); ?></span> </td> <td><?php if($news_status=="deleted") { print("<class='hofblack10'>$news_title</span>"); }ELSE{ print("<a class='blueul' href='edit.php?id=$news_id'>$news_title</a>"); } ?></td> <td width="100"> <form id="list_update" action="status_update.php" method="post" name="list_update"> <select name="newnstatus" size="1"> <option <?php if($row['news_status'] == "") { print("selected"); } ?> selected="selected" value="">Status...</option> <option <?php if($row['news_status'] == "on") { print("selected"); } ?> value="on">On</option> <option <?php if($row['news_status'] == "off") { print("selected"); } ?> value="off">Off</option> <option <?php if($row['news_status'] == "deleted") { print("selected"); } ?> value="deleted">Delete</option> </select> <input type="hidden" name="nstatus" value="<?php echo $row[news_status]; ?>" /> <input type="hidden" name="id" value="<?php echo $row[news_id]; ?>" /> <input type="submit" name="update" value="update" /> </form> </td> </tr> <tr height="0"> <td bgcolor="white" width="60"></td> <td bgcolor="white" width="140" height="0"></td> <td bgcolor="white" width="80" height="0"></td> <td bgcolor="white" height="0"></td> <td bgcolor="white" width="100" height="0"></td> </tr> </table> <?php } mysql_close($connection);//}?> <table width="780" border="0" cellspacing="0" cellpadding="4"> <tr> <td width="60"></td> <td width="80"></td> <td><a class="blueullrg" href="add.php">Add News</a></td> <td align="right" width="120"></td> </tr> </table><?php // include("list_navigation.html"); ?> <?php include("../footer.html"); ?> </div></body></html> The action script php Code: [Select] <?php /* echo "fstatus: ".$fstatus."<BR>"; echo "id: ".$id."<BR>"; echo "fclient: ".$fclient."<BR>"; echo "newfstatus: ".$newfstatus."<BR>";*/ //set the date of agreement $timestamp = date('l jS \of F Y h:i:s A'); //get the DB connection variables include("../../../includes/config.php"); //connect to DB $connection = @mysql_connect($db_address,$db_username,$db_password) or die("Couldn't CONNECT."); $db = @mysql_select_db($db_name, $connection) or die("Couldn't select FILMS DATABASE."); // All appears well, so enter into database $query= "UPDATE news SET news_status = '$newnstatus' WHERE news_id='$id'"; $result = mysql_query($query) or die("could not execute query - Update FILMS Record to DB"); //setup an email to the Admin @ hof, w/o attachment $emailto="xx@xxx.co.uk"; $emailfrom="no-reply@xxxx.co.uk"; $emailsubject="xx Record Updated"; $emailmessage="Hello Registrar\n\n"; $emailmessage.="News ID: ".$id."\n"; $emailmessage.="Updated on: ".$timestamp."\n\n"; $emailmessage.="Status was: ".$nstatus."\n"; $emailmessage.="Status now: ".$newfnstatus."\n"; $emailmessage.="Thank you,\n\n"; $emailmessage.="Web Site ROBOT\n"; $emailmessage.="(Administrator)\n"; $emailmessage.="xxx.co.uk | xxx.biz\n"; $emailmessage.="----------------------------------------------\n"; $emailmessage.="e. http://www.xxx.co.uk/contact.php\n"; $emailmessage.="w. http://www.xxx.co.uk\n"; $emailheader="From: xxx.co.uk<$emailfrom>"; $emailheader .= 'Cc: xxx@xxx.co.uk'."\r\n"; $emailheader .= 'Bcc: xxx@xxxxx.co.uk'."\r\n"; $ok=mail($emailto,$emailsubject,$emailmessage,$emailheader); mysql_close($connection); if ($ok) { header("Location: list.php"); /* Redirect browser */ exit; } else { $errmsg="There was a problem, please try later or telephone us direct."; $errsta="1"; include("edit_error.html"); //echo "<p>Mail could not be sent. Sorry!</p>"; exit; } ?> Thanks in advance Can anyone post a generic update function to update mysql table. The manual approach: update $tablename set $column1='a', $column2='b' where $id=$value; what Im basically trying to do is just like a phpmyadmin function... you select rows you want to update with a checkbox and then it takes you to a page where the rows that are clicked are shown in forms so that you can view and edit info in them... and then have 1 submit button to update them all at once. Good morning. I am looking fo some help with an update script to update all rows in a table. This is what I have for a form and all looks well. form.php <?php // run the query and put the results in an array variable called $result $result = mysql_query("SELECT * FROM table ORDER BY 'id', 'title', 'text', 'number'"); print "<form method='post' action='update.php'> <table width='100%' border='0' cellspacing='1' cellpadding='1'><tr> <td align='center'><strong>ID</strong></td> <td align='center'><strong>Title</strong></td> <td align='center'><strong>text</strong></td> <td align='center'><strong>Number</strong></td> </tr>\n"; // start a loop to print all of the courses with their book information // the mysql_fetch_array function puts each record into an array. each time it is called, it moves the array counter up until there are no more records left while ($Update = mysql_fetch_array($result)) { // start displaying the info; the most important part is to make the name an array (notice bookinfo[$i]) print "<td align='center'><p>{$Update['id']}</p></td>\n"; print "<td align='center'><input type='text' name='title' value='{$Update['title']}' /></td>"; print "<td align='center'><input type='text' size='40' name='text' value='{$Update['text']}' /></td>\n"; print "<td align='center'><input type='text' size='40' name='number' value='{$Update['number']}' /></td>\n"; print "</tr>\n"; // add 1 to the count, close the loop, close the form, and the mysql connection } print "<tr> <td colspan='4' align='center'><input type='submit' value='submit' />"; print "</td> </tr> </table> </td> </tr> </form> </table>"; print "</tr>\n"; ?><br /><br /> My question is. How do I update this info into the database with the proper info. ie. Update.php? I'm new to PHP and I was able to figure out how to populate data from my database into my text fields. I am trying to add the update information to the same php file; however, I am now receiving errors within the data I was able to populate,
Notice: Undefined variable: stmt in C:\xampp\htdocs\Cust_App\update.php on line 47 and errors with the Update statement
Notice: Undefined variable: stmtupdate in C:\xampp\htdocs\Cust_App\update.php on line 96 I had defined the customerID variable above in the code, but it isn't being captured from here. I tried setting up this query like the one which gathered the data, but I'm off by a little bit. I would like the option to be able to update all fields. Any help is appreciated. I'm trying to learn as I may get asked to update other forms in the future. (new boss asks a lot) <?php require_once('database.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"> <!-- the head section --> <head> <title>My Guitar Shop</title> <link rel="stylesheet" type="text/css" href="main.css" /> </head> <!-- the body section --> <body> <div id="page"> <div id="header"> <h1>SportsPro Technical Support</h1> <p>Sports management software for the sports enthusiast.</p></h1> </div> <div id="main"> <h1>View/Update Customer</h1> <form action="update.php" method="get" > <?php if(isset($_GET['customerID'])) { $customerID = filter_input(INPUT_GET, 'customerID', FILTER_SANITIZE_NUMBER_INT); $sql = "SELECT * FROM customers WHERE customerID =$customerID "; $stmt = $db->query($sql); } ?> <div id="content"> <!-- display a table of products --> <h2>Customers</h2> <form method = "edit"> <?php foreach ($stmt as $cust) { ?> <div> <label>First Name</label> <input type="text" name="name" class ="form-control" value ="<?php echo $cust['firstName']; ?>"> </div><br> <div> <label>Last Name</label> <input type="text" name="name" class ="form-control" value ="<?php echo $cust['lastName']; ?>"> </div><br> <div> <label>Address</label> <input type="text" name="address" class ="form-control" value ="<?php echo $cust['address']; ?>"> </div><br> <div> <label>City</label> <input type="text" name="city" class ="form-control" value ="<?php echo $cust['city']; ?>"> </div><br> <div> <label>State</label> <input type="text" name="state" class ="form-control" value ="<?php echo $cust['state']; ?>"> </div><br> <div> <label>Country</label> <input type="text" name="countryCode" class ="form-control" value ="<?php echo $cust['countryCode']; ?>"> </div><br> <div> <label>Zip Code</label> <input type="text" name="postalCode" class ="form-control" value ="<?php echo $cust['postalCode']; ?>"> </div><br> <div> <label>Email </label> <input type="text" name="email" class ="form-control" value ="<?php echo $cust['email']; ?>"> </div><br> <div> <label>Phone Number </label> <input type="text" name="phone" class ="form-control" value ="<?php echo $cust['phone']; ?>"> </div><br> <div> <label>Password </label> <input type="text" name="password" class ="form-control" value ="<?php echo $cust['password']; ?>"> </div><br> <div> <?php } ?> <input type="Submit" name="Update_Data" value="Update Data"></input> <?php $sql2 = "UPDATE customers SET firstName = ". $stmtupdate['firstName']." WHERE customerID =$customerID "; $stmtupdate = $db->query($sql2); ?> </div> </div> <div id="footer"> <p> © <?php echo date("Y"); ?> SportsPro, Inc. </p> </div> </div><!-- end page --> </body> </html>
As the title says I need help with multiple update system.. Can't really get it to work at all >.< Here's some code: $selectt = mysql_query("SELECT * FROM exercises WHERE user='" . $_SESSION["user"] . "' AND exname='" . $_GET["edit"] . "'"); echo '<form method="POST" action="exercises.php?edited">'; echo '<div id="newexx">'; while($raw = mysql_fetch_array($selectt)) { echo '<input type="text" name="up[' . $raw["id"] . ']" value="' . $raw["swe"] . '">'; echo '<input type="text" name="up1[' . $raw["id"] . ']" value="' . $raw["eng"] . '"><br>'; echo '<input type="hidden" name="id[' . $raw["id"] . ']">'; } echo '</div>'; echo '<input type="submit" value="Update Exercise">'; echo '</form>'; if(isset($_GET["edited"])) { $swe = $_POST["up"]; $eng = $_POST["up1"]; $id = $_POST["id"]; foreach($id as $value => $index) { $update = "UPDATE exercises SET swe='".$swe."', eng='".$eng."' WHERE id='".$index."'"; mysql_query($update); } Would be thankful for reply! Hi Guys, I want my UPDATE function from the code below to only update those fields that are NOT empty - if they are empty on submit then do not update or change any values from that field. I know that sounds odd, but with my file fields, when I submit to change something else at a later date it will overwrite the photo, download1,2 & 3 values and as a result I loose my files from the mysql table. Cheers, S <?php include('config.php'); if (isset($_GET['Ter']) ) { $ter = (int) $_GET['Ter']; if (isset($_POST['submitted'])) { //Photo & Document Upload Upload $timestamp_photo = time(); $timestamp_download1 = time(); $timestamp_download2 = time(); $timestamp_download3 = time(); //This is the directory where the files will be saved //Photos $photo_target = "images/"; $photo_target = $photo_target .$timestamp_photo. basename( $_FILES['photo']['name']); //Documents $download_target = "documents/"; $download_target1 = $download_target .$timestamp_download1. basename( $_FILES['download1']['name']); $download_target2 = $download_target .$timestamp_download2. basename( $_FILES['download2']['name']); $download_target3 = $download_target .$timestamp_download3. basename( $_FILES['download3']['name']); //This gets all the other information from the form $photo = ($_FILES['photo']['name']); $download1 = ($_FILES['download1']['name']); $download2 = ($_FILES['download2']['name']); $download3 = ($_FILES['download3']['name']); //Pause Photo/Document Upload foreach($_POST AS $key => $value) { $_POST[$key] = mysql_real_escape_string($value); } $sql= "UPDATE `ter` SET `Ter` = '{$_POST['Ter']}' , `BranchName` = '{$_POST['BranchName']}' , `BranchAddress` = '{$_POST['BranchAddress']}' , `BranchTel` = '{$_POST['BranchTel']}' , `BranchEmail` = '{$_POST['BranchEmail']}' , `BranchLink` = '{$_POST['BranchLink']}' , `Theme` = '{$_POST['Theme']}' , `LocalInfo` = '{$_POST['LocalInfo']}' , `BranchInfo` = '{$_POST['BranchInfo']}' , `photo` = '$timestamp_photo{$_FILES['photo']['name']}' , `download1` = '$timestamp_download1{$_FILES['download1']['name']}' , `download1name` = '{$_POST['download1name']}' , `download2` = '$timestamp_download2{$_FILES['download2']['name']}' , `download2name` = '{$_POST['download2name']}' , `download3` = '$timestamp_download3{$_FILES['download3']['name']}' , `download3name` = '{$_POST['download3name']}' WHERE `Ter` = '$ter' "; mysql_query($sql) or die(mysql_error()); //Unpause Photo/Document Upload //Writes the photo to the server if(move_uploaded_file($_FILES['photo']['tmp_name'], $photo_target)) { echo "<br />The file ".$timestamp_photo. basename( $_FILES['photo']['name']). " has been uploaded. <br />"; } else { echo ""; } //End of Photo/Document Upload //Writes the photo to the server if(move_uploaded_file($_FILES['download1']['tmp_name'], $download_target1)) { echo "<br />The file ".$timestamp_download1. basename( $_FILES['download1']['name']). " has been uploaded. <br />"; } else { echo ""; } //End of Photo/Document Upload //Writes the photo to the server if(move_uploaded_file($_FILES['download2']['tmp_name'], $download_target2)) { echo "<br />The file ".$timestamp_download2. basename( $_FILES['download2']['name']). " has been uploaded. <br />"; } else { echo ""; } //End of Photo/Document Upload //Writes the photo to the server if(move_uploaded_file($_FILES['download3']['tmp_name'], $download_target3)) { echo "<br />The file ".$timestamp_download3. basename( $_FILES['download3']['name']). " has been uploaded. <br />"; } else { echo ""; } //End of Photo/Document Upload echo (mysql_affected_rows()) ? "<br />Edited Branch.<br />" : "<br />Nothing changed. <br />"; } $row = mysql_fetch_array ( mysql_query("SELECT * FROM `ter` WHERE `Ter` = '$ter' ")); ?> |