PHP - Duplicate Entry In Sql Database
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. Similar Tutorialshey 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()); } } Hi.. So im currently working on a script.. My script generates a "oid" based on timestamp. Ive made the "oid" field unique in my db, so if i do a quick refresh i get the message: Duplicate entry '1283195988' for key 'oid' Is there some way i can check if its a dublicate, and if it is + it with 1 or something? Hey guys! I know, I know this problem is EVERYWHERE but i just dont understand! I have a solid knowlage of php but my SQL skills are low, so i dont know too much about Keys and stuff. But my error is: Duplicate entry '' for key 2. The thing that im working on at this section is logging in with facebook. The code that presents my error is: $sql = "SELECT * FROM users WHERE uid=".$uid; $fbid = mysql_query($sql); $num_rows = mysql_num_rows($fbid); if(mysql_num_rows($fbid) < 1) { echo "You are not logged in. "; mysql_query("INSERT INTO `users` (`uid`) VALUES ('".$uid."')") or die(mysql_error()); } else { mysql_query("UPDATE users SET logged = '1' WHERE uid=".$uid); //mysql_query("UPDATE users SET full_name = $me WHERE uid=".$uid); echo "Your Logged in "; echo $me['name']; ?> Continue to <a href="removed :)"> My Settings </a>. <? } Any help is welcome Hey folks, Sorry for being a pain in the ass. I am trying to submit data to my database via a form and when I click Submit, I get: Duplicate entry '' for key 1 I understand that it means I have a duplicate entry with the ID of 1 or something like that. I can't find where the issue is. Here is the form: <form actin="" id="settings" name="settings"> <table class="listing form" cellpadding="0" cellspacing="0"> <tr> <th class="full" colspan="2"><?php echo $lang_settings; ?></th> </tr> <tr> <th colspan="2"><?php echo $lang_settings_description; ?></th> </tr> <tr> <td><?php echo $lang_sitename; ?>: </td> <td><input type="text" name="sitename" value="<?php echo $site_name; ?>" width="172" /> <em>Site name for logo</em></td> </tr> <tr> <td><?php echo $lang_email; ?>: </td> <td><input type="text" name="email" value="<?php echo $site_email; ?>" width="172" /> <em>Your email address</em></td> </tr> <tr> <td><?php echo $lang_yourname; ?>: </td> <td><input type="text" name="name" value="<?php echo $your_name; ?>" width="172" /> <em>Your own name</em></td> </tr> <tr> <td><?php echo $lang_meta_description; ?>: </td> <td><input type="text" name="meta-description" value="<?php echo $description; ?>" width="172" /> <em>SEO</em></td> </tr> <tr> <td><?php echo $lang_keywords; ?>: </td> <td><input type="text" name="meta-keywords" value="<?php echo $keywords; ?>" width="172" /> <em>Separate with Commas</em></td> </tr> <tr> <td><input type="submit" class="button" name="submit" value="<?php echo $lang_button_savesettings; ?>"></td> </tr> </table> </form> Here is the Insert code: $insert = "INSERT INTO settings (site_name, description, keywords, email, name) VALUES ('$sitename', '$meta_description', '$meta_keywords', '$site_email', '$your_name')"; mysql_query($insert) or die(mysql_error()); Can anyone please tell me where I am going wrong here? Much appreciated. Hi I am getting this error message and don't know why. please help this is the message " Error: Duplicate entry '' for key 1 " Here is the code Code: [Select] <?php include'../DB-connection.php'; $sql="INSERT INTO Company(CompanyName,Address,Logo,PhoneNumber,ContactPerson) VALUES('".mysql_real_escape_string($_POST[CompanyName])."', '".mysql_real_escape_string($_POST[Address])."', '".mysql_real_escape_string($_POST[Logo])."', '".mysql_real_escape_string($_POST[PhoneNumber])."', '".mysql_real_escape_string($_POST[ContactPerson])."')"; if(!mysql_query($sql,$con)) { die(' Error: '. mysql_error()); } echo " <center>your compnay info added       <a href='User-Login.php'>Login to Post a job</a> </center>" ; mysql_close($con) ?> What exactly does the entry in the title mean? I cannot make sense out of it. I would appreciate if somebody can shed some light in. The error message occurs when I try to vote with the voting system I created. Please i ran into this problem help me : Code: [Select] <p>Posted by <a href=""> <?php if(isset($_GET['id'])) { $tpid=$_GET['id']; } else { $tpid=$_POST['id']; } include"header.php"; $sql="SELECT*FROM topics WHERE topicsid='$tpid'"; $result=mysql_query($sql) or die(mysql_error()); while($row=mysql_fetch_array($result)) { echo"{$row['topics_by']}"; echo"</a></p>"; echo"<p>"; echo"{$row['topics_subject']}"; echo" <p align='left'><img src='speakout_1.png'/>"; echo"{$row['topics_content']}"; echo"<p class='post-footer align-right'> <a href='' class='comments'>"; session_start(); if(isset($_SESSION['views'])) $_SESSION['views']=$_SESSION['views']+1; else $_SESSION['views']=1; echo"Comments:".$_SESSION['views']; echo"</a>"; echo"<span class='date'>"; echo"{$row['topics_date']}"; } ?></span> </p> </div> <h3>Comments:</h3> <table> <tr class="row-a"> <td class="first"></td> <td><?php include"header.php"; $sql="SELECT post_content,post_by FROM post WHERE topicsID='$tpid'"; $result=mysql_query($sql)or die(mysql_error()); while($row=mysql_fetch_array($result)) { echo"<strong>{$row['post_by']}</strong>: {$row['post_content']}"."</br>"; } ?></td> </tr> </table> <?php include"header.php"; if(isset($_POST['submit'])) { $comment=mysql_real_escape_string(trim($_POST['comment'])); $name=mysql_real_escape_string(trim($_POST['name'])); $hidden=$_POST['id']; if($comment!=='' && $name!=='') { $ins="INSERT INTO post(topicsID,post_content,post_by)VALUES('$hidden','$comment','$name')"; mysql_query($ins) or die(mysql_error()); } else { echo"you cannot post an empty field"; } } ?> <h3>Post your comments here</h3> <form action=''method='post'> <textarea name="comment" id="content" style="width:400px;height:50px;background-color:#D0F18F;color:#000000;font:15px/20px cursive;scrollbar-base-color:#638E0D;"></textarea> <br /> Name:<input type="text"name="name"/> <input class="button" type="submit"name="submit"value="submit" /> <input type="hidden"name="id"value='<?php echo "$tpid"; ?>'/> </p> </form> <br /> </div> Hi there, I am trying to add a bit of php to capture an email address and add it to mysql database. This part works fine but i get this message: Error: Duplicate entry '' for key 'PRIMARY' How do i get rid of this error? Thanks! <?php session_start(); include('include/includes.php'); $cart = Cart::CreateInstance(); if(isset($_GET)){ foreach($_GET as $k=>$v){ $smarty->assign($k,$v); } } if(isset($_GET['remove'])){ $cart->RemoveItems($_GET['remove'],1); } if(isset($_GET['removeAll'])){ $cart->RemoveItems($_GET['removeAll'],$_GET['counts']); } if(isset($_GET['emptyCart'])){ if($_GET['emptyCart']){ $cart->EmptyCart(); header("Location: cart.html"); exit(0); }} if(isset($_GET['add'])){ $itemId = $_GET['add']; $size = $_GET['size']; if (isset($_GET['qty'])) { $qty = $_GET['qty']; } else { $qty = 1; } $cart->addItems($itemId.'-'.$size, array($size,$itemId), $qty); } $cart = Cart::CreateInstance(); $cartBox = $cart->GetCart(); //print_r($cartBox); $total = 0; $subTotal = array(); $db = new DB(); $prods = $db->select("SELECT friendly,name,id FROM products"); $smarty->assign('prods',$prods); if(is_array($cartBox)){ foreach($cartBox as $key=>$item){ $id = $cartBox[$key]['data']->_itemData[1]; $products = $db->select("SELECT detail,image,friendly,name FROM products WHERE id='$id'"); $detailjson = json_decode($products[0]['detail']); foreach($detailjson as $detail){ list($k, $v) = split_by_colon($detail); if($k == $cartBox[$key]['data']->_itemData[0]){ $price = $v;} } $cartBox[$key]['data']->_itemData[3] = $products[0]['image']; $cartBox[$key]['data']->_itemData[6] = $products[0]['name']; $cartBox[$key]['data']->_itemData[2] = $products[0]['friendly']; $cartBox[$key]['data']->_itemData[5] = $price; $sub = (int)$item['count'] * $price; $cartBox[$key]['data']->_itemData[4] = $sub; $total += $sub; } } else { $cartBox = array(); } $count = $cart->GetItemsCount(); $shipping = (int)0; if($total>0&&$total<5){ $shipping = 2.99; }elseif($total>5&&$total<10){ $shipping = 3.99; }elseif($total>10&&$total<15){ $shipping = 4.99; }elseif($total>15&&$total<20){ $shipping = 5.99; }elseif($total>20&&$total<30){ $shipping = 6.99; }elseif($total>30&&$total<40){ $shipping = 7.99; }elseif($total>40&&$total<50){ $shipping = 8.99; }elseif($total>50&&$total<60){ $shipping = 9.99; }elseif($total>60&&$total<70){ $shipping = 10.99; }elseif($total>70&&$total<80){ $shipping = 11.99; }elseif($total>80&&$total<90){ $shipping = 12.99; }elseif($total>90&&$total<100){ $shipping = 15.99; }elseif($total>100&&$total<110){ $shipping = 16.99; }elseif($total>110&&$total<120){ $shipping = 17.99; }elseif($total>120&&$total<130){ $shipping = 18.99; }elseif($total>130&&$total<140){ $shipping = 19.99; }elseif($total>140&&$total<150){ $shipping = 20.99; }elseif($total>150&&$total<160){ $shipping = 21.99; }elseif($total>160&&$total<170){ $shipping = 22.99; }elseif($total>170&&$total<180){ $shipping = 23.99; }elseif($total>180){ $shipping = 24.99; } /* 0 - 4.99 = 2.99 5 - 9.99 = 3.99 10 - 14.99 = 4.99 15 - 19.99 = 5.99 20 - 29.99 = 6.99 30 - 39.99 = 7.99 40 - 49.99 = 8.99 50 - 69.99 = 9.99 70 - 99.99 = 10.99 100+ = 12.99 */ if(isset($_GET['eushipping'])||(isset($_POST['rec_country'])&&$_POST['rec_country']!='uk')){ if($_POST['rec_country']=='au' || $_GET['country']=='au'){ //Set shipping for Austria $shipping = ceil($total/60.00)*30.00; }elseif($_POST['rec_country']=='be' || $_GET['country']=='be'){ //Set shipping for Belgium $shipping = ceil($total/60.00)*20.00; }elseif($_POST['rec_country']=='bu' || $_GET['country']=='bu'){ //Set shipping for Bulgaria $shipping = ceil($total/60.00)*50.00; }elseif($_POST['rec_country']=='cy' || $_GET['country']=='cy'){ //Set shipping for Cyprus $shipping = ceil($total/60.00)*108.00; }elseif($_POST['rec_country']=='cz' || $_GET['country']=='cz'){ //Set shipping for Czech Republic $shipping = ceil($total/60.00)*33.00; }elseif($_POST['rec_country']=='de' || $_GET['country']=='de'){ //Set shipping for Denmark $shipping = ceil($total/60.00)*30.00; }elseif($_POST['rec_country']=='es' || $_GET['country']=='es'){ //Set shipping for Estonia $shipping = ceil($total/60.00)*45.00; }elseif($_POST['rec_country']=='fi' || $_GET['country']=='fi'){ //Set shipping for Finalnd $shipping = ceil($total/60.00)*30.00; }elseif($_POST['rec_country']=='fr' || $_GET['country']=='fr'){ //Set shipping for France $shipping = ceil($total/60.00)*28.00; }elseif($_POST['rec_country']=='ge' || $_GET['country']=='ge'){ //Set shipping for Germany $shipping = ceil($total/60.00)*25.00; }elseif($_POST['rec_country']=='gr' || $_GET['country']=='gr'){ //Set shipping for Greece $shipping = ceil($total/60.00)*50.00; }elseif($_POST['rec_country']=='hu' || $_GET['country']=='hu'){ //Set shipping for Hungary $shipping = ceil($total/60.00)*25.00; }elseif($_POST['rec_country']=='ir' || $_GET['country']=='ir'){ //Set shipping for Ireland $shipping = ceil($total/60.00)*25.00; }elseif($_POST['rec_country']=='it' || $_GET['country']=='it'){ //Set shipping for Italy $shipping = ceil($total/60.00)*30.00; }elseif($_POST['rec_country']=='la' || $_GET['country']=='la'){ //Set shipping for Latvia $shipping = ceil($total/60.00)*42.00; }elseif($_POST['rec_country']=='li' || $_GET['country']=='li'){ //Set shipping for Lithuania $shipping = ceil($total/60.00)*35.00; }elseif($_POST['rec_country']=='lu' || $_GET['country']=='lu'){ //Set shipping for Luxembourg $shipping = ceil($total/60.00)*20.00; }elseif($_POST['rec_country']=='ma' || $_GET['country']=='ma'){ //Set shipping for Malta $shipping = ceil($total/60.00)*108.00; }elseif($_POST['rec_country']=='ne' || $_GET['country']=='ne'){ //Set shipping for Netherlands $shipping = ceil($total/60.00)*25.00; }elseif($_POST['rec_country']=='no' || $_GET['country']=='no'){ //Set shipping for Norway $shipping = ceil($total/60.00)*37.00; }elseif($_POST['rec_country']=='pol' || $_GET['country']=='pol'){ //Set shipping for Poland $shipping = ceil($total/60.00)*35.00; }elseif($_POST['rec_country']=='por' || $_GET['country']=='por'){ //Set shipping for Portugal $shipping = ceil($total/60.00)*30.00; }elseif($_POST['rec_country']=='ro' || $_GET['country']=='ro'){ //Set shipping for Romania $shipping = ceil($total/60.00)*48.00; }elseif($_POST['rec_country']=='slv' || $_GET['country']=='slv'){ //Set shipping for Slovakia $shipping = ceil($total/60.00)*32.00; }elseif($_POST['rec_country']=='slk' || $_GET['country']=='slk'){ //Set shipping for Slovenia $shipping = ceil($total/60.00)*29.00; }elseif($_POST['rec_country']=='sp' || $_GET['country']=='sp'){ //Set shipping for Spain $shipping = ceil($total/60.00)*36.00; }elseif($_POST['rec_country']=='swe' || $_GET['country']=='swe'){ //Set shipping for Sweden $shipping = ceil($total/60.00)*32.00; }elseif($_POST['rec_country']=='swi' || $_GET['country']=='swi'){ //Set shipping for Switzerland $shipping = ceil($total/60.00)*55.00; }elseif($_POST['rec_country']=='ukh' || $_GET['country']=='ukh'){ //Set shipping for UK - Highlnads and Islands $shipping = ceil($total/60.00)*18.00; }elseif($_POST['rec_country']=='ukn' || $_GET['country']=='ukn'){ //Set shipping for UK - Northern Island $shipping = ceil($total/60.00)*18.00; }elseif($_POST['rec_country']=='jng' || $_GET['country']=='jng'){ //Set shipping for Jersey and Guernsey $shipping = ceil($total/60.00)*34.00; } } /* */ if(isset($_GET['count'])){ echo (int)$count; exit; } if(isset($_GET['order'])){ if($_GET['order']){ }} if(isset($_GET['ajax'])){ $noAjax = $_GET['ajax']; }else{ $noAjax = false; } $smarty->assign('noAjax',$noAjax); if(isset($_GET['t'])){ $t=$_GET['t'].'.tpl'; } else { $t = 'cart.tpl'; } if(isset($_POST['cmd'])) { $_SESSION['paypal'] = $_POST; //print_r($_POST); } if(isset($_POST['rec_houseA1'])){ $filename = time().'-'.rand(1,499); $paypal = $_SESSION['paypal']; unset($paypal['checkout_x']); unset($paypal['checkout_y']); $_SESSION['addresses'] = $_POST; $File = 'sales/'.$filename.'.php'; $Handle = fopen($File, 'x'); fwrite($Handle,'<? '); fwrite($Handle,'$cart = array('); foreach($cartBox as $k=>$v){ fwrite($Handle,'"'.$k.'"=>array('); foreach($v as $key=>$value){ if(is_object($value)){ fwrite($Handle,'"'.$key.'"=>(object)array('); foreach($value as $keys=>$values){ if(is_array($values)){ fwrite($Handle,'"'.$keys.'"=>array('); foreach($values as $keyd=>$valued){ fwrite($Handle, '"'.$keyd.'"=>"'.$valued.'",'); } fwrite($Handle,'""=>""),'); }else{ fwrite($Handle, '"'.$keys.'"=>"'.$values.'",'); } } fwrite($Handle,'""=>""),'); }else{fwrite($Handle, '"'.$key.'"=>"'.$value.'",');} } fwrite($Handle,'""=>""),'); } //$total += $_POST['shipping']; fwrite($Handle,'"total"=>"'.$total.'");'); fwrite($Handle,' '); fwrite($Handle,'$detail = array('); foreach($_POST as $k=>$v){ if(is_array($v)){ fwrite($Handle,'array('); foreach($v as $key=>$value){ if(is_array($value)){ fwrite($Handle,'array('); foreach($value as $keys=>$values){ fwrite($Handle, '"'.$keys.'"=>"'.$values.'",'); } fwrite($Handle,')'); }else{fwrite($Handle, '"'.$key.'"=>"'.$value.'",');} } fwrite($Handle,')'); }else{ fwrite($Handle, '"'.$k.'"=>"'.$v.'",'); } } fwrite($Handle,'""=>"");'); fwrite($Handle,' '); fwrite($Handle,'$paypal = array('); foreach($paypal as $k=>$v){ if(is_array($v)){ fwrite($Handle,'array('); foreach($v as $key=>$value){ if(is_array($value)){ fwrite($Handle,'array('); foreach($value as $keys=>$values){ fwrite($Handle, '"'.$keys.'"=>"'.$values.'",'); } fwrite($Handle,')'); }else{fwrite($Handle, '"'.$key.'"=>"'.$value.'",');} } fwrite($Handle,')'); }else{ fwrite($Handle, '"'.$k.'"=>"'.$v.'",'); } } fwrite($Handle,'""=>"");'); fwrite($Handle,' '); fwrite($Handle,'$shipping = "'.$shipping.'"; '); fwrite($Handle,'$subtotal = "'.$total.'"; '); $totals = $total+$shipping; fwrite($Handle,'$totals = "'.$totals.'";'); fclose($Handle); $smarty->assign('filename',$filename); $smarty->assign('shipping',$shipping); $smarty->assign('paypal',$paypal); //print_r($paypal); $smarty->display('paypal.tpl'); }else{ $smarty->assign('total',$total+$shipping); $smarty->assign('itemsInBox',$count); $smarty->assign('cartBox',$cartBox); $smarty->assign('shipping',$shipping); $style = $db->select("SELECT * FROM styles WHERE `name`='default'"); $smarty->assign('style',$style); $smarty->display($t); } ?> <?php $con = mysql_connect("organicgrowshopcouk.fatcowmysql.com","worm","*******"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("ogs_mailinglist1", $con); $sql="INSERT INTO mailinglist (email) VALUES ('$_POST[rec_email]')"; if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } mysql_close($con); ?> I have a table called "colors". It has 2 columns, id and color. All I'm trying to do is pull the data into the form, then edit the colors (for example - misspelled, etc.) Then submit it back to the table. Here is the code that pulls the data into a form so I can edit it: Code: [Select] <form action="adminupdatecolors.php" method="post"> <table width="500" border="1" cellpadding="10"> <tr> <td>Color Options:</td> <td> <? $result = mysql_query("SELECT * FROM colors"); while ($row = mysql_fetch_assoc($result)) { echo '<input type="text" name="color[]" value="' . $row['color'] . '"/>' . $row['id'] . '<br />'; } ?> </td> </tr> <tr> <td> </td> <td><input type="Submit" value="Update Colors"></td> </tr> </form> </table> Here is my update script: Code: [Select] <?php include("config.php"); include("db.php"); $id=$_POST['id']; $color=$_POST['color']; $result = mysql_query("SELECT id FROM colors ORDER BY id DESC LIMIT 0,1"); if ($row = mysql_fetch_assoc($result)) { $id = $row['id']; } $sql = "DELETE FROM colors WHERE id='$id'"; mysql_query($sql) or die("Error: ".mysql_error()); foreach ($color as $colorvalue) { $sql2 = "INSERT INTO colors (id,color) VALUES ($id,'$color')"; mysql_query($sql2) or die("Error: ".mysql_error()); } header("Location: " . $config_basedir . "adminhome.php"); ?> 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 i'm trying to get the username of the last person to enter something into a database table,and display it an html table. the problem is, the query is failing, and i get the error "Table 'forum.posts' doesn't exist". if in the error message "forum" means the name of the database, and "posts" the name of the table, there is something wrong, as they both exist. the code i'm using is below $list = "SELECT * FROM section_main ORDER BY section_title"; $result = mysql_query($list) or die ("Query failed"); $numofrows = mysql_num_rows($result); for($j = 0; $j < $numofrows; $j++) { $row = mysql_fetch_array($result); echo "<tr><th>". $row['section_title']."</th></tr>"; $query2 = "SELECT * FROM section_sub WHERE section_id = '".$row['section_id']."' ORDER BY section_sub_title"; $result2 = mysql_query($query2) or die("Select Error :" . mysql_error()); $numofrows2 = mysql_num_rows($result2); for($i = 0; $i<$numofrows2; $i++){ $row2 = mysql_fetch_array($result2); echo "<tr><td><a href='display_forum.php?id={$row2[section_sub_id]}'>".stripslashes($row2[section_sub_title])."</a></td><td>"; $new = mysql_query("Select * FROM posts WHERE section_sub_id = '".$row2['section_sub_id'] . " ' ") or die ("Select Error :" . mysql_error()); //this is where the error message is from $lastpost = mysql_fetch_assoc($new); echo $lastpost['username']; echo"</td></tr>"; } } i've checked that the names of the tables and fields in the queries are correct, but i cant think of anything else that might be wrong. any help would be great. 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... I'm working on an old cms I built a few years ago and for some reason my Delete page isn't working. It has to be something simple I'm overlooking. The database connection is made just above this code and is pulling the thumb and title listed by id. When I push delete I'm getting the cmd=delete&id=2 passed on so something is up with my last if statement (I think). Here is the code: if(!isset($cmd)) { //display all the news $result = mysql_query("select * from verizon order by id"); //run the while loop that grabs all the news scripts while($r=mysql_fetch_array($result)) { //grab the title and the ID of the enws $title=$r["title"];//take out the title $id=$r["id"];//take out the id $thumb=$r["thumb"]; echo "<div id='delete'> <table> <tr> <td width='350px'><strong>$title</strong></td><td><a href='verizondelete.php?cmd=delete&id=$id'> Delete</a></td> </tr> <td colspan='2' align='center'><img src='../upload/verizon/$thumb'></td> </table> </div><br />"; } } if($cmd=="delete") { $sql = "DELETE FROM verizon WHERE id='$id'"; $result = mysql_query($sql); echo "<h1 style='text-align:center;'>deleted!</h1>"; } } ?> Hi I'm very much a newbie to PHP and am struggling with a registration and login problem. The registration part is fine - the password is emailed out fine, I check the database and the entry is there, the password is encrypted. but when the user tries to log in.... if (mysql_num_rows($result) == 0) .... it returns 0? and the access denied page is shown. I'm thinking it is something to do with the sql database encryption? I'm completely lost here and would appreciate some guidance Thanks in advance Jan 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 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>"; } } Hi, Would someone please give me some assistance on how to display random products from my database I need to display a maximum of 6 images and there link in two rows of 3 so; [image] [image] [image] [image] [image] [image] and each image would have something like; <a href="<? echo $row['product_link'] ?>"><img src="<? echo $row['product_image'] ?>"/></a> but i don't know how to display these at random and make sure only 6 appear at a time. Thanks for any help, hope you understand what im trying to explain Hey guys, im new around here, and i have just recently started teaching myself PHP, by looks of this site i seem very experienced but im eager to learn I seem to get an error with this code. The point of this code is to look into my database and pull out all entries with the first name _____ (whatever the user inputs) Error: Warning: mysql_fetch_array() expects parameter 1 to be resource, null given in C:\xampp\htdocs\searchans.php on line 12 Code: Filename:search.php Code: [Select] <html> <form action='searchans.php' method='POST'> First Name: <input type='text' name='firstname'><br> <input type='submit' value='Search'> </form> </html>Code: Filename:searchans.php Code: [Select] <?php $firstname = $_POST['firstname']; $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); } $query = mysql_query("SELECT * FROM Persons WHERE FirstName='$firstname'"); while($row = mysql_fetch_array($result)) { echo $row['FirstName'] . " " . $row['LastName'] . " " . $row['Age']; echo "<br />"; } ?> Hello all. I am finishing up a paypal IPN php script and was wondering how I can take some data and cut some of it off before I enter it into the mysql database? Heres what I have. $payment_date = HH:MM:SS DD Mmm YY, YYYY PST This comes from paypal. I want to in my code take that and automatically cut off the HH:MM:SS part. So my question is, how can I take a known piece of data and automatically trim the first 9 spots off of it? Something like: $payment_date = HH:MM:SS DD Mmm YY, YYYY PST Minus 1 thru 9 of $payment_date = $result $payment_date2 = $result Any help? Thanks! |