PHP - Create Unique Id For Mysql?
Hello guys,
Similar TutorialsI 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(); } } Hello Good day,
I am have a project for company. Can you please give me advice on how will I going to determine each computer assigned to each employee.
I have my own working unit (PC), of course that i used to login on our company web site. But when someone try to log in on our web site using their own account on my working unit it will be registered as fraud.
My problem is how will i am going to check if accountTwo try to log in on accountOne pc unit. Right now we're using cookie but if they use other browser or private browser the data on the cookie was not send on the request.
Righ now I am trying to determine using Mac Address of each PC, but still can't figure out how to get the Mac Address. It gives the server address where the site was hosted.
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? 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... 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. 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> 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 want to create array from mysql what is the script for this...? value like $data = array("1" => .0032, "2" => .0028, "3" => .0021, "4" => .0033, "5" => .0034, "6" => .0031, "7" => .0036, "8" => .0027, "9" => .0024, "10" => .0021, "11" => .0026, "12" => .0024, "13" => .0036, "14" => .0028, "15" => .0025); Hey yall! I'm working on a new site idea and I've run across a problem that I know is simple enough but I'm stumped. It's in the signup form What I want to do is insert the new user into the 'Login' table and get the user id that was just created and use that to create a table with the user id in the name. Here is what I have: // now we insert user into 'Login' table mysql_real_escape_string($insert = "INSERT INTO `Login` (`UID`, `pass`, `HR`, `mail`, `FullName`) VALUES ('{$_POST['username']}', '{$_POST['pass']}', '{$_POST['pass2']}', '{$_POST['e-mail']}', '{$_POST['FullName']}')"); mysql_query($insert) or die( 'Query string: ' . $insert . '<br />Produced an error: ' . mysql_error() . '<br />' ); $error="Thank you, you have been registered."; setcookie('Errors', $error, time()+20); // Get user ID mysql_real_escape_string($checkID = "SELECT * FROM Login WHERE `mail` = '{$_POST['e-mail']}'"); while ($checkIDdata = mysql_fetch_assoc($checkID)) { $userID = $checkIDdata; // now we create table 'Transactions" for the user mysql_real_escape_string($create = "CREATE TABLE `financewatsonn`.`Transactions_{$userID}` ( `ID` INT( 20 ) NOT NULL AUTO_INCREMENT COMMENT 'Transaction ID', `name` VARCHAR( 50 ) NOT NULL COMMENT 'Name/Location', `amount` VARCHAR( 50 ) NOT NULL COMMENT 'Amount', `date` VARCHAR( 50 ) NOT NULL COMMENT 'Date', `category` VARCHAR( 50 ) DEFAULT NULL COMMENT 'Category', `delete` INT( 1 ) NOT NULL DEFAULT '0', UNIQUE KEY `ID` ( `ID` ) ) ENGINE = MYISAM DEFAULT CHARSET = utf8 COMMENT = 'User ID {$userID}'"); mysql_query($create) or die( 'Query string: ' . $create . '<br />Produced an error: ' . mysql_error() . '<br />' ); } I know in 'Get user ID' that I need to get the ID but I'm not sure how to get that information. i get the error Quote Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource at 166 which is the while line under Get user ID Hey guys, Currently Im using the code: while($row=mysql_fetch_array($nt)){ echo" $row[user_login],$row[user_email],$row[CallHistoryTimes],$row[CallHistoryInfo],$row[CallHistoryLastOp]$row[CallHistoryLastDate],<br>"; } To list a mysql array; what I am trying to do is to use the mysql row ID and turn the entire string above into a list. So for example, the database would get the ID information & create a link of edit.php/?id=3 If someone could help me on this it would be mega appreciated. Thanks What I mean by dynamic is say I created a function to generate a random code. I put it in a variable named $key. I make a form with a hidden input type with the name and value of $key. When the form posts, it generates the table name to whatever $key is. Because I tried something like this & its not querying. Heres my code: <?php $dbc = mysqli_connect('localhost', 'cpacrop_todo', 'pass', 'cpacrop_todo') or die('Failed to connect to database!'); function make_key($num_chars) { if ((is_numeric($num_chars)) && ($num_chars > 0) && (! is_null($num_chars))) { $key = ''; $accepted_chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'; //seed srand(((int)((double)microtime()*1000003)) ); for ($i=0; $i<=$num_chars; $i++) { $random_number = rand(0, (strlen($accepted_chars) -1)); $key .= $accepted_chars[$random_number] ; } return $key; } } $key = make_key(6); ?> <form action="" method="post"> <input type="hidden" name="<?php echo "$key"; ?>" /> <input type="submit" name="submit" value="Submit" /> </form> <?php if ($_POST['submit'] == "Submit") { $query = "CREATE TABLE `$key` ( `id` INT AUTO_INCREMENT, `title` VARCHAR(35), `description` VARCHAR(365) );"; mysqli_query($dbc,$query) or die('Unable to query database.'); echo "Success"; } ?> If this is possible, what am I doing wrong? Thanks! i have two tables, employee details table(empno, emp_name , branch) and attendance table(date, Ot, attendence). I want to create a relation between two tables I want to create a text file based blog ( not using MySQL or other databases). I have tried to google for tutorials but I couldn't find anything. is there anyone who can help me and give me some tips? is there any tutorials about this because I found nothing? Any good books? This is an assignment that I have to do and I am using this book: Spring into PHP 5 by Addison Wesley. I am a newbie in php and really want to do this because this is my last task and I really want to learn. So I'm grateful if anyone can help me. How would I create a prepared mysql temp table using PHP? I currently write my prepared statements like the example below. How would I create a "TEMP" table? Thanks!
$connection8y = new mysqli("host", "xxx", "xxx", "db"); Hi there, I hope somebody can help me creating a loop for the following code: What it currently does is, showing only 1 image, while in fact there are 3 of them. I've combined a loginsystem with slideviewer. When i use the original php code (or a part of it) it only shows one listing. I need it to list all of them. <div id="mygalone" class="svw"> <ul> <li> <?php $result = mysql_query("SELECT reference FROM user_photos WHERE`profile_id`='".$row['id']."'"); while ($row2 = mysql_fetch_array($result, MYSQL_ASSOC)) { echo "<a href=\"".$_GET['username']."/pics/".$row2['reference']."\"> <img src=\"".$_GET['username']."/pics/thumbs/".$row2['reference']."\"></a><br/><br/>"; } } ?> </li> </div> What can be stripped down to this: <?php { $result = mysql_query("SELECT reference FROM user_photos WHERE`profile_id`='".$row['id']."'"); while ($row2 = mysql_fetch_array($result, MYSQL_ASSOC)) { echo "<img src=\"".$_GET['username']."/pics/".$row2['reference']."\">"; } } ?> You would asume that this is allready a loop, but it does not act like it. Best regards, Martijn (the netherlands) I have a mysql table with the structure of Code: [Select] ID Menu_Name Parent_ID 1 Finance NULL 2 Business NULL 3 Investment 1 4 Trading 2 How can I create a html <ul><li> list based on the parent? |