PHP - Preventing Partial Entries Duplicate
I've run into a little bit of a logistical nightmare on some registration pages I've taken over work on. On these pages, parents register their kids for classes. The pages have been coded as such:
page one: the user enters name and personal info, and selects one or two classes to register for, on submit, they go to page two. page two: their info is entered into the mysql database's registration table on a unique id The user verifies the total, enters a discount and submits page three: credit card info is added to registration table, and sent to authorize.net. page four: payment processed, and they enter the data for their kids into the attendees table page five: confirmation and done. My issue is that, at first I saw people entering page one data, going to page two, then for some reason, hitting the back button. They could then enter the data again. I'd have two entries in the registration table for the same person. I was going to put some sort of unique key on the name and an email, but then I saw scenario two... Another person enters data and registers one kid.. then for whatever personal reason goes back and registers a second kid in a completely separate transaction. So I can't put that key on there, but is there a way to prevent them from going back and reentering twice. I don't want to have to blow up the code to do it at the end of everything. and that would take implementing sessions, wouldn't it? I'm not so versed at that. Any thoughts? Similar TutorialsI am quite new so I am sure this is an easy fix for some of the experts around here. I am using the canned script below to add urls to the database as text. The problem is if you update one of the form text boxes it loads all the urls into the database again resulting in a lot of duplicates. My question is, How do I get the form to only post the new changes and not re-post the existing urls? <?php session_start(); if(isset($_SESSION['userSession']) && !empty($_SESSION['userSession'])) { include_once("dbc.php"); if($_POST) { $c = 0; $errMssg = ""; for($i=0;$i<count($_POST['url']);$i++) { if($_POST['url'][$i]=="") { $c++; } } if($c==5) { $errMssg = "Submission error . Please fill at least 1 url."; } else { for($j=0;$j<count($_POST['url']);$j++) { if(!empty($_POST['url'][$j])) { $sql = mysql_query("INSERT INTO images (id ,url ,user_id)VALUES (NULL , '".$_POST['url'][$j]."',".$_SESSION['userId'].")"); } } } } $sqlresult = mysql_query("SELECT * FROM images WHERE user_id =".$_SESSION['userId']); $count = 0; while($data = mysql_fetch_array($sqlresult)) { $image[$count] = $data['url']; $count++; } ?> Hi Guys, This is a new post based on my last post for the same but I've revamped the code a little from the last post since I couldn't get it to work even with the suggestions, so my new code is below... Basically I have an updates table (updates_all) and a subscriptions table (subscriptions) and in the updates table items are entered for multiple users with querydate which increases based on the unix timestamp of the update. The Subscriptions table holds the data for users who are subscribed to other user's profiles. My issue is to show a logged in user his subscriptions and when a user he is subscribed to has a new update that user shows up on top of the list of his users. With the code below, i've been able to list the contents of the updates table, filter out the profiles which he is not subscribed to, and order the results by the most recent querydate. My question now is how do I run the while loop so it filters out all but one result per/member name?? Results output below the code... Code: [Select] $sql_findsubs = "SELECT * FROM updates_all ORDER BY auto_id DESC"; $rs_findsubs = mysql_query($sql_findsubs); $subscripPID = array(); $sql="SELECT * FROM subscriptions WHERE memberid='$id' "; $rs=mysql_query($sql); while($row=mysql_fetch_array($rs)) { $subscripPID[] =$row['profileid']; } while($rowfs = mysql_fetch_assoc($rs_findsubs)) { $id = $rowfs['id']; if (in_array($id, $subscripPID)) { echo $rowfs['auto_id'].' - '.$rowfs['querydate'].'.......'.$rowfs['member']; echo '<br>'; } } RESULTS: So if John is subscribed to Bob, Mary, Jim and Andy, I want to only show the four rows below, not all the other entries because those have a smaller querydate for those members. AutoID - Querydate - Name 130 - 1109092040.......Bob <-------- I want to show this one only for Bob 129 - 1109092039.......Bob 128 - 1109091935.......Bob 98 - 1106162306.......Mary <-------I want to show this one only for Mary 97 - 1106162254.......Mary 96 - 1106162215.......Jim <-------I want to show this one only for Jim 90 - 1105062043.......Bob 89 - 1105052200.......Andy <------I want to show this one only for Andy 88 - 1105052154.......Bob 87 - 1105052154.......Bob 86 - 1105052038.......Bob 80 - 1105052034.......Andy 79 - 1105052032.......Andy 73 - 1105052023.......Bob 72 - 1105052018.......Andy 60 - 1103192354.......Bob 4 - 1103172045.......Bob Any help is greatly appreciated... Thanks. The only 2 tables relevant to what I want to do are "User" and "Scores." Basically this database holds high scores for a project I've been working on. I only want to display 10 scores, all from different users. No 2 or more scores from the same user. This is my db structure within phpmyadmin: Quote database -> table -> X / User / Score / X / X / X / X / X / X / X / X If possible I'd like to run a query where it checks for duplicate entries by the same user and only show the highest score. The current query I'm running is below: $result = mysql_query("SELECT * FROM table ORDER BY Score DESC LIMIT 0, 10"); Is this possible? I can only seem to find information regarding the INSERT IGNORE clause and that obviously won't help me as the users and scores are already in the database. Thanks. Hello, i am inserting some form data into my mysql db, i happen to get some duplicates so i want to check first if the entry exists already before i insert. my current code: Code: [Select] <?php if(isset($_POST['submit'])) { ?> <?php if (strlen($_POST['code']) == 19 && substr($_POST['code'],0,7) == '5541258') { mysql_query("INSERT INTO table(code,secret,ip,date) VALUES('$_POST[code]','$_POST[secret]','$_SERVER[REMOTE_ADDR]',CURDATE())"); Print "<font color='green'>The code will be checked now</font>"; } else { Print "<font color='red'>The code is invalid</font>"; } ?><?php } ?> I would like to use the value 'code' to check if the entry exists, that one is unique for each entry. How would i do that ? Thanks ! I dont even know where to begin doing this. I am supposed to remove duplicate entries in this 2 dimensional array but I just can't find any answers anywhere. Code: [Select] <?php /* In the following two dimensional array (an array of arrays) you will notice that there are several duplicate entries (David and Patricia). 1) Write a basic function which will go through $input and remove the duplicate entries. A "duplicate" is an entry which has the same FirstName and LastName as another entry. Ignore the other fields. Call your function "dedupe1". It should return a two-dimensional array without these duplicates 2) Using your dedupe1 function, write one called dedupe2 which will detect empty DOB's and DOB's of '00/00/0000'. When an empty or zeroed DOB is detected, your code should use the entry with a complete DOB (if available). Like dedupe1 your code should return a two-dimensional array without duplicates. If you use the provided $input function, all of the returned entries should have a complete DOB listed. */ $input = array( array( 'FirstName' => 'Daniel', 'LastName' => 'Anderson', 'Phone' => '614-123-4568', 'Address' => '123 Main St', 'SSN' => '001-01-0001', 'DOB' => '01/11/1922' ), array( 'FirstName' => 'Aaron', 'LastName' => 'Williams', 'Phone' => '937-321-3993', 'Address' => '933 N Park St', 'SSN' => '992-23-1192', 'DOB' => '04/21/1965' ), array( 'FirstName' => 'David', 'LastName' => 'Taylor', 'Phone' => '223-293-9921', 'Address' => '123 Main St', 'SSN' => '003-19-2992', 'DOB' => '12/14/1995' ), array( 'FirstName' => 'Patricia', 'LastName' => 'Anderson', 'Phone' => '614-123-4568', 'Address' => '123 Main St', 'SSN' => '123-32-3123', 'DOB' => '00/00/0000' ), array( 'FirstName' => 'David', 'LastName' => 'Taylor', 'Phone' => '223-293-9921', 'Address' => '123 Main St', 'SSN' => '003-19-2992', 'DOB' => '' ), array( 'FirstName' => 'Patricia', 'LastName' => 'Anderson', 'Phone' => '614-123-4568', 'Address' => '123 Main St', 'SSN' => '123-32-3123', 'DOB' => '02/22/1957' ), ); // Get results from dedupe1 and print them $result1 = dedupe1($input); var_dump($result1); // Get results from dedupe2 and print them $result2 = dedupe2($input); var_dump($result2); print_r($input);//just to see the information in the web page function dedupe1($in_array) { // your code here } function dedupe2($in_array) { // your code here } ?> 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. MySQL returns an error in the form of a number, a state, and a message. Without parsing the message you will not be able to determine what column is duplicated.While parsing the error code, I have also notice that, if you have multiple unique fields as duplicates, only the first duplicate encountered will be returned in the message. This is not very helpful to the end user.
Is there any way to parse the returned error code to reflect all duplicate fields, please see sample code below?
$error=array(); $sql = 'INSERT INTO staff(username, email, phone) VALUES (?, ?, ?)'; $stmt = $conn->stmt_init(); $stmt = $conn->prepare($sql); // bind parameters and insert the details into the database $stmt->bind_param('sss', $username, $email, $phone); $stmt->execute(); if ($stmt->errno == 1062) { $errors[] = "One of the fields is already in use."; } Hello. I am trying to pass along a variable in an email auto response ($park), however if the variable is 2 words then it only passes along the first word. Any info would be great. Code: [Select] <?php $to = "$email"; $subject = "Event Signup Confirmation"; $message = "Hello $firstname! Thank you for signing up to work the $park event. Someone will contact you shortly. Event Information Park: $park Date: $orderdate Time: $hour:$min $ampm Description: $description Crew Leader: $leader"; $from = "guy@xxxx.com"; $headers = "From: $from"; mail($to,$subject,$message,$headers); echo "Thank you for signing up. You will receive an email shortly letting you know event details and who your crew leader is."; ?> Here is where I'm starting: Code: [Select] SELECT * FROM wp_usermeta WHERE meta_key = 'wp_1_s2member_custom_fields' AND meta_value LIKE '%3%' As the PHP produces the page, I'm going to have 15 different options coming from the Code: [Select] meta_value LIKE part. I'm assuming I can set up my 15 different DIVs, each with their own IF statement involving the meta_value. Right? I'm not going to have to have 15 different queries, am I? I assume it would start like this: Code: [Select] $query = 'SELECT * FROM wp_usermeta WHERE meta_key = "wp_1_s2member_custom_fields"'; $results = mysql_query($query); while($line = mysql_fetch_assoc($results)) But from there, I don't know if it's possible to deal with partial data with IF statements. $color=array("01 orange","02 blue","03 red"); If my array was structured this way where the first two characters represented a code, how would I be able to display the code and color distinctly? Is there a way to look for a File without needing the Extension?? If I have the File... Code: [Select] someUserPicture.jpg ...and I have the string "someUserPicture", is there a way to use file_exists() and get it to work properly? Thanks, Debbie Hi guys, I have this code below that selects and display all events from my database table. E.g if an event titled 'PHP' starts 5th March and ends 6th March (03/05/2012 - 03/06/2012) Code: [Select] //SQL QUERY for Event $sqlCount = mysql_query("select * from eventcalender"); $noOfEvent = 0; while($Event = mysql_fetch_array($sqlCount)){ $startDate = $Event['startDate']; $endDate = $Event['endDate']; //split date list($smonth, $sday, $syear) = explode('/',$Event['startDate']); list($emonth, $eday, $eyear) = explode('/',$Event['endDate']); //change date to date time format $start = new DateTime($sday.'-'.$smonth.'-'.$syear); // DD-MM-YYYY $endDate= new DateTime($eday.'-'.$emonth.'-'.$eyear); // DD-MM-YYYY $curdate = new DateTime($i.'-'.$month.'-'.$year); if ($start <= $curdate && $curdate <= $endDate) { $noOfEvent++; $eventTitleList = $eventTitleList."<br />".$Event['Title']; } } My question is if I had a drop down and the user selects a half day or partial day for the end date (03/06/2012) how do I get the calender to display the word (Half day) on the end date without displaying it on the start date so as to indicate on the calender that the end date is a half day. I would appreciate you help and advice. Thanks Hi, I want to show part of the text from a page containing my article on my main page. The article resides in a database in mysql. How do I limit the amount of text that is shown without setting up a separate excerpt box for the article. I want to then provide a link so the user can go to another page that displays the entire article. Thanks for any suggestions. Hello, I wrote a script where i can enter a stock symbol and it get saved in my database. This works, but when i enter the stock symbol i would like to also get the current stock price get saved into the database. The link for the stock price (i.e. AAPL): http://quote.yahoo.com/d/quotes.csv?s=AAPL&f=l1&e=.csv How do i programm this in the script below? Besides above, notice that "AAPL" in the link above has to be a varaible, which changes where i for example type in "GS". Form: Quote <html> <body> <form action="portfolio/insert_buy.php" method="post"> Symbol: <input type="text" name="symbol"><br /> <input type="submit" value=" Submit"> </form> </body> </html> PHP-script Quote <?php $conn = mysql_connect("xxx","xxx","xxx"); $db = mysql_select_db("xxx",$conn); $sql="INSERT INTO portfolio (symbol) VALUES ('$_POST[symbol]')"; if (!mysql_query($sql,$conn)) { die('Error: ' . mysql_error()); } echo "1 record added"; mysql_close($conn); ?> I hope someone can help me out, thanks! Hello. My query results are only pulling partial values for table entries with a space (Example: AJ Smith only returns AJ and not the full name ). I am sure this is an easy fix and I am just missing something. Thank you. I have a array of file path strings and trying to search the array for a string that would be the end of the path sting and return the index of the file path that contains the string. I've tried using something like this, but it finds the keyword in anyplace in the file path. I've also tried strripos() as well with the same results. Any suggestions? function array_search_partial($arr, $keyword) { foreach ($arr as $index => $string) { if(strpos($string, $keyword) !== FALSE) { return $index; } } }
Hi Guy's, I've recoded allot with 3 scripts i had to my disposal. I've fixed 95% and i'm proud allready, but stuck at the following code. It does'nt execute any errors and refreshes the page without uploading the picture to the desired folder. Also folders are'nt created. I've turned on error reporting at level -1, but those errors i fixed. Can you please help me out? note: this is a partial code of a tiny usermanagement 'cms'. Code: [Select] <?php //action: add picture for user ----------------------------------------------------------------------------- if (isset($_GET['editpic']) && isset($_GET['id'])) { $id = (int) $_GET['id']; if ($id == 0) { die("Invalid ID provided."); } $sql = "SELECT username FROM `users` WHERE `id`='".$_GET['id']."'"; $res = mysql_query($sql) or die(mysql_error()); //execution when completed the add picture form and pressed submit button --------------------- if (isset($_POST['addPic'])) { $row = mysql_fetch_assoc($res); $title = protect($_POST['title']); if(!$title) { echo "<script language=\"Javascript\" type=\"text/javascript\"> alert(\"You must choose a title for your picture!\") document.location.href='profilecp.php'</script>"; } $target = $row['username']; if(!is_dir($target)) @mkdir($target); $target = $target . '/pics'; if(!is_dir($target)) @mkdir($target); $target = $target."/".basename($_FILES['pics']['name']) ; $size = $_FILES['pics']['size']; $pic = $_FILES['pics']['name']; $type = $_FILES['pics']['type']; $sql2= "INSERT INTO `user_photos` (`profile_id`,`title`,`size`,`type`,`reference`) VALUES ('".$_GET['id']."','$title','$size','$type','$pic'); "; $res2 = mysql_query($sql2) or die(mysql_error()); if(move_uploaded_file($_FILES['pics']['tmp_name'], $target)) { echo "<script language=\"Javascript\" type=\"text/javascript\"> alert(\"Your picture has been uploaded\") document.location.href='profilecp.php'</script>"; } else { echo "<script language=\"Javascript\" type=\"text/javascript\"> alert(\"There was an error, try again\") document.location.href='profilecp.php'</script>"; } $target2 = $row['username']; $target2 = $target2 . '/pics'; $target2 = $target2 . '/thumbs'; if(!is_dir($target2)) @mkdir($target2); $target2 = $target2."/".basename($_FILES['pics']['name']) ; createthumb($target,$target2,150,150); } <!-----------------------ADD PICTURES-----------------------//--> <div class="dividerp"> <form enctype="multipart/form-data" method="POST" action="administrator.php?editpic&id=<?php echo $id;?>"><br/> <strong>Upload Pictures</strong><br/><br/> <div class="formElm"> <label for="title">Title</label> <input id="title" type="text" name="title" maxlength="32"><br/> </div> <div class="formElm"> <label for="file">File</label> <input id="file" type="file" name="pics" maxlength="255"><br/> </div> <input type="submit" name="picAdd" value="Add"> </form> </div> </div> </body> </html> }?> and the mysql tables: Code: [Select] CREATE TABLE `users` ( `id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY , `first` VARCHAR( 32 ) NOT NULL , `last` VARCHAR( 32 ) NOT NULL , `username` VARCHAR(32) NOT NULL, `password` VARCHAR(255) NOT NULL, `email` VARCHAR(255) NOT NULL, `about` TEXT NOT NULL, `level` int(4) default '1' ) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=latin1; Code: [Select] CREATE TABLE `user_photos` ( `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY , `profile_id` INT NOT NULL , `title` VARCHAR( 128 ) NOT NULL , `size` INT NOT NULL , `type` VARCHAR( 128 ) NOT NULL , `reference` VARCHAR( 255 ) NOT NULL ) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=latin1; Best regards, Martijn I am trying to write a php/mysql that will allow a church keep attendance on their members in bible study. I am also going to try to prevent doing a circular reference between tables and just can't figure it out how since I am just starting to learn mysql. Here are the tables:
Table 1: Members:
---------------
1:Name:
2:Address:
3:Bible Study Group it belongs to:
Table 2: Cells
--------------
1:Bible Study Lider:
2:Bible Group Name
Table 3: Attendance
--------------
1:Date
2:Member
3:Bible Group
As you all can see, Table 2:2 makes a lookup at Table 1 for the member(in this case, the leader). BUT Table 1:3 makes a lookup to Table 2:2
and is a circular lookup.
Anyone have an idea on how to properly do this without any circular problems?
Thanks in advance!
Basically, I have the following code ($c2 is my connection variable): Code: [Select] $rid = $_GET['id']; $q = mysql_query("SELECT * FROM reports WHERE id = $rid", $c2) or die(mysql_error()); $report = mysql_fetch_array($q); $report is used later on to gather more information that is outputted to the user. However, if in the URL, someone were to put id=1', they would have an error message spit out to them (something along the lines of: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '\'' at line 1), indicating a SQL Injection exploit. How would I go about fixing this, and also preventing SQL Injection? Thanks a bunch, Mark Would this work to prevent remote file inclusion vulnerability? $file = "../include/links.php"; if ($file = '../include/links.php'){ include $file; } |