PHP - Multiple Duplicate Database Records On Submitting A Form
First of all excuse me if this topic is inappropriate in this forum. But I think it's rather a PHP problem.
I can't figure out multiple duplicate database records on submitting a form. The database table have two columns: the first one 'Id' with AUTO_INCREMENT and the second one 'Name'. Here's the php code for database insertion and the form: ------------------------------------------------------------------ <?php if($_GET['add_name']){ $host = *******; $user = *******'; $pass = *******; $db = *******; $con = mysql_connect($host,$user,$pass) or die; mysql_select_db($db,$con); $name = $_GET['add_name']; $sql = "INSERT INTO names (Name) VALUES ('$name')"; mysql_query($sql); } ?> <form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="GET"> Your Name: <input name="add_name" type="text" /> <input type="submit" value="Submit" /> </form> ------------------------------------------------------------------ After submitting the form to itself once I have multiple Name entries with different Ids. The curious thing is that with Chrome browser I get two duplicate records, with Mozilla - three of them. Seems like mysql_query runs multiple times. It works fine when submitting the form to a separate script and not to itself. Do I miss something? It must be very basic. Similar Tutorialshello every body...
two
I'm creating an IPN in paypal for my membership site but the problem I'm facing is that on successfull verification of the purchase, four rows are getting inserted in the database...
The code is
<?php require '../db.php'; $paypalmode = '.sandbox'; $req = 'cmd=' . urlencode('_notify-validate'); foreach ($_POST as $key => $value) { $value = urlencode(stripslashes($value)); $req .= "&$key=$value"; } $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'https://www'.$paypalmode.'.paypal.com/cgi-bin/webscr'); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); curl_setopt($ch, CURLOPT_POSTFIELDS, $req); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Host: www'.$paypalmode.'.paypal.com')); $res = curl_exec($ch); curl_close($ch); if (strcmp ($res, "VERIFIED") == 0) { $transaction_id = $_POST['txn_id']; $payerid = $_POST['payer_id']; $firstname = $_POST['first_name']; $lastname = $_POST['last_name']; $payeremail = $_POST['payer_email']; $paymentdate = $_POST['payment_date']; $paymentstatus = $_POST['payment_status']; $mdate= date('Y-m-d h:i:s',strtotime($paymentdate)); $otherstuff = json_encode($_POST); $date = date("y-m-d"); $q = $pdo->connect()->query("INSERT INTO payment (mid,username,amount,paypal_id,txn_id,received_date) VALUES('{$_SESSION['user_id']}','{$_SESSION['uname']}','{$_POST['mc_gross']}','{$_POST['payer_email']}','{$_POST['txn_id']}','$date')"); $q->execute(); $q1 = $pdo->connect()->query("UPDATE members SET amount_loaded = amount_loaded + {$_SESSION['amount']} WHERE mid = '{$_SESSION['user_id']}'"); $q1->execute(); //header("Location: funds.php"); echo "verified"; } ?>two for the payment and in the members table, the amount is getting doubled. (i.e if anybody purchases For $2, it shows $4 in the database....) Any help will be really appreciated... I need Delete Duplicate Email Records That Are Attached To One Account But Can Be Found In Multiple Accounts I have a table, consumer_mgmt. It collects consumer information from various forms. These forms are available through different pages that are part of a business package. A business can offer these signups to gather names and emails from consumers for various types of specials they may offer. So a consumer my be in the consumer_mgmt table 5, 10, 15 times for that particular business. But, that consumer may be in the consumer_mgmt table multiple times for a different business. So multiple times for multiple businesses. I need to remove duplicates for each business account so the consumer is only the consumer_mgmt only once for each business. There are approximately 15,000 rows currently in the consumer_mgmt table. I'm not sure where to begin on the logic. Since there are multiple business accounts that the emails are attached to, would one have to build a case for each loop? This is the form that I'm using and it populates just fine but when you make the changes I can't figure out how to get it to update each record in my database. Code: [Select] <table width="100%" cellspacing="1" cellpadding="2" border="0"> <form action="<?php echo $_SERVER["PHP_SELF"] . "?update=1"; ?>" method="post"> <tr> <td><b>Category Name</b></td> <td><b>Category Description</b></td> <td><b>Order</b></td> <td align="right"><input type="submit" value="Update"></td> </tr> <?php read_cat_list($cat); for ($i = 0; $i < $cat["count"]; $i++) { echo "<tr>\n"; echo "<td width=\"30%\" valign=\"top\"><input type=\"text\" name=\"cat_name_" . safe_string($cat[$i]["cat_id"]) . "\" size=\"30\" maxlength=\"250\" value=\"" . safe_string($cat[$i]["cat_name"]) . "\"></td>\n"; echo "<td width=\"36%\" valign=\"top\"><textarea name=\"cat_desc_" . safe_string($cat[$i]["cat_id"]) . "\" rows=\"2\" cols=\"30\">" . safe_string($cat[$i]["cat_desc"]) . "</textarea></td>\n"; echo "<td width=\"10%\" valign=\"top\"><input type=\"text\" name=\"cat_order_" . safe_string($cat[$i]["cat_id"]) . "\" size=\"3\" maxlength=\"3\" value=\"" . safe_string($cat[$i]["cat_order"]) . "\"></td>\n"; echo "<td width=\"24%\" valign=\"top\">[ <a href=\"#\" onmouseover=\"window.status = 'Delete " . safe_string($cat[$i]["cat_name"]) . "'; return true;\" onmouseout=\"window.status = ''; return true;\" onclick=\"javascript:del_cat(" . $cat[$i]["cat_id"] . ", '" . safe_string($cat[$i]["cat_name"]) . "'); return false;\">Delete</a> ]</td>\n"; echo "</tr>\n"; } ?> <tr> <td colspan="4" align="right"><input type="submit" value="Update"></td> </tr> </form> </table> the safe_string function just cleans up the output/input from the database, This next block is my form processor for this form. Code: [Select] <?php function update_cats($vars) { $err = ""; #if ($SESSION["level"] != ADMIN) { # $err = ERR_NOT_ENOUGH_ACCESS; #} else { $temp = array_keys($vars); for ($i = 0; $i < count($temp); $i++) { if (substr($temp[$i], 0, 9) == "cat_name_") { if ($vars[$temp[$i]] == "") { $err = "Category names cannot be blank."; break; } else { $name_query["cat_name"] .= substr($temp[$i], 9) . ", "; } } } for ($i = 0; $i < count($temp); $i++) { if (substr($temp[$i], 0, 9) == "cat_desc_") { $desc_query["cat_desc"] .= substr($temp[$i], 9) . ", "; } } for ($i = 0; $i < count($temp); $i++) { if (substr($temp[$i], 0, 10) == "cat_order_") { if ($vars[$temp[$i]] == "") { $err = "Category orders cannot be blank."; break; } else { $order_query["cat_order"] .= substr($temp[$i], 10) . ", "; } } } #} if (!$err) { if ($name_query["cat_name"]) { $update_name_query = "update category"; $update_name_query .= " set cat_name = '" . $name_query["cat_name"] . "'"; $update_name_query .= " where cat_id in (" . substr($name_query["cat_name"], 0, -2) . ")"; update_db($update_name_query); } if ($desc_query["cat_desc"]) { $update_desc_query = "update category"; $update_desc_query .= " set cat_desc = '" . $name_query["cat_desc"] . "'"; $update_desc_query .= " where cat_id in (" . substr($desc_query["cat_desc"], 0, -2) . ")"; update_db($update_desc_query); } if ($order_query["cat_order"]) { $update_order_query = "update category"; $update_order_query .= " set cat_order = '" . $name_query["cat_order"] . "'"; $update_order_query .= " where cat_id in (" . substr($order_query["cat_order"], 0, -2) . ")"; update_db($update_order_query); } } return $err; } ?> update_db is my database caller, if you need any of the functions that I use that are not here please post back and tell me. now when I process the form all my fields change to this: cat_name: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, cat_desc: cat_id: 0 for all the records in the database table, I'm just trying to update each record with the values it needs Here is my database table with the data. Code: [Select] CREATE TABLE `category` ( `cat_id` int(11) NOT NULL AUTO_INCREMENT, `cat_name` varchar(255) NOT NULL, `cat_desc` text NOT NULL, `cat_order` int(11) NOT NULL, PRIMARY KEY (`cat_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=16 ; -- -- Dumping data for table `category` -- INSERT INTO `category` (`cat_id`, `cat_name`, `cat_desc`, `cat_order`) VALUES(1, 'Hand Tossed Pizza', '', 1); INSERT INTO `category` (`cat_id`, `cat_name`, `cat_desc`, `cat_order`) VALUES(2, 'Hand Tossed Specialty Pizzas', '', 2); INSERT INTO `category` (`cat_id`, `cat_name`, `cat_desc`, `cat_order`) VALUES(3, 'Chicago Style Deep Dish', '', 3); INSERT INTO `category` (`cat_id`, `cat_name`, `cat_desc`, `cat_order`) VALUES(4, 'Specialty Chicago Style Deep Dish', '', 4); INSERT INTO `category` (`cat_id`, `cat_name`, `cat_desc`, `cat_order`) VALUES(5, 'Chicken Wings & Tenderloins', '', 5); INSERT INTO `category` (`cat_id`, `cat_name`, `cat_desc`, `cat_order`) VALUES(6, 'Hot Sides', '', 6); INSERT INTO `category` (`cat_id`, `cat_name`, `cat_desc`, `cat_order`) VALUES(7, 'Hot Sandwiches', '', 7); INSERT INTO `category` (`cat_id`, `cat_name`, `cat_desc`, `cat_order`) VALUES(8, 'Cold Sandwiches', '', 8); INSERT INTO `category` (`cat_id`, `cat_name`, `cat_desc`, `cat_order`) VALUES(9, 'Pastas', '', 9); INSERT INTO `category` (`cat_id`, `cat_name`, `cat_desc`, `cat_order`) VALUES(10, 'Fresh Salads', '', 10); INSERT INTO `category` (`cat_id`, `cat_name`, `cat_desc`, `cat_order`) VALUES(11, 'Fresh Breads', '', 11); INSERT INTO `category` (`cat_id`, `cat_name`, `cat_desc`, `cat_order`) VALUES(12, 'Soups', '', 12); INSERT INTO `category` (`cat_id`, `cat_name`, `cat_desc`, `cat_order`) VALUES(13, 'Kids Menu', '', 13); INSERT INTO `category` (`cat_id`, `cat_name`, `cat_desc`, `cat_order`) VALUES(14, 'Drinks', '', 14); INSERT INTO `category` (`cat_id`, `cat_name`, `cat_desc`, `cat_order`) VALUES(15, 'Desserts', '', 15); Hope I have provided plenty of info on what I got and what I need for it todo Thanks Hello, i am having an issue when i try to go through multiple pages from a database. The database contains apartment information. I currently have it set to limit my results to 30 per page and this is working correctly, however when i try to scroll to page two like 1..2..3 i am displayed with every apartment listed in the database, and not the certain category that i would like selected. //assigning variables $SESuser_lng = $_COOKIE['SESuser_lng']; $SESuser_admlevel = $_COOKIE['SESuser_admlevel']; $id = $_GET['id']; $pgrow = $_GET['pgrow']; $msg = $_GET['msg']; $ht_filter = $_GET['ht_filter']; //sql query to retrieve result set $htfilter selects the distinct apartment categories $sqlFilter = ($ht_filter > 0 ? " WHERE p.idhotel = $ht_filter" : ""); $sql = "SELECT p.id, p.idhotel, p.nombre, p.thmb, p.archivo, h.nombre FROM prensa p LEFT JOIN hoteles h ON p.idhotel = h.id $sqlFilter ORDER BY p.nombre, h.nombre"; //DB_pager $nav = new DB_Pager('30'); $result = $nav->execute($sql, $dbcnx); //Javascript link creation <span id="display-links"><?php echo $nav->display_links(); ?></span> any help will be greatly appreciated I have PHP forms that are not submitting to my database. I think it is something minor but I just can't see it! Can anyone help? At the beginning of index.php, the page holding the forms, I have this: Code: [Select] [b]<?php include("functions/globals.php"); ?> <?php include("functions/userfunctions.php"); ?>[/b] [b]Here are these pages:[/b] [b]globals.php[/b] <?php ob_start();//Required for the redirect to work?> <?php include("loginstatus.php");?> <?php session_start(); ?> [b]((Here's loginstatus.php for good measu [/b] <?php class cUser { public $username = "";//The User Name public $userid = "";//The User ID public $type = "";//The Type Of User } ?> [b]))[/b] [b]And here is userfunctions.php[/b] <?php include_once("databasefunctions.php"); (this holds the connection) $userdbtable = "users"; function GetHeaders() { $headers = 'MIME-Version: 1.0' . "\r\n"; $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; // Additional headers $headers .= "To: {$username} <{$email}>" . "\r\n"; $headers .= 'From: My Website <[email]noreply@myswebsite.com[/email]>' . "\r\n"; return $headers; } function CreateAccount($firstname, $lastname, $username, $password, $email, $type) { global $userdbtable; openDatabase(); $firstname = mysql_real_escape_string($firstname); $lastname = mysql_real_escape_string($lastname); $username = mysql_real_escape_string($username); $password = mysql_real_escape_string($password); $email = mysql_real_escape_string($email); $type = mysql_real_escape_string($type); $nonencrypted = $password; $password = sha1($password); $result = QuickQuery("INSERT INTO {$userdbtable}(firstname, lastname, username, password, email, type) VALUES('{$firstname}','{$lastname}','{$username}','{$password}','{$email}',{$type}')"); if($result) { $headers = GetHeaders(); $message = "\"Welcome to my website!\"<br /> <br /> Your username is: {$username}<br /> Your password is: {$nonencrypted}<br /> <br /> Signed,<br /> <br /> Me "; mail($email, "Account Creation", $message, $headers); mail("[email]myemailaddress@me.com[/email]", "Account Created", "{$username} has created a new account", $headers); } } function ValidateUser($username, $password) { global $userdbtable; openDatabase(); $username = mysql_real_escape_string($username); $password = mysql_real_escape_string($password); $result = QuickQuery("SELECT * FROM {$userdbtable} WHERE username = '{$username}'"); closeDatabase(); if(!mysql_result($result,0,"username"))//Make sure the user exists return "User Does Not Exist"; $temppwd=mysql_result($result,0,"password");//Make sure the passwords match if(sha1($password) != $temppwd) return "Password Does Not Match"; return 1; } function GetUserID($username) { global $userdbtable; openDatabase(); $username = mysql_real_escape_string($username); $result = QuickQuery("SELECT id FROM {$userdbtable} WHERE username = '{$username}'"); closeDatabase(); if($result) return(mysql_result($result,0,"id"));//Get the user id else return 0; return(mysql_result($result,0,"id"));//Get the UserID } function GetUserType($username) { global $userdbtable; openDatabase(); $username = mysql_real_escape_string($username); $result = QuickQuery("SELECT type FROM {$userdbtable} where username = '{$username}'"); closeDatabase(); return(mysql_result($result,0,"type"));//Get the user type } function GetUserEmail($username) { global $userdbtable; openDatabase(); $username = mysql_real_escape_string($username); $result = QuickQuery("SELECT email FROM {$userdbtable} WHERE username = '{$username}'"); closeDatabase(); return(mysql_result($result,0,"email"));//Get the user email } function ConfirmPassword($id, $password) { global $userdbtable; openDatabase(); $password = mysql_real_escape_string($password); $password = sha1($password); $result = QuickQuery("SELECT * FROM {$userdbtable} WHERE id = '{$id}' AND password = '{$password}'"); closeDatabase(); if(!$result) return 0; else return 1; } function ChangePassword($id, $password) { global $userdbtable; openDatabase(); $password = mysql_real_escape_string($password); $password = sha1($password); return QuickQuery("UPDATE {$userdbtable} SET password='{$password}' WHERE id={$id}"); } function ResetPassword($email) { global $userdbtable; openDatabase(); $email = mysql_real_escape_string($email); $result = QuickQuery("SELECT * FROM {$userdbtable} WHERE email = '{$email}'"); $num = mysql_numrows($result); if(!$num) return 0; $user = mysql_result($result, 0, "username"); $email = mysql_result($result, 0, "email"); $randompwd = RandomPwd(); $temp = sha1($randompwd); $headers = GetHeaders(); mail($email, "Blah blah blah. Your newusername is: {$user}, and your new password is: {$randompwd}. ", $headers); if(QuickQuery("UPDATE {$userdbtable} SET password='{$temp}' WHERE email='{$email}'")) return 1; } function RandomPwd() { $length = 10; $characters = '0123456789abcdefghijklmnopqrstuvwxyz'; $string = ""; for ($p = 0; $p < $length; $p++) { $string .= $characters[mt_rand(0, strlen($characters))]; } return $string; } ?> [b]Here is the info on index.php for login and registration[/b] [b]Login:[/b] <?php if($_GET['logout'] == 'logout') { session_destroy(); Redirect("index.php"); } if($_POST['submitted'] == "login") { // echo ValidateUser("Jimmy", "password"); //CreateAccount($name, $password, $email, $type); if(ValidateUser($_POST['username'], $_POST['password']) == 1) { $_SESSION['user'] = new cUser; $_SESSION['user']->username = $_POST['username']; $_SESSION['user']->usertype = GetUserType($_POST['username']); $_SESSION['user']->userid = GetUserID($_POST['username']); Redirect("index.php"); } // CreateAccount("test", "test", "[email]me@website.com[/email]", "user"); } ?> [b]Registration[/b] <?php if($_POST['submitted'] == "register") { $firstname = $_POST['firstname']; $lastname = $_POST['lastname']; $username = $_POST['username']; $email = $_POST['email']; $password = $_POST['password']; $confirmpwd = $_POST['confirmpwd']; if(!$firstname) $error = "Invalid First Name"; else if(!$lastname) $error = "Invalid Last Name"; else if(!$username) $error = "Invalid User Name"; else if(!$email) $error = "Invalid Email"; else if(!$password) $error = "Invalid Password"; } ?> <?php if($_POST['submitted'] && !$error) { $result = QuickQuery("SELECT username FROM users WHERE username='{$username}'"); if(mysql_numrows($result) > 0) $error = "Be More Creative. Someone Already is Using That Username."; else { $result = QuickQuery("SELECT email FROM users WHERE email='{$email}'"); if(mysql_numrows($result) > 0) $error = "Email Already Being Used. Maybe you already registered."; else if($confirmpwd != $password) $error = "Matching passwords means the second password must be exactly like this first."; else { CreateAccount($firstname, $lastname, $username, $password, $email, "user"); } } } ?> [b]Both forms are here[/b] <div class="btn-show"> <p>Login</p> </div> <div class="pushup-form"> <div class="btn-close"> Close </div> <div class="clear"> </div> <form action="index.php" method="post"> <p style="font-size:14px">Login</p> <p>Username:<input type="text" name="username" style="font-size:12px;"/></p> <p>Password:<input type="password" name="password" style="font-size:12px;"/></p> <p><input class="login" type="submit" name="submitted" value="login" /></p> <p><a href="pwd.php?pwd=lostpwd" style="font-size:10px">Forgot Username or Password?</a></p> </form> <div class="panel"> <form action="index.php" method="post"> <p>First Name:<input type="text" name="firstname" value="<?php echo $firstname;?>" /></p> <p>Last Name:<input type="text" name="lastname" value="<?php echo $lastname;?>" /></p> <p>Username:<input type="text" name="username" value="<?php echo $username;?>" /></p> <p>Email:<input type="text" name="email" class="clear" value="<?php echo $email;?>" /></p> <p>Password:<input type="password" name="password" value="<?php echo $password;?>" /></p> <p>Confirm Password:<input type="password" name="confirmpwd" value="<?php echo $confirmpwd;?>" /></p> <p class="clear"> <p><input class="register" type="submit" name="submitted" value="register"/></p> </p> </form> </div> <p style="text-align:center;" class="flip">Need to Register?</p> </div> [code] These forms open from the right side of my website by clicking "Register." The top of the form has an option for login and by clicking "Need to Register?" The rest of the form expands. Any ideas? My database is set up correctly. MOD EDIT: code tags added. Hi there, Im fairly new at php and mysql but nevertheless im trying to build a web based campaign game for starwars minatures boardgame. Its fairly straightforward and going well.. However ive been thinking about how it will work and have stumbled across a possible problem (because of my limited craft at programming). I want to have a single form that updates all records in the tables, this would simulate an "end of turn" button. Im sure i can do this if doing stuff in the game (e.g. move, create , modify, delete, fleets/ships and auto increment ships hulls simulating repair) if it was done on the same page. However i wanted to to initiate some of these adjustments in their respective pages (fleet.php, planets.php, ships.php etc) and then once the user is happy to click the end turn button somewhere which would update all of these things at the same time.. Is this possible at all??? If anybody could help that would be brilliant. Thank you p.s. if anybody wants a copy of the finished product when its complete, your most welcome. This select box below does remember and highlight -one- selection after submitting the form. But when i make it multiple, it doesn't highlight any of the selections after submitting. Any idea about how to achieve this? Thanks in advance. Code: [Select] <?php $options_amount = array("0","1","2","3","4","5","6","7","8","9","10+"); $no_way = $_GET['no_way']; ?> <select class="postform" name="no_way[]" multiple size="5"> <option <?php if ($no_way == 'all') { ?>selected="selected"<?php }?> value="all">Any</option> <?php foreach ($options_amount as $option) { ?><option <?php if ($no_way == $option) { ?>selected="selected"<?php }?> value="<?php echo $option; ?>"><?php echo $option; ?></option><?php }?> </select> Hi. When a record is added its done via a form and processed via inserts.php. I need to use the same form but to recall the data (by id) so it can be editted. Cant work it out though. Help would be well appreciated! edit.php: <CENTER><B>Update a Vehicle</B></CENTER> <BR> <?php $query="SELECT * FROM cars"; $result=mysql_query($query); $i=0; while ($i < $num) { $carname=mysql_result($result,$i,"CarName"); $cartitle=mysql_result($result,$i,"CarTitle"); $carprice=mysql_result($result,$i,"CarPrice"); $carmiles=mysql_result($result,$i,"CarMiles"); $cardesc=mysql_result($result,$i,"CarDescription"); ?> <form action="showroomedit.php" method="post"> <CENTER>Vehicle Name:</CENTER> <CENTER><input type="text" name="CarName" value="<?php echo $carname; ?>"></CENTER> <br> <CENTER>Vehicle Type:</CENTER> <CENTER><input type="text" name="CarTitle" value="<?php echo $cartitle; ?>"></CENTER> <br> <CENTER>Vehicle Price:</CENTER> <CENTER><input type="text" name="CarPrice" value="<?php echo $carprice; ?>"></CENTER> <br> <CENTER>Vehicle Mileage:</CENTER> <CENTER><input type="text" name="CarMiles" value="<?php echo $carmiles; ?>"></CENTER> <br> <CENTER>Vehicle Description:</CENTER> <CENTER><textarea name="CarDescription" rows="10" cols="30" value="<?php echo $cardesc; ?>"></textarea></CENTER> <br> <CENTER><input type="Submit"></CENTER> </form> </TD> cant work out why it isnt working... guys, I have looked on google for this and apparently noone is doing it. I have 4 checkboxes and I want to send mail indicating which boxes were checked. the only code I've found is PHP that captures the *status* of the boxes, such as "on" or "off". I want to capture the names of the actual checkbox elements. Here is the code I'm currently testing (which just prints out "on" or "off" to indicate which boxes are checked): if(isset($_POST['checkboxes'])) { foreach($_POST['checkboxes'] as $selected){ echo $selected . "</br>"; } } else { echo "No Desired Contact Time Specified."; } if I check all 4 boxes for instance, I get this: on on on on any way to get the names? thanks! I have a controller(generatebill.php) where I have collected all the value from the form(normaluserview.php). I can see my value is stored. But whenever I wanted to display those values in table format in another view(invoice.php in this case), it keeps repeating. For better understanding, I have uploaded the files as well.. Please help
Attached Files
generatebill.php 592bytes
2 downloads
invoice.php 31bytes
3 downloads
normaluserview.php 3.4KB
1 downloads
I have a hopefully small issue on a form submitting data to the mysql database table and email. The email side works fine as does the adding the data to the database table but if I upload two files, it stores the support ticket twice in the database table where as I want to store just once and the files be stored as a array in the database table. I got the code from the link https://www.codexworld.com/upload-multiple-images-store-in-database-php-mysql/
<?php require_once "registerconfig.php"; if (isset($_POST['submit'])) { // File upload configuration $targetDir = "support-ticket-images/"; $allowTypes = array('pdf','doc','docx','jpg','png','jpeg','gif'); $statusMsg = $errorMsg = $insertValuesSQL = $errorUpload = $errorUploadType = ''; // Escape user inputs for security $ticket_subject = htmlentities($_POST['ticket_subject'], ENT_QUOTES); $ticket_message = strip_tags($_POST['ticket_message'], ENT_QUOTES); $ticket_status ='PENDING SUPPORT'; $username = htmlentities($_SESSION["user_name"], ENT_QUOTES); $user_id = htmlentities($_SESSION["user_id"], ENT_QUOTES); $fileNames = array_filter($_FILES['files']['name']); if(!empty($fileNames)){ foreach($_FILES['files']['name'] as $key=>$val){ // File upload path $fileName = basename($_FILES['files']['name'][$key]); $targetFilePath = $targetDir . $fileName; // Check whether file type is valid $fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION); if(in_array($fileType, $allowTypes)){ // Upload file to server if(move_uploaded_file($_FILES["files"]["tmp_name"][$key], $targetFilePath)){ // Image db insert sql $insertValuesSQL .= "('".$ticket_subject."','".$ticket_message."','".$fileName."','".$ticket_status."','".$username."', '".$user_id."'),"; }else{ $errorUpload .= $_FILES['files']['name'][$key].' | '; } }else{ $errorUploadType .= $_FILES['files']['name'][$key].' | '; } } if(!empty($insertValuesSQL)){ $insertValuesSQL = trim($insertValuesSQL, ','); // Insert image file name into database $insert = $link->query("INSERT INTO DB TABLE NAME (ticket_subject, ticket_message, file_name, ticket_status, user_name, user_id) VALUES $insertValuesSQL"); if($insert){ $to = "emailaddress"; $subject = "A new support ticket has been submitted"; $message = " <strong>$username</strong> has just created a support ticket, below is the support ticket <br /><br /> <u>Support Ticket Details</u> <br /><br> <strong>Support Ticket Subject</strong>: $ticket_subject <br/><br><strong>Support Ticket Message</strong>: $ticket_message <p><strong><u>Support Ticket Files</u></strong> <br> <img src='$fileName'> "; // Always set content-type when sending HTML email $headers = "MIME-Version: 1.0" . "\r\n"; $headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n"; // More headers $headers .= 'From: <noreply@emailaddress>' . "\r\n"; $mail=mail($to,$subject,$message,$headers); $errorUpload = !empty($errorUpload)?'Upload Error: '.trim($errorUpload, ' | '):''; $errorUploadType = !empty($errorUploadType)?'File Type Error: '.trim($errorUploadType, ' | '):''; $errorMsg = !empty($errorUpload)?'<br/>'.$errorUpload.'<br/>'.$errorUploadType:'<br/>'.$errorUploadType; header("location: support-ticket-confirmation?user=$username"); }else{ $statusMsg = "Sorry, there was an error uploading your file."; } } }else{ $statusMsg = 'Please select files to upload.'; } // Display status message echo $statusMsg; } ?> The structure of the db table column is file_name, VARCHAR(255), latin1_swedish_ci, NOT NULL hello .. I have 3 tables: student - infractions - Actions and view1 it Includes all tables and i make view1 source my page. my database structu Table: student Columns: ID_student int(11) AI PK name varchar(45) Age varchar(45) Grade varchar(45) Table: infractions Columns: ID_infractions int(11) AI PK infractions_text varchar(45) ID_student int(11) Table: actions Columns: ID_Actions int(11) AI PK Actions_text varchar(45) ID_student int(11) view1 SELECT student.ID_student AS ID_student, student.name AS name, student.Age AS Age, student.Grade AS Grade, infractions.ID_infractions AS ID_infractions, infractions.infractions_text AS infractions_text, actions.ID_Actions AS ID_Actions, actions.Actions_text AS Actions_text FROM (student JOIN infractions ON student.ID_student = infractions.ID_student) JOIN actions ON student.ID_student = actions.ID_student php page code: PHP Code: This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=309981.0 [ Newbie Alert ] Hi i have an array of 39 arrays. Only 5 are shown below so that you have an idea before i ask my question. <? array(39) { [0]=> array(3) { [0]=> string(18) "unit name 1" [1]=> string(9) "category name 1" [2]=> string(20) "Course 1" } [1]=> array(3) { [0]=> string(54) "unit name 2" [1]=> string(15) "category name 2" [2]=> string(20) "Course 1" } [2]=> array(3) { [0]=> string(29) "unit name 3" [1]=> string(15) "category name 2" [2]=> string(20) "Course 1" } [3]=> array(3) { [0]=> string(64) "unit name 4" [1]=> string(30) "category name 3" [2]=> string(20) "Course 2" } [4]=> array(3) { [0]=> string(57) "unit name 5" [1]=> string(24) "category name 1" [2]=> string(20) "Course 1" } [5]=> array(3) { [0]=> string(50) "unit name 6" [1]=> string(24) "category name 4" [2]=> string(20) "Course 2" } } i want a php solution to print category names in table headers , unit names in table rows and course name(s) in table caption.I have tried foreach loop but how to remove duplicate entries as you can see category name 1 and 2 will become two separate headers instead of one and same is the case with Course 1 and 2. i have googled but could'nt find any solution. i don't want to remove duplicate entries , all i want to display them once in a table as described above. Dear all, I have a problem that I need to be helped with using one form and storing the images in database. I would like to upload multiple images with same title from "title" field. Can somebody help me with this? <?php $db_host = 'localhost'; // don't forget to change $db_user = 'mysql-user'; $db_pwd = 'mysql-password'; $database = 'test'; $table = 'ae_gallery'; // use the same name as SQL table $password = '123'; // simple upload restriction, // to disallow uploading to everyone if (!mysql_connect($db_host, $db_user, $db_pwd)) die("Can't connect to database"); if (!mysql_select_db($database)) die("Can't select database"); // This function makes usage of // $_GET, $_POST, etc... variables // completly safe in SQL queries function sql_safe($s) { if (get_magic_quotes_gpc()) $s = stripslashes($s); return mysql_real_escape_string($s); } // If user pressed submit in one of the forms if ($_SERVER['REQUEST_METHOD'] == 'POST') { // cleaning title field $title = trim(sql_safe($_POST['title'])); if ($title == '') // if title is not set $title = '(empty title)';// use (empty title) string if ($_POST['password'] != $password) // cheking passwors $msg = 'Error: wrong upload password'; else { if (isset($_FILES['photo'])) { @list(, , $imtype, ) = getimagesize($_FILES['photo']['tmp_name']); // Get image type. // We use @ to omit errors if ($imtype == 3) // cheking image type $ext="png"; // to use it later in HTTP headers elseif ($imtype == 2) $ext="jpeg"; elseif ($imtype == 1) $ext="gif"; else $msg = 'Error: unknown file format'; if (!isset($msg)) // If there was no error { $data = file_get_contents($_FILES['photo']['tmp_name']); $data = mysql_real_escape_string($data); // Preparing data to be used in MySQL query mysql_query("INSERT INTO {$table} SET ext='$ext', title='$title', data='$data'"); $msg = 'Success: image uploaded'; } } elseif (isset($_GET['title'])) // isset(..title) needed $msg = 'Error: file not loaded';// to make sure we've using // upload form, not form // for deletion if (isset($_POST['del'])) // If used selected some photo to delete { // in 'uploaded images form'; $id = intval($_POST['del']); mysql_query("DELETE FROM {$table} WHERE id=$id"); $msg = 'Photo deleted'; } } } elseif (isset($_GET['show'])) { $id = intval($_GET['show']); $result = mysql_query("SELECT ext, UNIX_TIMESTAMP(image_time), data FROM {$table} WHERE id=$id LIMIT 1"); if (mysql_num_rows($result) == 0) die('no image'); list($ext, $image_time, $data) = mysql_fetch_row($result); $send_304 = false; if (php_sapi_name() == 'apache') { // if our web server is apache // we get check HTTP // If-Modified-Since header // and do not send image // if there is a cached version $ar = apache_request_headers(); if (isset($ar['If-Modified-Since']) && // If-Modified-Since should exists ($ar['If-Modified-Since'] != '') && // not empty (strtotime($ar['If-Modified-Since']) >= $image_time)) // and grater than $send_304 = true; // image_time } if ($send_304) { // Sending 304 response to browser // "Browser, your cached version of image is OK // we're not sending anything new to you" header('Last-Modified: '.gmdate('D, d M Y H:i:s', $ts).' GMT', true, 304); exit(); // bye-bye } // outputing Last-Modified header header('Last-Modified: '.gmdate('D, d M Y H:i:s', $image_time).' GMT', true, 200); // Set expiration time +1 year // We do not have any photo re-uploading // so, browser may cache this photo for quite a long time header('Expires: '.gmdate('D, d M Y H:i:s', $image_time + 86400*365).' GMT', true, 200); // outputing HTTP headers header('Content-Length: '.strlen($data)); header("Content-type: image/{$ext}"); // outputing image echo $data; exit(); } ?> <html><head> <title>MySQL Blob Image Gallery Example</title> </head> <body> <?php if (isset($msg)) // this is special section for // outputing message { ?> <p style="font-weight: bold;"><?=$msg?> <br> <a href="<?=$PHP_SELF?>">reload page</a> <!-- I've added reloading link, because refreshing POST queries is not good idea --> </p> <?php } ?> <h1>Blob image gallery</h1> <h2>Uploaded images:</h2> <form action="<?=$PHP_SELF?>" method="post"> <!-- This form is used for image deletion --> <?php $result = mysql_query("SELECT id, image_time, title FROM {$table} ORDER BY id DESC"); if (mysql_num_rows($result) == 0) // table is empty echo '<ul><li>No images loaded</li></ul>'; else { echo '<ul>'; while(list($id, $image_time, $title) = mysql_fetch_row($result)) { // outputing list echo "<li><input type='radio' name='del' value='{$id}'>"; echo "<a href='{$PHP_SELF}?show={$id}'>{$title}</a> – "; echo "<small>{$image_time}</small></li>"; } echo '</ul>'; echo '<label for="password">Password:</label><br>'; echo '<input type="password" name="password" id="password"><br><br>'; echo '<input type="submit" value="Delete selected">'; } ?> </form> <h2>Upload new image:</h2> <form action="<?=$PHP_SELF?>" method="POST" enctype="multipart/form-data"> <label for="title">Title:</label><br> <input type="text" name="title" id="title" size="64"><br><br> <label for="photo">Photo:</label><br> <input type="file" name="photo" id="photo"><br><br> <label for="password">Password:</label><br> <input type="password" name="password" id="password"><br><br> <input type="submit" value="upload"> </form> </body> </html> For some reason it just stopped working. It was fine earlier. I don't even think I messed with it. :/ mysql_query("INSERT INTO apps VALUES ('', '$username', '$age', '$why', '$ip', '$random', '$id', '0')"); The data wont go in the database for some reason. Hi everyone, I need a little bit of help finishing off my code. Ive managed to get this far. Code: [Select] <?php mysql_connect("") or die ("Not Connected to MYSQL"); echo "</br>"; mysql_select_db("") or die ("Not Connected to DB"); // Database Connection stuff $partialNumber = $_POST['partialNumber']; // Post the Partial number $partialNumber = strtoupper($partialNumber); $numberSearch = mysql_query("SELECT * FROM product_option_value_description WHERE name LIKE '%$partialNumber%'") or die (mysql_error()); // Query to select the key number //Query to get product ID // $productId = "SELECT product_id FROM product_option_value_description"; //Query to get product ID // while ($keyNumber = mysql_fetch_array($numberSearch)) { $id = $keyNumber['product_id']; // Query for the images // $query = "SELECT image FROM product WHERE product_id = '$id'"; $result = mysql_query($query); $row = mysql_fetch_array($result) or die(mysql_error()); $query2 = "SELECT product_option_id FROM product_option_value WHERE product_id = '$id'"; $result2 = mysql_query($query2); $row2 = mysql_fetch_array($result2) or die(mysql_error()); $query3 = "SELECT product_option_value_id FROM product_option_value WHERE product_id = '$id'"; $result3 = mysql_query($query3); $row3 = mysql_fetch_array($result3) or die(mysql_error()); ?> <div> <br /><br /> Key Number: <? echo $keyNumber['name']; ?></a> <form action="http://www.co.uk/teststore/index.php?route=checkout/cart" method="post" enctype="multipart/form-data" id="product"> <br /> <table style="width: 100%;"> <tr> <td> Colour: <select name="option[<? echo $row2['product_option_id']; ?>]"> <option value="<? echo $row3['product_option_value_id']; ?>"></option> </select></td> </tr> </table> <div class="content"> Qty: <input type="text" name="quantity" size="3" value="1" /> <input type="hidden" name="product_id" value="<? echo $id; ?>" /> <input name="submit" type="submit" value="Add to Cart" /> </div> </form> <? echo $row3['product_option_value_id']; ?> </div> <br /> <img height="150" width="150" src='http://www.co.uk/teststore/image/<? echo $row['0']; ?>'/> <? } ?> And here is my SQL Table code. Code: [Select] product_option_value_id product_option_id product_id 599 302 49 598 302 49 589 297 42 588 297 42 So as you can probably tell, it is a search program that looks for products on a shopping cart. The products will have different option values, and the php script will grab the option values and echo them in a form to post back to the cart to add the product to the basket. The problem is that the "product_option_value_id" can have lots of different values, but my code echos only the first one it finds. So when I click the add to cart button, it will only add the first option value for the product it finds. For some reason I am having a hard time explaining this, so I hope someone can help me. Thanks for looking. I 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++; } ?> I have created an input field on a website for people to subscribe by their email address. The email address is stored in a database. I am using PHPMyAdmin. The email address is successfully working, but I want to prevent duplicate email address to be stored, however, I am having an error. Here are my codes: HTML codes: Code: [Select] <form action="index.php" method="post"> <input type="text" size="25" placeholder="Your email address..." name="enter"/> <input class="submit" type="submit" value="Subscribe" name="subscribe"/> <br/> PHP with Query codes: Code: [Select] <?php if ( $_SERVER['REQUEST_METHOD'] == "POST" ) { $ee = htmlentities($_POST['enter']); if (!preg_match('/^[^0-9][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[@][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[.][a-zA-Z]{2,4}$/',$ee) || empty($ee)){ echo '<p class="fail">Failed...Try again!</p>'; } else { @mysql_connect ('localhost', 'root', '') or die ('A problem has occurred, refresh the page and try again!'); @mysql_select_db ('links') or die ('A problem has occurred, refresh the page and try again!'); $duplicate = "SELECT * FROM `email` WHERE `emailaadress` = '{$ee}'"; $query = "INSERT INTO email (id, emailaddress) VALUES('NULL', '.$ee')"; $result = mysql_query($duplicate); if ( mysql_num_rows ( $result ) > 1) { /* Username already exists */ echo 'Username already exists'; } else { mysql_query($query); echo '<p class="success">Successfully subscribed!</p>'; } } } ?> Error I am having: Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\softwareportfolio\index.php on line 68 Can someone help me? Thank |