PHP - Duplicate Records Are Getting Inserted In The Database
hello 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... Similar TutorialsFirst 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. This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=309981.0 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: [ 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. 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? Hello all! I'm having a problem inserting an array into my database. My database is connected when I run the script but my table isn't being populated. Please help! Here's my table structure followed by the php: CREATE TABLE `demographic` ( `uid` bigint(20) unsigned NOT NULL, `first_name` varchar(50) default NULL, `last_name` varchar(50) default NULL, `email` varchar(200) default NULL, `link` varchar(255) default NULL, `affiliations` varchar(255) default NULL, `birthday` varchar(50) default NULL, `current_location` varchar(200) default NULL, `education_history` varchar(500) default NULL, `work` mediumtext, `hometown_location` varchar(400) default NULL, `interests` varchar(200) default NULL, `locale` varchar(50) default NULL, `movies` varchar(500) default NULL, `music` varchar(500) default NULL, `political` varchar(200) default NULL, `relationship_status` varchar(100) default NULL, `sex` varchar(10) default NULL, `tv` varchar(200) default NULL, `status` tinyint(4) default NULL, `created` datetime default NULL, `updated` datetime default NULL, PRIMARY KEY (`uid`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; <?php $link = mysql_connect('host', 'user', 'pass'); if (!$link) { die('Could not connect: ' . mysql_error()); } $db_selected = mysql_select_db('database'); if (!$db_selected) { die ('Can\'t use beta : ' . mysql_error()); } echo 'Connected successfully'; mysql_close($link); include_once "fbmain.php"; $config['baseurl'] = "baseurl"; //if user is logged in and session is valid. if ($fbme){ //collect some data using legacy api $param = array( 'method' => 'users.getinfo', 'uids' => $fbme['id'], 'fields' => 'birthday_date, interests, locale, political, relationship_status, affiliations', 'callback' => '' ); try{ $info = $facebook->api($param); } catch(Exception $o){ error_log("Legacy Api Calling Error!"); } //using graph api //array data $workInfo = getWorkInfoAsString($fbme); $education = getEducationAsString($fbme); $moviesArr = $facebook->api("/me/movies"); $musicArr = $facebook->api("/me/music"); $televisionArr = $facebook->api("/me/television"); //format some api data $movies = getArrayDataAsString($moviesArr['data']); $music = getArrayDataAsString($musicArr['data']); $television = getArrayDataAsString($televisionArr['data']); //data from legacy api $networks = ''; if (!empty($info[0]['affiliations'])){ $flag = true; foreach ($info[0]['affiliations'] as $item){ if (!$flag) $networks.= ' # '; $networks .= $item['name']; $flag = false; } } $now = date("Y-m-d G:i:s"); $insData = array( 'uid' => $fbme['id'], 'first_name' => $fbme['first_name'], 'last_name' => $fbme['last_name'], 'email' => isset($fbme['email']) ? $fbme['email'] : '', 'link' => $fbme['link'], 'affiliations' => $networks, 'birthday' => $info[0]['birthday_date'], 'current_location' => isset($fbme['location']['name']) ? $fbme['location']['name'] : '', 'education_history' => $education, 'work' => $workInfo, 'hometown_location' => isset($fbme['hometown']['name']) ? $fbme['hometown']['name'] : '', 'interests' => $info[0]['interests'], 'locale' => $info[0]['locale'], 'movies' => $movies, 'music' => $music, 'political' => $info[0]['political'], 'relationship_status' => $info[0]['relationship_status'], 'sex' => isset($fbme['gender']) ? $fbme['gender'] : '', 'tv' => $television, 'status' => '0', 'created' => $now, 'updated' => $now, ); $this->db->insert('demographic', $insData); } function getWorkInfoAsString($fbme, $delim = '#', $partDelim = ' | '){ $info = ""; $flag = false; if (empty($fbme['work'])) return ''; foreach($fbme['work'] as $item){ if ($flag) $info .= $partDelim; $flag = true; $info .= (isset($item['employer']['name']) ? $item['employer']['name'] : '' ). $delim . (isset($item['location']['name']) ? $item['location']['name'] : '' ). $delim . (isset($item['position']) ? $item['position']['name'] : '' ). $delim . (isset($item['start_date']) ? $item['start_date'] : '' ). $delim . (isset($item['end_date']) ? $item['end_date'] : '' ); } return $info; } function getEducationAsString($fbme, $delim = '#', $partDelim = ' | '){ $info = ""; $flag = false; if (empty($fbme['education'])) return ''; foreach($fbme['education'] as $item){ if ($flag) $info .= $partDelim; $flag = true; $info .= (isset($item['school']['name']) ? $item['school']['name'] : '' ). $delim . (isset($item['year']['name']) ? $item['year']['name'] : ''); } return $info; } function getArrayDataAsString($data, $delim = '#', $partDelim = ' | '){ $info = ""; $flag = false; foreach($data as $item){ if ($flag) $info .= $partDelim; $flag = true; $info .= $item['name']; } return $info; } ?> After I've successfully inputted something in my script and then click refresh in Chrome with "Right Click -> Reload", the same thing that I've inputted before gets re-inserted AGAIN into the database, thus resulting in multiple versions of the same thing in the MySQL database. How can I prevent that? p.s. Chrome is warning with a pop up of repeated action, and when I then click continue the repeated insertion of the data occurs, and I'd like to prevent the repeated insertion. Hello everyone.
It seems like my code is not working properly.
i have tried both mysqli and PDO to insert data into database,but it only takes me back to same page again,without doing nothing in the database (been checking this a few times to be sure).
both php and html code are on the same page.
Could anyone point me to the missing link in my code?
here's my code (HTML & PHP) :
<form action="" id="SignUpForm" autocomplete="on" style="display:none" method="post"> <!-- Form is Hidden until the user is clicking the "Sign Up" button. --> <input type="hidden" name="Language" value="English"> Fill up the following fields:<br><br> First name:<input type="text" name="fname" required><br><br> Last name: <input type="text" name="lname" required><br><br> Age: <input type="number" name="UserAge" min="1" max="120" required><br><br> Gender: <input type="radio" name="Gender" value="male">Male<br> <input type="radio" name="Gender" value="Female">Female<br> E-mail Address: <input type="email" name="email" autocomplete="off" required><br><br> Pick your new password: <input type="password" maxlength=”40” name="Password" required pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,40}"> Add password strength checker here.<br><br> <!-- Uses regular expression. --> Confirm Password: <input type="password" maxlength=”40” name="ConfirmPassword" required pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,40}"><br><br> <!-- A better way is to use onblur to check user's type match. --> <hr> <script> (function(){ $("#submit").click(function(){ $(".error").hide(); //Bind an event handler to the "error" JavaScript event. var hasError = false; var passwordVal = $("#Password").val(); var checkVal = $("#ConfirmPassword").val(); if (passwordVal == '') { $("#Password").after('<span class="error">Please enter a password.</span>'); hasError = true; } else if (checkVal == '') { $("#ConfirmPassword").after('<span class="error">Please re-enter your password.</span>'); hasError = true; } else if (passwordVal != checkVal ) { $("#ConfirmPassword").after('<span class="error">Passwords do not match.</span>'); hasError = true; } if(hasError == true) {return false;} }); }); </script> <script> //The validationMessage property of a DOM node contains the message the browser displays to the user when a node's validity is checked and fails. document.getElementById("name").validationMessage; document.getElementById("lname").validationMessage; document.getElementById("UserAge").validationMessage; document.getElementById("Gender").validationMessage; document.getElementById("email").validationMessage; document.getElementById("Password").validationMessage; document.getElementById("ConfirmPassword").validationMessage; </script> Now let's go through your prefered food. Check the appropriate boxed beyond.<br><br> This will help us to better understand your food discipline:<br> <p style="text-align:center"><b> Meat And Poultry:</b></p> <div id="MeatCheckBox"> <input type="checkbox" name="FoodTypes[]" value="Hamburger">Hamburger<br> <input type="checkbox" name="FoodTypes[]" value="Steak">Steak<br> <input type="checkbox" name="FoodTypes[]" value="GroundBeef">Ground Beef<br> <input type="checkbox" name="FoodTypes[]" value="Bacon">Bacon<br> <input type="checkbox" name="FoodTypes[]" value="Beef">Beef<br> <input type="checkbox" name="FoodTypes[]" value="Salami">Salami<br> <input type="checkbox" name="FoodTypes[]" value="Chicken">Chicken (In all its forms)<br> <input type="checkbox" name="FoodTypes[]" value="NoMeat">I don't eat meat at all (Vegeterian/Vegan)<br> </div> <p style="text-align:center"><b> Fish And Seafood:</b></p> <div id="FishAndSeaFood"> <input type="checkbox" name="FoodTypes[]" value="Fish">Fish<br> <input type="checkbox" name="FoodTypes[]" value="Sushi">Sushi<br> <input type="checkbox" name="FoodTypes[]" value="CannedFish">Canned Fish<br> <input type="checkbox" name="FoodTypes[]" value="Oysters">Seafood<br> <input type="checkbox" name="FoodTypes[]" value="SmokedSalmon">Smoked Salmon<br> </div> <div id="Vegetables"> <p style="text-align:center"><b> Do you eat vegtables?</b></p><br> <input type="radio" name="YesOrNo" value="Yes">Yes <!-- Give both options the same name,Because they are related. --> <input type="radio" name="YesOrNo" value="No">No<br> </div> <hr> <p>Do you workout as part of your lifestyle?</p><br> <input type="radio" name='workout_options' value='valuable' data-id="DoWorkout" class="workout_options" /> I do workout occasionally <input type="radio" name='workout_options' value='valuable' data-id="DoNotWorkout" class="workout_options" /> I am not working out<br><br><br> <section> <div id=DoWorkout class="workout_options"><p>We see you're not having any exercise at the moment.<br><br>Did you know that doing some kind of activity like running or cardio 3 times a week improve your life quality?<br><br>We'll help you go straight from zero to hero!</p></div> <div id=DoNotWorkout class="workout_options">What type of workout you're working on at the moment? Please choose from the options beyond:<br><br><br> <input type="checkbox" name="Cardio" value="Cardio" data-id="Cardio"/>Cardio/Aerobics<br><br> <input type="checkbox" name=" Weight_Lifting" value=" Weight_Lifting" data-id="Weight_Lifting"/>Weight Lifting/ Anaerobics</div><br> </section> <input type="submit" value="Sign Up!" id="submit"> </div> </form>PHP/PDO: <?php // connnecting to MYSQL with PDO. // Connection data (server_address, database, username, password) $hostdb = 'localhost'; $namedb = 'caf_users'; $userdb = 'root'; $passdb = 'mypassword'; if (isset($_POST['SignUpButton'])) { $yesOrNo=$_POST["YesOrNo"]; $firstName=$_POST["fname"]; $lastName=$_POST["lname"]; $userGender=$_POST["Gender"]; $emailAddress=$_POST["email"]; //check if user entered the exact password twice. if ($_POST["password"] === $_POST["confirm_password"]) { $password=$_POST["password"]; $hash = password_hash($passwod, PASSWORD_DEFAULT);} // The first parameter is the password string that needs to be hashed, //and the second parameter specifies the algorithm that should be used for generating the hash. //encrypted by bcrypt algorithm. else { echo "Passwords are mismatched. Please try again."; }; $userAge=$_POST["UserAge"]; // Display message if successfully connect, otherwise retains and outputs the potential error try { $conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb); //Initiate connection witht the PDO object instance. $conn->exec("SET CHARACTER SET utf8"); // Sets encoding UTF-8 echo 'Connected to database'; // Define an insert query $sql = "INSERT INTO `users` ('Workout','first_name','last_name','gender','Email_Address','Password','User_Age') VALUES ($YesOrno,$fname,$lname,$Gender,$email,$password,$UserAge)"; $count = $conn->exec($sql); $conn = null; // Disconnect if($count !== false) echo 'Number of rows added: '. $count; } catch(PDOException $e) { echo $e->getMessage(); } } ?>Thank you in advance, Osher. Ugh. Ive been asking so many questions, betcha already know my name. Hahah. Anyways, I know I already asked a question like this, but this is different. One of the values I am trying to insert into a database is simply not working. Here is the columnes in my mysql database: c_id commet story user date_added star Every value but 'commet' is getting inserted into database. NO error, no mysql errror. I have racked my brain trying to figure out what is wrong with the script. Here is my code: Code: [Select] <?php $idget = $_GET['id']; mysqlConnect(); //submit story if(isset($_POST['submit'])) { $com_form = mysql_real_escape_string(bb($_POST['commet'])); $rat_form = $_POST['rat']; $story_form = $idget; $user = $_SESSION['user']; $date = date("Y-m-d"); $query1 = " INSERT INTO story_commets(star, story, user, date_added, commet) VALUES($rat_form, '$story_form', '$user', '$date', '$com_form') "; mysql_query($query1) or die(mysql_error()); //} } // desplay reviews $query3 = " SELECT * FROM story_commets WHERE story = '$idget' ORDER BY date_added "; $select3 = mysql_query($query3) or die(mysql_error()); //$x=1; $ratav = array(); //if(mysql_num_rows($select3) == 0) //{ echo '<div id="message"> No Reviews Yet.... <>'; //} //else //{ while($rows3 = mysql_fetch_assoc($select3)) { $commetdb = $rows3['commet']; $user_com_db = $rows3['user']; $datedb = $rows3['date_added']; $stardb = $rows3['star']; //get profile picture $query4 = " SELECT * FROM login_info WHERE user = '$user_com_db' "; $select4 = mysql_query($query4) or die(mysql_error()); $rows4 = mysql_fetch_assoc($select4) or die(mysql_error()); $profile_pic = $rows4['profile_picture']; $user_id = $rows4['id']; echo " <div class='rev_cont'> <div class='info'> <img src='$profile_pic' /> <a href=?p=profile&id=$user_id> $user_com_db </a> <> <br /> <div class='rev'> <strong> $stardb/10 </strong> <br /> $commetdb <> <div id='date'> <em> Date Added: $datedb </em> <> <> <hr /> "; $ratav[]=$stardb; } $sum = array_sum($ratav); $count = count($ratav); $av = $sum / $count; $avf = round($av, 1); echo"<div id='message'> Rating Avarage: $avf /10 <>"; //} if (isset($_SESSION['user'])) { echo" <p> Did you like this story? Did you hate it? Give it a rating and let the author know!</p> <form action='?p=review&id=$idget' method='post' target='_self'> <label> Your rating is on a scale of 1-10 </label> <select name='rat'> <option> 1 </option> <option> 2 </option> <option> 3 </option> <option> 4 </option> <option> 5 </option> <option> 6 </option> <option> 7 </option> <option> 8 </option> <option> 9 </option> <option> 10 </option> </select> <label> Commets: </label> <textarea name='commet' cols='70' rows='9'></textarea> <input name='story' type='hidden' value='$idget' /> <br /> <input type='submit' value = 'Post' name='submit' /> </form> "; } else { echo "<div id='message'> Sign in to post a review! <>"; } ?> Here are the specifics if you want it. Here is the response part of the code: Code: [Select] <?php if(isset($_POST['submit'])) { $com_form = mysql_real_escape_string(bb($_POST['commet'])); $rat_form = $_POST['rat']; $story_form = $idget; $user = $_SESSION['user']; $date = date("Y-m-d"); $query1 = " INSERT INTO story_commets(star, story, user, date_added, commet) VALUES($rat_form, '$story_form', '$user', '$date', '$com_form') "; mysql_query($query1) or die(mysql_error()); //} } ?> Here is the form part of my code: Code: [Select] <?php if (isset($_SESSION['user'])) { echo" <p> Did you like this story? Did you hate it? Give it a rating and let the author know!</p> <form action='?p=review&id=$idget' method='post' target='_self'> <label> Your rating is on a scale of 1-10 </label> <select name='rat'> <option> 1 </option> <option> 2 </option> <option> 3 </option> <option> 4 </option> <option> 5 </option> <option> 6 </option> <option> 7 </option> <option> 8 </option> <option> 9 </option> <option> 10 </option> </select> <label> Commets: </label> <textarea name='commet' cols='70' rows='9'></textarea> <input name='story' type='hidden' value='$idget' /> <br /> <input type='submit' value = 'Post' name='submit' /> </form> "; } else { echo "<div id='message'> Sign in to post a review! <>"; } ?> Its probably something really mundane. HelP! Am a newbie in php. Since I can't insert values to the database with respect to a user Id or with any other token using WHERE clause. I.e "INSERT INTO receipts(date) VALUES(example) where id="**....." If I need to fetch several values of column for a particular user, how do I go about it? Thank you!!! 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 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++; } ?> Hi all Complete noob here..... What I have to do is create a new database every year, but I can't just import last years data completely, only records when needed. I can do it myself in PHPMyAdmin, but I don't want my employees touching mysql directly. What I am trying to do is write a php script that will serach for a reocrd in last years database and if it exists insert it into the new database if it doesn't exists bring up a form so it can be entered. Any help would be greatly appreciated. Thanx ZZ hey guys, I'm getting a problem uploading my csv file to mysql database, the code on the top half just makes sure that I don't import data that I don't want into the database, numbers that are too high or too low on certain rows, and the second half is importing the array that I create from the csv file into the database however I'm getting the following error
Duplicate entry 'Array' for key 'strProductCode'
Now I've never had this error before and I'm not sure what's causing it so any help would be very much appreciated
$data = array(); if (($handle = fopen("stock.csv", "r")) !== FALSE) { while (($row = fgetcsv($handle, 1000, ",")) !== FALSE) { // only add rows to the array where the 4th column value is greater than or equal to 10 if(($row[3] >= 10 && $row[4] >= 5) OR ($row[3] >= 0 AND $row[4] > 5)){ if($row[4] < 1000){ $data[] = $row; } } } foreach ($data as &$value) { mysql_query("INSERT INTO tblProductData (intProductDataId, strProductCode, strProductName, strProductDesc, strProductStock, strProductCost, dtmDiscontinued, dtmAdded, stmTimestamp) VALUES(null, '$data[0]', '$data[1]', '$data[2]', '$data[3]', '$data[4]', 'time', 'added', 'time') ") or die(mysql_error()); } } I have written code in php to connect and insert rows into a MSSQL database. i used odbc to connect database.user can enter his details through the form. after submitting the form the details are getting stored into a database. while inserting rows into a database am not trying to insert duplicate values . for this i have given if conditions.these conditions are able to notice the user cname and name exist in the database if the same name exist. but the else part after these conditions are not working i.e rows are not getting inserted. i put everything inside the while loop. how can i correct it? This is my php code. $connect = odbc_connect('ServerDB','sa', 'pwd'); //connects database $query2="select count(*) from company";//this is needer for loop through $result2=odbc_exec($connect,$query2); while(odbc_fetch_row($result2)); { $count=odbc_result($result2,1); echo "</br>","$count"; } $query1="select * from company"; $result1 = odbc_exec($connect, $query1); # fetch the data from the database while(odbc_fetch_row($result1)) { $compar[$count] = odbc_result($result1, 1); $namearray[$count] = odbc_result($result1, 2); if($compar[$count]==$_POST['cname']) { echo "<script> alert(\"cname Exists\") </script>"; } else if($namearray[$count]==$_POST['name']) { echo "<script> alert(\"Name Exists\") </script>"; } else { $query=("INSERT INTO company(cname,name) VALUES ('$_POST[cname]','$_POST[name]') "); $result = odbc_exec($connect, $query); echo "<script> alert(\"Row Inserted\") </script>"; } } I am having a big problem in MySQL and a part in my PHP coding as well. I created a registration form, where the user will have to fill his names, email address, choose a username and so on. I do not want duplicate email address and username in my database, thus, if a user choose either an email address or a username which has already taken, he will be notified. To prevent this duplication, I have set both the email address and username fields as UNIQUE KEY in MySQL. My problems a Even by setting both the username and email address fields as UNIQUE KEY, it is not working as I can register using the same email address or username. How to solve this? I have coded also to prevent this problem of duplicate so that the user will be notified to choose another email or username, but I am having a warning. My PHP codes: Code: [Select] <?php if ($_SERVER['REQUEST_METHOD'] == 'POST') { if (isset($_POST['fname']) && isset($_POST['lname'])&& isset($_POST['emailr']) && isset($_POST['user']) && isset($_POST['pass'])) { //Assignng variables $firstname = mysql_real_escape_string($_POST['fname']); $lastname = mysql_real_escape_string($_POST['lname']); $email = mysql_real_escape_string($_POST['emailr']); $uname = mysql_real_escape_string($_POST['user']); $pwd = mysql_real_escape_string($_POST['pass']); $pmd= md5($pwd); //Database $connect = mysql_connect('localhost', 'root', '') or die ('Connection Failed'); mysql_select_db('registration', $connect) or die ('Connection Failed'); //Registration codes if (empty($firstname) || empty($lastname) || empty($email) || empty($uname) || empty($pmd)) { echo '<p class="error">All fields are required to fill!</p>'; return false; } elseif (strlen($firstname) && (strlen($lastname) < '2')) { echo '<p class="error">Invalid first name or last name!</p>'; return false; } elseif (filter_var($firstname, FILTER_VALIDATE_INT) || (filter_var($lastname, FILTER_VALIDATE_INT))) { echo '<p class="error">First name or last name cannot be integers!</p>'; return false; } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) { echo '<p class="error">Email address not valid!</p>'; return false; } elseif (strlen($uname) && (strlen($pmd) < '6' )) { echo '<p class="error">Username or password must be minimum 6 characters!</p>'; return false; } else { $query = "INSERT INTO login (id, firstname, lastname, emailaddress, username, password) VALUES('', '$firstname', '$lastname', '$email', '$uname', '$pmd')"; mysql_query($query, $connect); if (mysql_num_rows(mysql_query("SELECT * FROM login WHERE emailaddress = '$email' username = '$uname'"))) { echo '<p class="fail">This email or username is already taken!</p>'; } } } } ?> The warning message I am getting: Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\miniimagehosting\register.php on line 44 I created this database Code: [Select] <?php $mysqli = mysqli_connect('localhost', 'admin', 'jce123', 'php_class'); if(mysqli_connect_errno()) { printf("connection failed: %s\n", mysqli_connect_error()); exit(); }else{ $q = mysqli_query($mysqli, "DROP TABLE IF EXISTS airline_survey"); if($q){echo "deleted the table airline_survey....<br>";} else{echo "damm... ".mysqli_error($mysqli);} $sql = "CREATE TABLE airline_survey ( id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, staff CHAR(10) NOT NULL, luggage CHAR(10) NOT NULL, seating CHAR(10) NOT NULL, clean CHAR(10) NOT NULL, noise CHAR(10) NOT NULL )"; $res = mysqli_query($mysqli, $sql); if($res === TRUE) { echo "table created"; } else { printf("Could not create table: %s\n", mysqli_error($mysqli)); } mysqli_close($mysqli); } ?> When I look at it it looks fine. I have a form that sends data to this script: Code: [Select] <?php $con = mysql_connect('localhost', 'admin', 'abc123'); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("php_class", $con); foreach ($_POST as $key => $value) { $staff = ""; $luggage = ""; $seating = ""; $clean = ""; $noise = ""; switch($key){ case "staff": $staff = $value; break; case "luggage": $luggage = $value; break; case "seating": $seating = $value; break; case "clean": $clean = $value; break; case "noise": $noise = $value; break; default: echo "we must be in the twilight zone"; } echo $staff."<br>"; [color=red] mysql_query("INSERT INTO airline_survey (staff, luggage, seating, clean, noise) VALUES ($staff, $luggage, $seating, $clean, $noise)");[/color] } ?> as you can see right before the insert query I test one of the variables to see if it has the string I'm expecting and it does. The problem is the script runs without giving me an error message but the data never gets inserted into the table. Code: [Select] <?php ob_start(); session_start(); $pagerank=2; if ($rank < $pagerank){ header('Location:main.php?id=lowrank.php'); } else{ $name1 = $_GET["name"]; $type2 = $_GET['type']; Echo "Your seach for ".$name1." gave the following results: "; $records_per_page = 15; $total = mysql_result(mysql_query("SELECT COUNT(*) FROM systems WHERE '$type2' LIKE '%$name1%'"), 0) or die(mysql_error()); $page_count = ceil($total / $records_per_page); Echo $total." Records Found"; echo "<table border=0>"; $page = 1; if (isset($_GET['page']) && $_GET['page'] >= 1 && $_GET['page'] <= $page_count) { $page = (int)$_GET['page']; } $skip = ($page - 1) * $records_per_page; $result = mysql_query("SELECT * FROM systems WHERE $type2 LIKE '%$name1%' ORDER BY Security DESC LIMIT $skip, $records_per_page") or die(mysql_error()); echo "<table border=1>"; echo "<td>System Name</td><td>Security</td><td>Class</td>"; while ($row = mysql_fetch_array($result)) { echo "<tr>"; echo "<td valign =top>".$row['System Name']."</td>"; echo "<td valign =top>".round($row['Security'],1)."</td>"; echo "<td valign =top>".$row['System Type']."</td>"; echo "</tr>"; } echo "</table>"; echo "<br>"; for ($i = 1; $i <= $page_count; ++$i) { echo '<a href="main.php?id=' . $_GET['id'] .'&name='.$name1.'&type='.$type1. '&page=' . $i . '">' . $i . '</a> '; } } ?> The above code takes data entered in a form and is suppose to show the matching results, but no records are showing, it works when I replace the $name1 and $type2 with the actual values, any ideas? Google Chrome Developer Tool causes an error when I run the following and there are not any records. I keep getting errors when I try to change it.
<?php $host = 'localhost'; $user = 'root'; $pass = ''; $database = 'ecommerce'; $options = array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_EMULATE_PREPARES => false ); $keyword = $_GET['keyword']; $dbo = new PDO("mysql:host=$host;dbname=$database", $user, $pass, $options); $q1 = "SELECT * FROM products INNER JOIN keywords on keywords.keywordID = products.KeywordID and keywords.KeyWord1 = \"$keyword\" "; $counter = 10; $counter1 = 0; foreach ($dbo->query($q1) as $row) {
|