PHP - Random Unique Row From Mysql
Hi,
First off: I got a table with two columns and 100.000 rows. Some of the rows are duplicates (allowing me to "weight" the chance of some rows being hit the first time the script runs) Allright. This i what I want to do: When the user clicks a button: 1. Generate a random selected row from the table (this I allready accomplished using this code: Code: [Select] <?php //CODE FROM WWW.GREGGDEV.COM function random_row($table, $column) { $max_sql = "SELECT max(" . $column . ") AS max_id FROM " . $table; $max_row = mysql_fetch_array(mysql_query($max_sql)); $random_number = mt_rand(1, $max_row['max_id']); $random_sql = "SELECT * FROM " . $table . " WHERE " . $column . " >= " . $random_number . " ORDER BY " . $column . " ASC LIMIT 1"; $random_row = mysql_fetch_row(mysql_query($random_sql)); if (!is_array($random_row)) { $random_sql = "SELECT * FROM " . $table . " WHERE " . $column . " < " . $random_number . " ORDER BY " . $column . " DESC LIMIT 1"; $random_row = mysql_fetch_row(mysql_query($random_sql)); } return $random_row; } //USAGE $randomdata = random_row('MYTABLE', 'MYCOLUMN'); echo $randomdata[2]; // Where [2] is the data I want to extract. ?> This script works fine. The problem is that I want to exclude the results that have allready been shown. With me? Therefore, since I have duplicate rows of certain data, I need to exclude all the rows that are the same. I have a couple of solutions, but I can't seem to fit it into this script. (I will not use the ORDER_BY_RAND() query; it'll be too slow for a table with 100.000 rows) SO: Here's ideas I've come up with that might work, but because of my limited experience with PHP and MySQL, haven't been able to accomplish. 1) Insert a "temporary" column in the table which is filled with 1 and 0's where 1 indicates that the row has allready been taken? (If possible) 2) Use PHP sessions to store the previously generated rows? 3) Create a temporary table, which fills up with the allready generated rows by the random script? 4) Create a unique txt-file (e.g: _USERSIPADRESS__.txt) which can be used to save and extract data from the random script? (fopen, fwrite and so fourth) I hope you understand what I'm trying to do Any suggestions would be highly appreciated. Thank you. Similar TutorialsHello, 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(); } } hi, I am trying to create 7 lines, out of 49 numbers, each line must have unique numbers not seen in any other line so that every number out of 49 has been used in one of those lines, I also need them to be in order, lowest to highest except for the last number which needs to be completely any random ( as long as its not elsewhere in the 7 lines and its one of 49) I have made an attempt, <?php function code(){ for ($i=1; $i<=7; $i++){ $one = mt_rand(1, 49); echo $one; echo ' '; }} function lines(){ for ($i=1; $i<=7; $i++){ code(); echo '<br/>'; }} lines(); ?> but I am seriously failing at producing every number from 1 to 49 throughout those 7 lines and of course failing at ordering them with the random at the end that is not in order.. sorry if this sounds confusing but I would appreciate any help, thanks How to generate a unique random number in php??? Any one who can help me? I am looking to generate a random number for every user contribution as a title of the contribution. I could simply check the database each time with a query and generate a number which does not equal to any of the entries of the database. But I imagine this as inefficient and it could become slow if the database is big in my opinion. Also I'd have to contain all the numbers of the database somewhere to manage the "not equals to", in an array or something similar but that can end up as a giant one. Excuse the layman's speech I am new to this. Any suggestions how this can be solved efficiently without straining the resources too much? You can explain it linguistically and do not have to provide me any scripts, I will figure it out. hi!, is it possible to use rand() to generate unique number that will be saved in a database as a primary key? Since i dont want to have numbers like 00001 incrementing on the table. They dont look like real account numbers... i need something like 45642 or 95452 and the like. thanks in advance. How do I total unique id's with php or MySQL. For instance in MySQL I have... ID 1 1 3 4 2 1 1 3 How can I total all of the 1's, all of the twos, all of the threes and so forth. I have four 1's, one 2, two 3's and so forth... I have a mysql unique index on two columns: UNIQUE KEY `page_id` (`page_id`,`tag_id`) I have a mysql query like this: Code: [Select] mysql_query("insert into link_tags (page_id, tag_id) values ($page_id, $tag_id)"); If I run that, what would be the best way for php not to fail if the key already exists? within a while loop, would this be best? Code: [Select] if(mysql_query("insert into link_tags (page_id, tag_id) values ($page_id, $tag_id)")) continue; Or would the code above (first code) be sufficient enough? Hello guys, I am trying to write a script that runs through a CSV file and inserts unique values in a mysql database and spits the duplicate out into a new CSV. I can find the duplicates when I load it into an array, but when I insert them into a MySQL database, I cannot determine if they are duplicates. If I use INSERT IGNORE, it will run the whole file, and reject the duplicates. This is fine, except I need to create a file of the duplicate entries. What is the best way to determine if the insert attempt was rejected? I could do a select to see if the row is there, spit it out...insert if not, but I was thinking there should be a way for MySQL to talk back to me to cut the queries in half... Any ideas? Thanks I've started a to-do app, and everything works fine. Every user has his own unique to-do items that he can add. The only issue is that when I log-in with a user, ALL the items of all users are displayed when I'm redirect to my main page. I want to make it as so every user has his own page where only the to-do items he has created are visible, not every item from every user. I'm a total beginner with PHP so I'm sorry if this is a stupid question. This is my todomain.php code <?php require 'db_conn.php'; require 'config.php'; session_start(); // If the session variable is empty, this // means the user is yet to login // User will be sent to 'login.php' page // to allow the user to login if (!isset($_SESSION['id'])) { $_SESSION['msg'] = "You have to log in first"; header('location: login.php'); } // Logout button will destroy the session, and // will unset the session variables // User will be headed to 'login.php' // after loggin out if (isset($_GET['logout'])) { session_destroy(); unset($_SESSION['id']); header("location: login.php"); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset= "UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <link rel="stylesheet" href="css/bootstrap-grid.min.css"> <link rel="stylesheet" href="css/bootstrap.min.css"> <link rel="stylesheet" href="style.css"> <a href="index.php?logout='1'" style="color: black;"> Click here to Logout </a> <?php if (isset($_SESSION['success'])) : ?> <div class="error success" > <h3> <?php echo $_SESSION['success']; unset($_SESSION['success']); echo $_SESSION["username"] ?> </h3> </div> <?php endif ?> <title>TODO App</title> <script src="https://kit.fontawesome.com/d72928d9b9.js" crossorigin="anonymous"></script> </head> <body> <div class="container m-5 p-2 rounded mx-auto bg-light shadow"> <!-- App title section --> <div class="row m-1 p-4"> <div class="col"> <div class="p-1 h1 text-primary text-center mx-auto display-inline-block"> <i class="fa fa-check bg-primary text-white rounded p-2"></i> <u>My Todo-s</u> </div> </div> </div> <!-- Create todo section --> <form action="app/add.php" method="POST" autocomplete="off"> <div class="row m-1 p-3"> <div class="col col-11 mx-auto"> <div class="row bg-white rounded shadow-sm p-2 add-todo-wrapper align-items-center justify-content-center"> <div class="col"> <input class="form-control form-control-lg border-0 add-todo-input bg-transparent rounded" type="text" name="title" placeholder="Add new .."> </div> <div class="col-auto m-0 px-2 d-flex align-items-center"> <label class="text-secondary my-2 p-0 px-1 view-opt-label due-date-label d-none">Due date not set</label> <i class="fa fa-calendar my-2 px-1 text-primary btn due-date-button" data-toggle="tooltip" data-placement="bottom" title="Set a Due date"></i> <i class="fa fa-calendar-times-o my-2 px-1 text-danger btn clear-due-date-button d-none" data-toggle="tooltip" data-placement="bottom" title="Clear Due date"></i> </div> <div class="col-auto px-0 mx-0 mr-2"> <button type="submit" class="btn btn-primary">Add</button> </div> </div> </div> </div> </form> <?php $todos=$conn->query("SELECT * FROM todos ORDER BY id ASC"); ?> <div class="row mx-1 px-5 pb-3 w-80"> <div class="col mx-auto"> <?php while($todo=$todos->fetch(PDO::FETCH_ASSOC)){ ?> <!-- Todo Item 1 --> <div class="row px-3 align-items-center todo-item rounded"> <?php if($todo['checked']){ ?> <input type="checkbox" class="check-box" data-todo-id="<?php echo $todo['id'];?>" checked /> <h2 class="checked"><?php echo $todo['title'] ?> </h2> <div class="col-auto m-1 p-0 todo-actions"> <div class="row d-flex align-items-center justify-content-end"> </div> </div> <?php } else{ ?> <input type="checkbox" class="check-box" data-todo-id="<?php echo $todo['id'];?>"/> <h2><?php echo $todo['title'] ?></h2> <?php } ?> <div class="col-auto m-1 p-0 d-flex align-items-center"> <h2 class="m-0 p-0"> <i class="fa fa-square-o text-primary btn m-0 p-0 d-none" data-toggle="tooltip" data-placement="bottom" title="Mark as complete"></i> </h2> </div> <div class="col-auto m-1 p-0 todo-actions"> <div class="row d-flex align-items-center justify-content-end"> <h5 class="m-0 p-0 px-2"> <i class="fa fa-pencil text-info btn m-0 p-0" data-toggle="tooltip" data-placement="bottom" title="Edit todo"></i> </h5> <h5 class="m-0 p-0 px-2"> <i class="remove-to-do fa fa-trash-o text-danger btn m-0 p-0" data-toggle="tooltip" data-placement="bottom" title="Delete todo" id="<?php echo $todo['id']; ?>"></i> </h5> </div> <div class="row todo-created-info"> <div class="col-auto d-flex align-items-center pr-2"> <i class="fa fa-info-circle my-2 px-2 text-black-50 btn" data-toggle="tooltip" data-placement="bottom" title="" data-original-title="Created date"></i> <label class="date-label my-2 text-black-50"><?php echo $todo['date_time'] ?></label> </div> </div> </div> </div> <?php } ?> </div> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script> <script src="js/bootstrap.bundle.min.js"></script> <script src="js/myjs.js" ></script> <script src="js/jquery-3.3.1.min.js"></script> <script> $(document).ready(function(){ $(".remove-to-do").click(function(e){ const id = $(this).attr('id'); $.post('app/remove.php', { id: id }, (data) => { if(data){ $(this).parent().parent().parent().parent().hide(300); } } ); }); $(".check-box").click(function(e){ const id = $(this).attr('data-todo-id'); $.post('app/checking.php', { id: id }, (data) => { if(data!='error'){ const h2= $(this).next(); if(data === '1'){ h2.removeClass('checked'); }else{ h2.addclass('checked'); } } } ); }); }); </script> </body> </html>
I spent several hours trying to figure this thing out. Thought I had it nailed, but still getting duplicate record entries into the MySQL DB when I do NOT want them.
Here's the plot:
People filling out the possible attendance form for a Ham Radio event *sometimes* bring a 2nd person (either a spouse or a friend). The 2nd person may, or may not, also has a Callsign which I need to put INSERT the same MySQL Callsign column. In any event, to also identify the 2nd person as coming 'with' the 1st person.
MOST of the attendees are individuals with NO 2nd person.
My entry form has these primary fields:
callsign
fullname
AND...
callsign2
fullname2
What I came up with was to process the MySQL INSERT for the primary callsign & fullname into their respective MySQL DB Columns (which works fine), and then........... immediately following the main Query INSERT, to do a substitution type thing depending on whether or not a form entry was made in the callsign2 field, AND/OR, the fullname2 field.
This partially works, but if there is ONLY a primary callsign and fullname in the form, I'm still getting a duplicate record entry which includes the callsign in the `with` column (which should ONLY take place IF there is a 2nd person indicated).
Confusing?
Here is what I have been wrestling with to try and accomplish the objective, and now my eyes are glazed over ;-(
// TRICKY PART HERE // If a 2nd Callsign AND a Fullname if ($callsign2 != ' ' && $fullname2 != ' ') { // Still make reference to the primary Callsign in the MySQL DB `with` column $with = $callsign; // Assignment to allow 2nd Callsign to be entered in the MySQL `callsign` column $callsign=$callsign2; $fullname=$fullname2; $sql="INSERT INTO `mytable` (`callsign`, `fullname`, `with`) VALUES ('$callsign', '$fullname', '$with')"; // If NO 2nd Callsign BUT a Fullname } elseif ($callsign2 = ' ' && $fullname2 != ' ') { // Make reference to the primary Callsign in the MySQL DB `with` column $with = $callsign; $callsign=$callsign2; $fullname=$fullname2; $sql="INSERT INTO `mytable` (`callsign`, `fullname`, `with`) VALUES ('$callsign', '$fullname', '$with')"; } else { // The only thing I could thing of to (hopefully) NOT make a 2nd entry // record in the MySQL DB IF there is NO 2nd person referenced $with = $callsign; } if (!mysqli_query($con,$sql)) { die('Error: ' . mysqli_error($con)); }This mostly works EXCEPT if only a single (primary) person entry. The recap the objetives: 1. If ONLY a primary/single person entry on the form: * callsign & fullname get INSERTed into the `callsign` and `fullname` columns in the DB as ONLY one record entry 2. If BOTH a primary and 2nd person on the form: A. IF the 2nd person has a Callsign, then the 2nd record entry would be: * callsign2 & fullname2 get INSERTed into the `callsign` & `fullname` columns in the 2nd DB as a separate record entry * callsign of the primary person also gets INSERTED into the `with` column in the same 2nd DB record entry B. IF the 2nd person does NOT have a callsign, then the 2nd record entry would be: * fullname2 gets INSERTed into the `fullname` column in the DB as a separate 2nd DB record entry * callsign of the primary person also gets INSERTED into the `with` column in the same 2nd DB record entry I obvioiusly have overlooked something, but just can't seem to figure it out at this point {SIGH}. Thanks for any enlightenment. -FreakingOUT I have a form that passes multiple images and I wanted them to have a substring of a md5 encrypted time for generating unique codes so I don't delete or overwrite an older file. I keep the actual images in a folder and the path in mysql. The folder is working perfectly and there are no problems generating unique codes but I have been trying all night and I can't figure out why mysql won't update. I can actually get it to update but then I loose the functionallity of the code and if I don't upload a 4 images and leave one blank, the blank one deletes the previously uploaded field in the table row. Here is the md5 encrypted time for generating unique codes: Code: [Select] $unique = strtolower(substr(md5(time()), 0, 4)); This is how it works with the folder: Code: [Select] $filePath = $uploadDir . $unique . $fileName; This is how I get it to update mysql but then loose functionality: Code: [Select] $values[$i] = $unique . mysql_real_escape_string(basename(trim($_FILES[$fields[$i]]['name']))); Here is the entire code: Code: [Select] <?php require_once('storescripts/connect.php'); mysql_select_db($database_phpimage,$phpimage); $unique = strtolower(substr(md5(time()), 0, 4)); $uploadDir = 'upload/'; if(isset($_POST['upload' . $config])) { foreach ($_FILES as $file) { $fileName = $file['name']; $tmpName = $file['tmp_name']; $fileSize = $file['size']; $fileType = $file['type']; if($fileName==""){ $filePath = 'upload/'; } else{ $filePath = $uploadDir . $unique . $fileName; } $filePath = str_replace(" ", "_", $filePath); $result = move_uploaded_file($tmpName, $filePath); if(!get_magic_quotes_gpc()) { $fileName = addslashes($fileName); $filePath = addslashes($filePath); } $fileinsert[]=$filePath; } } $mid = mysql_real_escape_string(trim($_POST['mid'])); $cat = mysql_real_escape_string(trim($_POST['cat'])); $item = mysql_real_escape_string(trim($_POST['item'])); $price = mysql_real_escape_string(trim($_POST['price'])); $about = mysql_real_escape_string(trim($_POST['about'])); $fields = array(); $values = array(); $updateVals = array(); for($i=1; $i<=4; $i++) { $fields[$i] = 'name'.$i; $values[$i] = mysql_real_escape_string(basename(trim($_FILES[$fields[$i]]['name']))); if($values[$i] != '') { $updateVals[] = "{$fields[$i]} = '{$values[$i]}'"; } } $updateNames = ''; if(count($updateVals)) { $updateNames = ", " . implode(', ', $updateVals); } $update = "INSERT INTO image (mid, cid, item, price, about, name1, name2, name3, name4) VALUES ('$mid', '$cat', '$item', '$price', '$about', '$values[1]', '$values[2]', '$values[3]', '$values[4]') ON DUPLICATE KEY UPDATE cid = '$cat', item = '$item', price = '$price', about = '$about' $updateNames"; $result = mysql_query($update) or die (mysql_error()); $id = mysql_insert_id(); ?> <p style="font-size:35px; font-family:Arial, Helvetica, sans-serif; color:#255E67; margin-left:25px;">Your Item Has Been Uploaded!</p> <script type="text/javascript"> setTimeout('ourRedirect()', 2000) function ourRedirect() { location.href='protator_php.php?mid=<?php echo $id ?>' } </script> Is there anyway in MySQL you can select a random record in a table? I normally do this by generating a random number first and then using that number to find a record but was wondering if there is an easier way. Thanks for any help. How would I make it so that for every set of data where a fieldname is 1+ it picks a random one out. For example User Hit Luke 0 Peter 1 Alex 3 Peter 1 For every value where Hit is 1 or over it selects out of the query results a random username. Hello coders, I'm using this code to grab random results from a table and it works well but I need it to be a non-repeating event. Code: [Select] $offset_result = mysql_query( " SELECT FLOOR(RAND() * COUNT(*)) AS `offset` FROM `jobs_board` "); $offset_row = mysql_fetch_object( $offset_result ); $offset = $offset_row->offset; I'm using this query followed by the html which is a set of divs with inline echo statements for the various variables I've localised from the table. Then I'm repeating that process a number of times to create a small list (I wanted to use a single while loop but cant figure it out at the moment). Anways, how can I make it so each query is random but also not repeated? At the moment they are indeed random but sometimes one same entry will appear a number of times consecutively... Nice one guys, L-plate Hi I am using php5 and Mysql I want to generate user id like phone format (Ex: xxx-xxx-xxxx). and check that user id exists in database or not. if yes, i have to generate new user id etc. If that user id not in database, i have to insert user id for new user. Means i have generate unique user id for login purpose. Generating user id is working fine. availability of user id also ok for me by using mysql_num_rows() function. But if user id i exists in database, how can i generate new user id. All this will be done in single instance (When user click on submit button from registration form). Here is my script. Code: [Select] <?php function UserID() { $starting_digit=5; $first_part1=rand(0,99); if(strlen($first_part1)==1) { $first_part="0".$first_part1; } else { $first_part=$first_part1; } $second_part1=rand(1,999); if(strlen($second_part1)==1) { $second_part="00".$second_part1; } elseif(strlen($second_part1)==2) { $second_part="0".$second_part1; } else { $second_part=$second_part1; } $third_part1=rand(1,9999); if(strlen($third_part1)==1) { $third_part="000".$third_part1; } elseif(strlen($third_part1)==2) { $third_part="00".$third_part1; } elseif(strlen($third_part1)==3) { $third_part="0".$third_part1; } else { $third_part=$third_part1; } $userid=$starting_digit.$first_part."-".$second_part."-".$third_part; return $userid; } $random_userid=UserID(); $sql=mysql_query("select * from users where user_id='".$random_userid."'"); if(mysql_num_rows($sql)==0) { $insert=mysql_query("insert into users (user_id) values ('".$random_userid."')"); } ?> If user id not exists in database, that user id inserting in database successfully. If not, empty value is inserting, not generating new user id. Can any one help me out please. I have a user table that holds email addresses and for testing purposes I am trying to replace every email address with an email address defined in an array. I would like to randomly choose an email address from the array and update the table with this address. When I run the following code it randomly chooses a email address from the array but then updates every row with this one email address. Can you someone please let me know what I am doing wrong. Thanks in advance. Code: [Select] $query = "SELECT * FROM user '"; $result = mysql_query($query); $input = array('email1', 'email2', 'email3', 'email4', 'email5', 'email6', 'email7'); $rand_keys = array_rand($input, 2); $replaceStr = $input[$rand_keys[0]]; while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { $rand_keys = ""; $rand_keys = array_rand($input, 2); $replaceStr = $input[$rand_keys[0]]; mysql_query("UPDATE user SET email = '$replaceStr'"); } Hi, I'm a researcher (and complete coding noob), and am planning a longitudinal study that requires e-mail follow-up with subjects taking an initial survey. For purposes of ethics/anonymity due to sensitive survey data, I'd like the acquired e-mails to be saved uncoupled from the survey responses; this is simple to deal with, and I use a basic PHP e-mail form, which injects the email address in a table in MySQL in a different server than the one used for the survey. The issue is that the e-mails are saved in the MySQL database in order of injection, thus it is still theoretically possible for me to link the e-mails back to the survey responses (which have a time stamp that I cannot remove). Ideally I would like not to be able (at all) to link the e-mails to the survey responses, and one way to do that (since I don't save the e-mail injection timestamps in MySQL) might be to have the e-mails saved in MySQL in a random order. Not sure if this is possible, and not even sure if this would be via PHP or MySQL side of things. The server is on godaddy and uses Starfield interface for MySQL but I cannot find an option for random insert/saving of table items (emails). They are saved in order of injection. Any solution for this? Thanks, the title sounds quite ridiculous but i dont know how else to put it... i want to return results, but my site has got quite popular, quicker than i would have thought. i want to paginate the results. but i want the results to appear at random. but the results should not appear twice... can this even be done? any questions...? thanks! |