PHP - Updating Sql If Item Exists
Hi all
I am trying to write a piece of code that cheks to see if an item is in the SQL databse and updates the quantity if it is, or adds it as a new line if it isn't. Here's my code: Code: [Select] if (isset($_GET['add'])) { $id = $_GET['id']; $qty = $_GET['qty']; $date = date ('D M j G:i:s'); $sql_products = mysql_query("SELECT * FROM `items` WHERE `id` = '".$id."'"); $result_products = mysql_fetch_array($sql_products); $product_title = $result_products['title']; $product_price = $result_products['price']; $sql_inbasket = mysql_query("SELECT * FROM `store_basket` WHERE `id` = '".$id."' AND sessionid = '".$sessionid."'"); $isiteminbasket = mysql_num_rows($sql_inbasket); if ($isiteminbasket == 0) { mysql_query ("INSERT INTO `store_basket` SET sessionid = '".$sessionid."', productid = '".$id."', item = '".$product_title."', qty = '".$qty."', price = '".$product_price."', date = '".$date."'"); header("Location: basket.php"); } else { mysql_query("UPDATE `store_basket` SET qty = qty + 1 WHERE id = '".$id."' AND sessionid = '".$sessionid."'") ; header("Location: basket.php"); } } Every time I try and add the same item to the basket, it adds as a new line instead of updating the existing line. Many thanks for your help! Pete Similar TutorialsHi all I am trying to write a piece of code that checks to see if an item is in the SQL database and updates the quantity if it is, or adds it as a new line if it isn't. Here's my code: Code: [Select] if (isset($_GET['add'])) { $id = $_GET['id']; $qty = $_GET['qty']; $date = date ('D M j G:i:s'); $sql_products = mysql_query("SELECT * FROM `items` WHERE `id` = '".$id."'"); $result_products = mysql_fetch_array($sql_products); $product_title = $result_products['title']; $product_price = $result_products['price']; $sql_inbasket = mysql_query("SELECT * FROM `store_basket` WHERE `id` = '".$id."' AND sessionid = '".$sessionid."'"); $isiteminbasket = mysql_num_rows($sql_inbasket); if ($isiteminbasket == 0) { mysql_query ("INSERT INTO `store_basket` SET sessionid = '".$sessionid."', productid = '".$id."', item = '".$product_title."', qty = '".$qty."', price = '".$product_price."', date = '".$date."'"); header("Location: basket.php"); } else { mysql_query("UPDATE `store_basket` SET qty = qty + 1 WHERE id = '".$id."' AND sessionid = '".$sessionid."'") ; header("Location: basket.php"); } } Every time I try and add the same item to the basket, it adds as a new line instead of updating the existing line. Many thanks for your help! Pete I have a script that seems to work well to insert a bookmark into a users database when he/she is logged into the system but I am having a hard time figuring out how I would go about making a work-a-round for having an item selected before being logged in, and inserted after they have logged in or registered. For example, I would like a user to be able to select an Item to add to bookmark whether that user is logged in/registered or not and if they are not, they would be greeted with a login/registration form and after successful login the add bookmark script would be initiated on the item previously selected. What I've got this far: Simple form to add bookmark: <form name="bm_table" action="add_bms.php" method="post"> <input type="text" name="new_url" value="http://" /> <input type="submit" value="Add Bookmark"/> </form> Then I have the add bookmark script: BEGIN php $new_url = $_POST['new_url']; try { check_valid_user(); //cannot get past this part since it ends the script....code below if (!filled_out($_POST)) { throw new Exception('Form not completely filled out.'); } // check URL format if (strstr($new_url, 'http://') === false) { $new_url = 'http://'.$new_url; } // check URL is valid if (!(@fopen($new_url, 'r'))) { throw new Exception('Not a valid URL.'); } // try to add bm add_bm($new_url); echo 'Bookmark added.'; // get the bookmarks this user has saved if ($url_array = get_user_urls($_SESSION['valid_user'])) { display_user_urls($url_array); } } catch (Exception $e) { echo $e->getMessage(); } END php Checking valid user - the portion I cannot get past in the above script: function check_valid_user() { // see if somebody is logged in and notify them if not if (isset($_SESSION['valid_user'])) { echo "Logged in as ".$_SESSION['valid_user'].".<br />"; } else { // they are not logged in do_html_heading('Problem:'); echo 'You are not logged in.<br />'; do_html_url('login.php', 'Login'); do_html_footer(); exit; } } How would I go about modifying the script so that a user could fill in the form (later it would be a link...obviously they probably wouldn't be filling in a form that is log-in specific - but same concept I think) Thanks in advance for the help! tec4 Hi there, I think this is a big question but I'd appretiate any help you can provide!! I have a list of items and subitems in a table that looks like this: id parent_id title 1 0 House Chores 2 1 Take Out Trash 3 1 Clean Room 4 0 Grocery List 5 4 Eggs 6 4 Produce 7 6 Lettuce 8 6 Tomato 9 4 Milk I want to display it like this: (+) House Chores: > Take Out Trash > Clean Room (+) Grocery List: > Eggs (+) Produce > Letutce > Tomato > Milk So basically each entry in the table has an unique id and also a parent id if it's nested inside another item. I "sort of" got it figured out in one way, but it doesnt really allow for nested subgroups. I'd like to know how would y'all PHP freaks to this Also taking suggestions for the javascript code to expand/collapse the tree !! Thank you! Well I am looking to change this url Code: [Select] http://website.com/product.php?Item=2369 to Code: [Select] http://website.com/product.php?Item=Item-Name Heres a snip of the code that handles that. <?php include_once('mysql_connect.php');$id = (int)$_GET['Item'];?>() any help would be appreciated. Hi community,i creating a simple website and description i analyzed my code about 3days...2hours a day. if i get the point in my head.then its say Website url is in use..but not..ok maybe i give the code below. so if you can explain whats wrong.thanks Code: [Select] <?php include_once ('connect.php'); $url= mysql_real_escape_string($_POST['url']); $desc=mysql_real_escape_string($_POST['desc']); if ($id == "krauti") { if (empty($_POST['url']) && empty($_POST['desc'])) { die('<br><center>Both Empty!.<center/><br/>'); } if (empty($_POST['url'])) { die('<br><center>URL Empty!.<center/>'); } if (empty($_POST['desc'])) { die('<br><center>desc empty fill it!.<center/>'); } $url = htmlspecialchars( stripslashes( strip_tags($_POST['url'] ) ) ); $aprasymas = htmlspecialchars( trim($_POST['desc'] ) ); $query = mysql_query("SELECT * FROM linkai WHERE url = '$url' AND 'desc' = '$desc'"); if( mysql_num_rows( $query ) == 1 ) { "INSERT INTO linkai ". "(id, url, desc) ". "VALUES('','$_POST[url]','$_POST[desc]')"; echo "Yes!."; } else if (mysql_num_rows($query) == 0 ){ echo "No!!"; } } ?> Can someone explain why this code: if (mysql_result($data,0,$SQLLargeName) = " "){ $LargeImage = "#"; } else { $LargeImage = mysql_result($data,0,$SQLLargeName); } Gives me this error? Fatal error: Can't use function return value in write context in /home/worldw44/public_html/SQL.php on line 38 And ways round it? Thanks. <SCRIPT LANGUAGE="JavaScript"> <!-- Begin function popUp(URL,URL2) { day = new Date(); id = day.getTime(); eval("page" + id + " = window.open(URL,'" + id + "', 'toolbar=0,scrollbars=1,location=0,top=10,left=10,statusbar=0,menubar=0,resizable=0,width=408,height=400');"); day = new Date(); id = day.getTime(); eval("page" + id + " = window.open(URL2,'" + id + "', 'toolbar=0,scrollbars=1,location=0,top=10,left=450,statusbar=0,menubar=0,resizable=0,width=408,height=400');"); } // End --> </script>I have a map which shows sales people by location and if more then one sales person exists then I would need 2 pop up windows. This works great other than the fact that the areas with one sales person are getting a blank 2nd popup as a second salesperson does not exist. Any help would be appreciated. Thanks In Advance Edited by phpbeginner, 27 June 2014 - 05:52 AM. I apologize in advance for any misuse of terminology. I find that I am rather ignorant in such things. I'm working on a WordPress theme. Specifically on the part that shows the "next: link-to-next-post" and "previous: link-to-prev-post" links. Here is the code that I have: Code: [Select] <?php $nextvar=next_post_link('%link'); $prevvar=previous_post_link('%link'); ?> <?php if (isset($nextvar)) { ?> <h3>Next</h3> <p><?php next_post_link('%link'); ?></p> <? } ?> <?php if (isset($prevvar)) { ?> <h3>Previous</h3> <p><?php previous_post_link('%link'); ?></p> <? } ?> The first part intends to check if the links exist. And this works fine. However, the only output I'm getting are the values of $nextvar and $prevvar. The headers are nonexistent. What's wrong? Any help is much appreciated, and I thank you in advance. Hi all, I have the following mysql delete query that essentially deletes a row from two seperate tables "messages" and "messages2" where the id is equal to that in both of the tables. The problem I am getting (for obvious reasons) is that it will only delete from the table, if it indeed exists in both tables. Here is the query: Code: [Select] DELETE FROM messages,messages2 USING messages,messages2 WHERE messages.id = messages2.id AND messages.id = ?; How would I go about setting it so that the query always deletes from table "messages" and only deletes from "messages2" when a corresponding id exists? I think it would involve an IF EXISTS clause, but I am not sure on this, or indeed how to implement it. Thanks in advance guys Dan This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=328831.0 My error below returns (echos) that there is no data under the table sites to display. But, there is. Why is it doing this? class_l.php <?php class displaySites { function grabSites() { $query = mysql_query("SELECT title,description,votes,dates,comments,out,in FROM sites ORDER BY id DESC LIMIT 100"); if(mysql_num_rows($query) > 0) { while($fetch = mysql_fetch_assoc($query)) { echo " <div id='post-1' class='post'> <h2 class='title'><a href='#'>". $fetch['title'] ."</a></h2> <h3 class='date'>Submitted on ". $fetch['date'] ."</h3> <div class='entry'> <p>". nl2br(stripslashes($fetch['description'])) ."</p> </div> <p class='meta'><a href='#'>View</a></p> <div class='hr'> </div> </div> "; } } else { echo " <div id='post-1' class='post'> <h2 class='title'><a href='#'>Oh NOEZ!</a></h2> <h3 class='date'>". date("M-d-Y") ."</h3> <div class='entry'> <p>There are currently no sites to display!</p> </div> <p class='meta'>View</p> <div class='hr'> <hr /> </div> </div> "; } } } class register { function createAccount() { $username = mysql_real_escape_string($_POST['username']); $password = md5(sha1(sha1($_POST['password']))); $name = mysql_real_escape_string($_POST['title']); $description = mysql_real_escape_string($_POST['description']); if(isset($username) && isset($password) && isset($name) && isset($description)) { if(!$username || !$password || !$name || !$description) { echo '<table border="0"><form action="register.php" method="POST"> <tr><td>Username</td><td><input type="text" name="username" maxlength="20"></td></tr> <tr><td>Password</td><td><input type="text" name="password" maxlength="30"></td></tr> <tr><td>Site Name</td><td><input type="text" name="title" maxlength="25"></td></tr> <tr><td>Site Description</td><td><textarea cols="40" rows="18" name="description" maxlength="750"></textarea></td></tr> <tr><td>Finish!</td><td><input type="submit"></td></tr> </form></table>'; } else { $query = mysql_query("SELECT * FROM sites WHERE username = '$username' LIMIT 1"); if(mysql_num_rows($query) > 0) { echo "Sorry, an account with this username already exists."; } else { $date = date("M-d-Y"); $ip = $_SERVER['REMOTE_ADDR']; //create their account mysql_query("INSERT INTO sites VALUES (null, '$username', '$password', '$name', '$description', 0, 0, 0, '$date', '$ip', 0)"); echo "You have successfully registered your site on NovaTops! <a href='login.php'>Login</a>"; } } } else { echo "One or more of the variables are not set."; } } } class login { function verifyLogin() { $username = mysql_real_escape_string($_POST['username']); $password = md5(sha1(sha1($_POST['password']))); if(isset($username) && isset($password)) { if(!$username || !$password) { echo "<table><form action='login.php' method='POST'> <tr><td>Username</td><td><input type='text' name='username' maxlength='20'></td></tr> <tr><td>Password</td><td><input type='password' name='password' maxlength='30'></td></tr> <tr><td>Finished?</td><td><input type='submit'></td></tr> </form></table>"; } else { $query = mysql_query("SELECT * FROM sites WHERE username = '$username' AND password = '$password'LIMIT 1"); if(mysql_num_rows($query) > 0) { echo "Congratulations! You have successfully logged in! <a href='index.php'>Home</a>"; $_SESSION['user'] = $username; } else { echo "It seems you've typed in the wrong username and/or password. <a href='login.php'>Try Again</a>"; } } } else { echo "One or more of the variables aren't set."; } } } ?> index.php <?php include_once('includes/config.php'); include_once('class_l.php'); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title><?php echo $title; ?></title> <meta name="keywords" content="" /> <meta name="description" content="" /> <link href="styles.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="wrapper"> <div class="top_text"><h1><a href="#"><?php echo $site_name; ?></a></h1> <h2><a href="#"><?php echo $slogan; ?></a></h2></div> <div id="content"> <div id="blog"> <div id="post-1" class="post"> <h2 class="title"><a href="#">Welcome to NovaTops!</a></h2> <h3 class="date">Created on April 06, 2011</h3> <div class="entry"> <p>Hello there! If your viewing this message right now, your on the awesome site called NovaTops! NovaTops allows you to register your site in our database, and then the site's script automatically starts to rank your site. The higher your rank, the more likely your site's going to get a ton of views!</p> </div> <div class="hr"> <hr /> </div> </div> <!-- end #post-1 --> <?php $displaySites = new displaySites(); $displaySites->grabSites(); ?> </div> <!-- end #blog --> <?php include_once('includes/navigation.php'); ?> <!-- end #sidebar --> <div style="clear: both; height: 1px;"></div> </div> <!-- end #content --> <div id="footer"> <p>Copyright © 2011. Design by <a href="http://www.flashtemplatesdesign.com/" title="Free Flash Templates">Free Flash Templates</a></p> <p><a href="#">Privacy Policy</a> | <a href="#">Terms of Use</a> | <a href="http://validator.w3.org/check/referer" title="This page validates as XHTML 1.0 Transitional"><abbr title="eXtensible HyperText Markup Language">XHTML</abbr></a> | <a href="http://jigsaw.w3.org/css-validator/check/referer" title="This page validates as CSS"><abbr title="Cascading Style Sheets">CSS</abbr></a></p> </div> </div> <!-- end #wrapper --> </body> </html> Maybe I am over thinking this, but I would like to see if their is another value after the current value without moving the internal array pointer. What can I do? Hi, I have a sign up form that generates a activation key and emails it to user and they cannot login until account has been activated etc. My problem is i am not sure how to in php generate a new activation key if the generated one has already been used. I know how to do the MySQL query to check if activation key already exists but not sure how to basically tell PHP that if the activation key already exists in DB then generate a new key until one is found that does not already exist. I gather i may need a loop but not sure. Could someone please help ? Like i say i know how to do the MySQL query just need some sample code to know how to do what i asked above. Thanks for anyhelp; Much Appreciated hello, have a question. im trying to do a select * where id exists in array $id8 here is my array Code: [Select] $result8 = mysql_query("SELECT * FROM customers WHERE whosclient = 'Lansoft'"); while($row8 = mysql_fetch_array($result8)) { $id8=$row8['id']; } here is my select code. it is only returning results for the highest number in the array Code: [Select] $result = mysql_query("SELECT * FROM timesheets WHERE status = 3 AND billable = 1 AND client = '$id8' ORDER BY date, starttime"); while($row = mysql_fetch_array($result)) { Thanks for any help! Code: [Select] $result = mysql_query("SELECT field_item_id_value FROM `content_type_ads`"); while($row = mysql_fetch_array($result)){ echo $row['field_item_id_value']; echo "<br />"; echo $result; } I am trying to use an "array diff()" argument and I am getting errors with it stating the above is not an array. I have used $row and $result, and neither work. Is this not dumping into an array properly? All, In my registration script I am trying to check if an email address already exists (yawn I know), and I am stuck. The code highlighted in bold is where I want to check if the email exists (notice that form checking is done above that, including sorting out the email address that the user enters) and if it doesnt insert data into the table. Trouble is that on loading the page it simply states the 'already submitted' error before an email is even entered into the form: Code: [Select] if(isset($_POST['name']) && !empty($_POST['name']) AND isset($_POST['email']) && !empty($_POST['email']) AND ($_POST['password']) && !empty($_POST['password'])){ $name = mysql_escape_string($_POST['name']); // Turn our post into a local variable $email = mysql_escape_string($_POST['email']); $password = mysql_escape_string($_POST['email']);// Turn our post into a local variable } $name = mysql_escape_string($_POST['name']); $email = mysql_escape_string($_POST['email']); $password = mysql_escape_string($_POST['password']); if(!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)){ // Return Error - Invalid Email $msg = 'The email you have entered is invalid, please try again.'; }else{ // Return Success - Valid Email $msg = 'Your account has been made, <br /> please verify it by clicking the activation link that has been sent to your email.'; } $hash = md5( rand(0,1000) ); // Generate random 32 character hash and assign it to a local variable. // Example output: f4552671f8909587cf485ea990207f3b [b]$emailCheck = mysql_query("SELECT email FROM users WHERE email = '".$email."'"); if (mysql_num_rows($emailCheck) > 0) { echo "already submitted"; } else {[/b] // We have a match, activate the account mysql_query("INSERT INTO users (username, password, email, hash) VALUES( '". mysql_escape_string($name) ."', '". mysql_escape_string(md5($password)) ."', '". mysql_escape_string($email) ."', '". mysql_escape_string($hash) ."') ") or die(mysql_error()); Thanks in advance, G Hi folks, Working on something and I'm not sure how best to do it. It's a system whereby customers can login and see pdf files. Each customer has a unique reference number which is mirrored with a folder on the server, the folder name being the customer reference number. That's the first bit of checking. Then, within that customer folder there will be between 1 and X sub folders which are labelled by unique product reference numbers. Beyond that, each of the product reference folders will have a year folder with a folder for each month of the year going forward. Here's an example of the folder structu - Customer Number (e.g. 12345678) - Product Number (e.g. 456789) (could be more than one) - Year (e.g. 2011) (could be more than one) -Month (e.g. 01/02/03/04/05/06 etc) Essentially, I'm just unsure how to check if folders exist and display their contents if they do. Here's my code so far, which does the first part of checking to see if the product numbers exist, but not the folder checking (I've not activated the hyperlinks in this code yet). This doesn't go as far as years and months yet, just the product number: Code: [Select] $query = mysql_query("SELECT * FROM customers where id = '$id'"); while($rst = mysql_fetch_array($query)) { echo "$rst[company_name]"; } $query = mysql_query("SELECT * FROM sites where company_name = '$company'"); while($rst = mysql_fetch_array($query)) { echo "$rst[site]<br>"; if ($rst[product1] !== ""){ echo "- <a href='#'>$rst[product1]</a><br>"; } if ($rst[product1] == ""){ echo ""; } if ($rst[product2] !== ""){ echo "- <a href='#'>$rst[product2]</a><br>"; } if ($rst[product2] == ""){ echo ""; } if ($rst[product3] !== ""){ echo "- <a href='#'>$rst[product3]</a><br>"; } if ($rst[product3] == ""){ echo ""; } if ($rst[product4] !== ""){ echo "- <a href='#'>$rst[product4]</a><br>"; } if ($rst[product4] == ""){ echo ""; } if ($rst[product5] !== ""){ echo "- <a href='#'>$rst[product5]</a><br>"; } if ($rst[product5] == ""){ echo ""; } Looking for the best method to conditionally strip leading zeros for the following situation: $a = array(01, 02, 03, ... 10, 11); $a < 10 ? $a = ? : ''; For the following result: 1, 2, 3, ... 10, 11 Is there a better method than explode? Hello, I want to check when adding a new user, that if there are 2 records that has the same recruiter id, it's should give an error, if less, than it makes him complete the registration Also check if the National ID number is not assigned to another user, so if there is a record that has it, it should give and error, if it's unavailable, it should let him complete the registration here is my code register.html Code: [Select] <html> <form action="post.php" method="post"> <table> <tr><td>First Name: <input type="text" name="fname" /></td></tr> <tr><td>Middle Name: <input type="text" name="mname" /></td></tr> <tr><td>Last Name: <input type="text" name="lname" /></td></tr> <tr><td>Mobile: <input type="text" name="mobile" /></td></tr> <tr><td>Telephone: <input type="text" name="tel" /></td></tr> <tr><td>Address: <input type="text" name="address" /></td></tr> <tr><td>Job Title: <input type="text" name="job" /></td></tr> <tr><td>Company: <input type="text" name="company" /></td></tr> <tr><td>National ID Number: <input type="text" name="nid" /></td></tr> <tr><td>Recruiter ID: <input type="text" name="recruiteris" /></td></tr> <tr><td>Email: <input type="text" name="email" /></td></tr> <tr><td>Password: <input type="password" name="password" /></td></tr> <tr><td>Type: <input type="text" name="type" /></td></tr> <tr><td><input type="submit" /></td></tr> </table> </form></html> post.php Code: [Select] <?php $sql="INSERT INTO users (id,fname, mname, lname, mobile, tel, address, job, company, nid, recruiteris, email, password, type) VALUES ('','$_POST[fname]','$_POST[mname]','$_POST[lname]','$_POST[mobile]','$_POST[tel]','$_POST[address]','$_POST[job]','$_POST[company]','$_POST[nid]','$_POST[recruiteris]','$_POST[email]','$_POST[password]','$_POST[type]')"; if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } echo "1 record added"; echo "<br />"; echo "<a href='http://waw-eg.com/admin/register.html'>Add More Client? Click Here</a><br/>"; echo "<a href='http://waw-eg.com/admin/Users.php'>View Users Click Here</a>"; mysql_close($con) ?> What is the best/proper way to check if a supplied URL goes to an actual image? My site will allow users to enter an image URL (like "http://example.com/images/monkey.jpg"). I will store the URL they enter in a MySQL database and then will call it up later and do some resizing to these images. But I don't want to try to do any resizing if the URL they supply doesn't actually go to an image, or if it's blank (i.e. the user didn't enter a URL yet). So basically, I will run a MySql query to pull back the contents of the column called "imageurl". Let's say those contents are stored in a variable called $imageurl. This is what I'm trying to accomplish.... Code: [Select] if ($theimageurl does NOT contain a URL to an image OR is blank) { // do this } else { //run my resizing code } I guess i could do this to check to see if it's blank, but not sure this is proper/most efficient way to check that part of the issue... Code: [Select] if (trim($theimageurl) == "") But greater than the "is it blank" concern is that people may enter URLs that just to a regular website so whether it's at this point in my code (or for security, I should probably do it BEFORE inserting it into my database :/ ) so curious if there are any functions that check to see if it's an image URL or not. I know of file_exists, but I'm pretty sure that's just checking to see if a file exists and doesn't check image URLs. Any info/suggestions would be appreciated as always! And if there are any recommended functions to check/clean the user-entered URL BEFORE it's entered into the database, please share Thanks! |