PHP - Pdo To Determine If Values Are Unique
I have a Unique Constraint setup on (emailAddress and pin) to allow multiple email addresses be the same and multiple pins but not the same emailAddress and pin value together (unique(emailAddress, pin))
Anyway, I am trying to generate a pin through a random seed, but I can't get my code to work properly to test if the combination already exists. Here is the chunk that does not work: Code: [Select] $tries = 0; $foundRows=0; do { $pin=null; $tries++; $pin = str_pad(rand(0,9), 4, "0", STR_PAD_LEFT); $stmt = $dbh->prepare("SELECT COUNT(*) FROM ajax WHERE emailAddress=:email AND pin=:pin LIMIT 1"); if ($stmt->bindParam(':email', $email, PDO::PARAM_STR) && $stmt->bindParam(':pin', $pin, PDO::PARAM_INT)) { $stmt->execute(); $foundRows = $dbh->query("SELECT FOUND_ROWS()")->fetchColumn(); echo "<br />$foundRows<br />"; } else { die ("<p>Could not bind to data verification</p>"); } } while ($foundRows > 0); This is always returning $foundRows=0 so always exiting the loop, and giving me a constraint error. Any ideas? Maybe a better way to do this? Similar TutorialsI have a table that I must be populated based on a check box selection. The maximum selection is 5, however, there are more then 10 choices. For example: Here is a choice of 10 different (checkbox) options that the user can select from: 1. Coke 2. Root Beer 3. Pepsi 4. Dr. Pepper 5. Sprite 6. 7up 7. Cream Soda 8. Club Soda 9. Water 10. Milk I've already managed to limit the users selection to only 5. My issue is determining which of the checkboxese were actually selected so that I can correctly place them in my database. The first thing to do is create variables from all the checkboxes: $coke = $_POST['coke']; $rootbeer = $_POST['rootbeer']; $pepsi = $_POST['pepsi']; $drpepper = $_POST['drpepper']; etc. etc. Now that I have all 10 selections as variables from a submitted form how can I determine which ones are empty (or which ones have values) so that I can then save them to the database respectively? I have a simple db with values. I want to find all duplicate values and rename them 1,2,3 - so if I have these values for a 'colour' field: pID / color 1 / brown 2 / blue 3 / red 4 / red 5 / brown ...would result in: 1 / brown1 2 / blue 3 / red1 4 / red2 5 / brown2 ...is this possible? Hi I am new this forum and looking for some much appreciated help with something that has me stumped. I have extracted regions from image names in a directory. example: 'edinburgh_castle_(Edinburgh).jpg' (Extracted Edinburgh from in-between the brackets) So I have a list of Regions, extracted from all the various image names in the directory which I want to populate into a dynamic drop down menu for filtering purposes. Here's my issue... I want there to be only one 'Edinburgh' option appearing in my drop down menu. I don't want duplicates. Here is my code so far. php: [Select] Hello All, I have a contact directory database. It has all the employees of my company (name, phone, email, department, building, etc). Say on one page I have the Marketing Department, and I want to say: "The Marketing Department Director is ________" How would I assign that value from the database? Do I want to put in a unique "keyword" field in the database, but then how would I store all the values automatically on the page? I see pages where I would want to list the Marketing Director, and his secretary, then another page with the Sales Director, and his secretary, etc.... all with being able to change the values in the database, and it changing across all the pages instantly. Do I need to say on every page "select * from database where keyword = marketingdirector" and then store that result as a variable? It seems unpractical to repeat that a few times for each different person I want to list. Is there a better way to do this then I'm thinking? Thanks all! Hi all, I have a situation where I need to remember what check boxes where checked over pagination, I have managed to do this via the use of this: http://jamesfunk.com/wordpress/?p=65 The problem is that as the code stood: Code: [Select] <input type="checkbox" name="compare" value="<?php echo $list['jobseeker_id'];?>" class="remember_cb"/> It was treating one ticked checkbox as them all because they all have the same name and are in the a while loop! I countered this by changing the code to: Code: [Select] <input type="checkbox" name="compare<?php echo $list['jobseeker_id']?>" value="<?php echo $list['jobseeker_id'];?>" class="remember_cb"/> Which effectively now makes the checkbox name unique... i.e. compare{id}. The problem with this is that I can now no longer process it. This is my processing code: $jobseekers = $_POST['compare']; $i = 0; for($i; $i<count($jobseekers); $i++){ $query = "SELECT * FROM jobseekers WHERE jobseeker_id = '$jobseekers[$i]'"; $result = mysql_query($query) or die (mysql_error()); while ($row = mysql_fetch_array($result)) { // Spit out the required data } } As you can see I am trying to get the data from $_POST['compare'], which will obviously now be blank as I have had to make the name unique.... the trouble is I'm not sure how to actually process this. Can anyone help me out here? any help or advice would be greatly appreciated! many thanks, Greens85 Hello, I need some help. Say that I have a list in my MySQL database that contains elements "A", "S", "C", "D" etc... Now, I want to generate an html table where these elements should be distributed in a random and unique way while leaving some entries of the table empty, see the picture below. But, I have no clue how to do this... Any hints? Thanks in advance, Vero I have a mysql table which will store users email addresses (each is unique and is the primary field) and a timestamp. I have added another column called `'unique_code' (varchar(64), utf8_unicode_ci)`. What I would very much appreciate assistance with is; a) Generating a 5 digit alphanumeric code, ie: 5ABH6 b) Check all rows the 'unique_code' column to ensure it is unique, otherwise re-generate and check again c) Insert the uniquely generated 5 digit alphanumeric code into `'unique_code'` column, corresponding to the email address just entered. d) display the code on screen. What code must I put and where? **My current php is as follows:** Code: [Select] require "includes/connect.php"; $msg = ''; if($_POST['email']){ // Requested with AJAX: $ajax = ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'); try{ if(!filter_input(INPUT_POST,'email',FILTER_VALIDATE_EMAIL)){ throw new Exception('Invalid Email!'); } $mysqli->query("INSERT INTO coming_soon_emails SET email='".$mysqli->real_escape_string($_POST['email'])."'"); if($mysqli->affected_rows != 1){ throw new Exception('You are already on the notification list.'); } if($ajax){ die('{"status":1}'); } $msg = "Thank you!"; } catch (Exception $e){ if($ajax){ die(json_encode(array('error'=>$e->getMessage()))); } $msg = $e->getMessage(); } } All, I have a zip code and for example the zip code is 01101. How can I determine if the first character in this is a zero? Thanks in advance. This may sound funny, but I'm not sure what I was trying to get this code to do... Code: [Select] <!-- Find Current Page Name --> <?php $page = basename($_SERVER['REQUEST_URI']); echo '<p>$page = ' . $page . '</p>'; // if ($page == '') { if (($page == '/')||($page == '')||($page == 'index.php')){ $page = "index.php"; echo '<p>You are on the Home Page.</p>'; }else{ echo '<p>You are on Some Other Page.</p>'; } What I mean by that is I'm not understanding why I chose... Code: [Select] if ($page == '') { and then... Code: [Select] if (($page == '/')||($page == '')){ and then... Code: [Select] if (($page == '/')||($page == '')||($page == 'index.php')){ Why would I get those different results from basename($_SERVER['REQUEST_URI'])?? And what should I expect locally on my Laptop with a Virtual Host set up (e.g. "http://local.debbie/index.php") versus using a Test Site (e.g. "http://www.doubledee.byethost2.com/") versus a real site (e.g. "www.debbie.com")?! Hope I'm making some sense here... Debbie I am pulling records from a mysql db. Example Output: Team A= Our Team Team b = An opponent team Team A score = 7 Team B score = 8 Team A = Our Team Team b = Another Opponent Team A score = 3 Team B score = 1 What I need now is to add ONE more output, which is whether this is a "WIN" or a "LOSS". Should I add a field into the table that calc's this? If so, how? Please be specific. Or, should I use php to compare Team A score vs Team B score PER every record and then insert this new variable into the output. If so, how do I create a new variable value for every single output in the table? I know ultimately that this is a IF THEN type of calc, but can't quite figure out how specifically. Please be specific. Thanks My uploader allows the following file formats: jpg gif png I tested that if someone was to name a file configure.php.jpg, my uploader allows it to upload I want to do a check to see if the user has 2 extensions, and if so it will not allow them to upload. I was thinking of just checking if the file name has two "." (dots) in the name. What function could I use to do this? Or .. is there a better way? Am currently using this code, and actually thinking about it should split the query to an include in order to allow for other database drivers, on the chance we may decide to ditch the old MySQL. But I digress from the question. Code: [Select] include($lib."dbconfig.php"); $q = 'SELECT * FROM file WHERE this = "'.$that'"; $result = mysql_query($q); if (mysql_num_rows($result) > 0) If the query doesn't pick up a row I'm getting this error yo, Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in D:\webpages\*\*\admin.php on line 553 So what would be a better way of testing if the query was successful? Hi, Competitors vs. against each other and are recorded in a database. Each participant equally has 4 matches each, as you can see in the attatchment following the points gained in their played matches. I want to be able to determine the qualified participants according to either their "points" or "wins/losses". If two competitors have the same points, then I have already made a solution that another match must be generated for the two participants with the same points and draws can not be submitted which means the points will always be different for each team. I want to pick out half of participants 8/16 (screenshot below) with highest points which will be the qualifiers, or pick out half participants 8/16 with best match stats according to wins/losses. Any help I would be very grateful, thanks. I can determine which radio button is selected for each file upload prompt because I have a name and a value. So the array name=image can have one of three values for each file upload prompt. Is there a way to determine which of the three file upload prompts was loaded (clicking browse & select image) with an image and which was not? There doesn't seem to be a value like there is with radio buttons. I want to be able to replace an already uploaded image with another. Thanks. <input type='radio' name='image[image0]' value='keep' checked='checked'/> <input type='radio' name='image[image0]' value='delete' /> <input type='radio' name='image[image0]' value='replace' /> <input type="file" name="image[]" /> <input type='radio' name='image[image1]' value='keep' checked='checked'/> <input type='radio' name='image[image1]' value='delete' /> <input type='radio' name='image[image1]' value='replace' /> <input type="file" name="image[]" /> <input type='radio' name='image[image2]' value='keep' checked='checked'/> <input type='radio' name='image[image2]' value='delete' /> <input type='radio' name='image[image2]' value='replace' /> <input type="file" name="image[]" /> if (isset($_POST['submitted']) && ($image = $_POST['image'])) { foreach($image as $imageKey => $imageValue) { if ($imageValue == 'keep') { do this } } } Hi, I'm making an attempt to build a small cms based site. I have read in a lot of places it is best to use the id of a table row to fetch contents, but being as I am using url rewrite in frontend, it won't be showing query strings, so I thought I would ask if anyone saw any potential problems if I did the following. Page table looks like this: Pages - id - name - content In backend, the user has a form to name the page and use ckeditor to add rich content. I will use php to ensure that the name is alphanumeric and use strtolower & str_replace to ensure that My First HTML Page is sent to mysql as my-first-html-page and also check that a row with this name does not already exist. So on front end this page url will be mywebsite.com/my-first-html-page So to output the content I strip out the domain & / so I'm left with the name as entered in the db. $url = $_SERVER['REQUEST_URI']; $url = str_replace ('/','',$url); Then in my function to output content I will use WHERE name = $url I have this function, but it doesnt work. Basically the list outputs a list of news features, and puts a line under neath each article to seperate them. However once the last article has been reached, I don't want the break to be shown. this is my code, any help would be appreciated as i am really struggling on this. Just need to determine the last item in the array, and stop the <hr split> from being output. function newsFeature(){ $event = "SELECT imgname, title, content, pkID from news ORDER BY date, time DESC LIMIT 5"; $event_page = query($event); $count = numRows($event_page); while ($row = mysql_fetch_assoc($event_page)) { $rowcount = $count; $para = substr($row['content'] , 0,100); $result .= '<article>'; $result .= '<a href="news-article.php?pkID=' . $row['pkID'] . '"><img src="uploads/thumbs/' . $row['imgname'] . '" alt="" width=116 height=83/ ></a>'; $result .= '<h2><a href="news-article.php?pkID=' . $row['pkID'] . '">' . $row['title'] . '</a></h2>'; $result .= '<p>' . $para . '...</p>'; $result .= '<p><a class="read-more" href="news-article.php?pkID=' . $row['pkID'] . '">Read more<span></span></a></p>'; $result .= '</article>'; if($row != end($row[])){ $result .= '<hr class="split">'; } } return $result; } How to reliably determine if server is Apache using PHP? For example isApache() function? When I upload new files, their file name is stored into my database. I have been told that a couple of the file downloads weren't working. Upon further investigation I figured out that the file the person wanted to download was nowhere to be seen in my downloads directory. How can I determine if a file exists in my directory? I assume I can somehow use the location that is stored inside my database (ex: myfile.pdf) and compare that with what's in the folder. Hey all, I would like to know the best way to determine whether a value has been changed in a multi select transfer. For example, I have two select fields. User clicks on button to add an item to the right select element with id of select2 from the left select element with an id of select1. When they click update, it posts to a php method. This is where I am uncertain what to do. How can I check that they indeed added or removed items from the right select element and if they did, determine which ones were removed or added to make the reflected changes in the database? This is what I have, but it's bad solution because it deletes all related records before it adds the ones it finds to the right select element: Code: [Select] public function update(){ $subcategory = new Category(); $subcategory->where('id',$this->uri->segment(4))->get(); $subcategory->delete($subcategory->related_category->get()->all); $new_parents = $this->input->post('catupload'); $parent_category = new Category(); $parent_category->where_in('controller',$new_parents)->get(); $subcategory->save($parent_category->all); } This is what the form elements look like: Code: [Select] echo "You can add or remove one or many parents associated with this category:"; echo "<div class='multiselect-transfer'>"; echo form_multiselect('catadd[]',$other_cats,'','id="select1"'); echo anchor('#','add >>','id="add"'); echo "</div>"; echo "<div class='multiselect-transfer'>"; echo form_multiselect('catupload[]',$default_cats,'','id="select2"'); echo anchor('#','<< remove','id="remove"'); echo "</div>"; echo form_submit('submit','Update'); echo form_close(); $other_cats variable holds array of categories that have not been asssociated with the current category being updated when this category was first created. The $default_cats variable holds an array of categories that have been associated with the current category being updated when this category was first created. And the javascript: Code: [Select] $().ready(function() { $('#add').click(function() { return !$('#select1 option:selected').remove().appendTo('#select2'); }); $('#remove').click(function() { return !$('#select2 option:selected').remove().appendTo('#select1'); }); }); Thanks for response. |