php manual increment membership no - php

i've got hundreds of people joining my website and create an membership id for them. i just created a new column in the database called user_no.
whats the mysql query for incrementing the membership no.
is it possible to start with AE then numbers ie: AE0001, AE0002, .... and it starts with 4 number not AE1, AE2..
mysql query:
UPDATE user SET user_no=..??
and on PHP side, how do i increment it? if there is a new member join in.
$db->query("INSERT INTO user (user_no) VALUES(AE'$user_no')");

Why not use an autoincrement field and append AE to it? Autoincrement will be carried out by MySQL so you don't have to worry about it in PHP : http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html
And to display your user key in the format of AE0001 you can do
$id = 'AE' . str_pad($autoincrementid, 5, "0", STR_PAD_LEFT);
http://php.net/manual/en/function.str-pad.php

I agree with everyone else who is saying that you should simply use the MySQL Auto-increment feature. That's what it's there for.
It is possible to write your own, possibly using MySQL's MAX() function to find the highest value of a field currently in the table. However unless you're using some very robust transactional code, there is always the danger that this method will result in duplicate records being created when two users create accounts at exactly the same time.
The amount of code required to avoid this is not small, and if you're inexperienced enough not to see the benefits of using Auto-increment then you're unlikely to get it right.
The whole point of Auto-increment is to save you from having to implement all that code every time.
In addition, it is highly recommended for performance reasons to use an integer value for your primary key. Sure, you can display it as "AE" . $id, but you should store it as an integer on the database.

Related

PHP if comparison vs MySQL Where (Which is more efficient)

My situation: My website will look at a cookie for a remember me token and a user ID. If the cookie exists it will unhash it and look up the user ID and compare the token. with a "WHERE userid = '' and rememberme = ''".
My question is: Will MySQL optimize this query on the unique userid so that the query does not scan the entire database for this 20+ character token? Or instead should I just select the token from the database and then use a php if comparison to check if the tokens are the same?
In short (tl;dr): Would it be better to check if a token matches in with a MySQL select query, or to grab all the tokens from a databases database and compare the values with a php if conditional?
Thanks!
Simple answer:
YES, the database will definitely optimism your search AS LONG AS THE variable you are searching in the WHERE ... portion is indexed! You definitely should not retrieve all the information via SQL and then do a PHP conditional if you are worried about performance.
So if the id column in your table is not indexed, you should index it. If you have let say... 1 million rows already in your table and run a command like SELECT * FROM user WHERE id = 994321, you would see a definite increase in performance.
Elaborating:
A database (like MySQL) is made to be much faster at executing queries/commands than you would expect that to happen in php for instance. In your specific situation, lets say you are executing this SQL statement:
$sql = "SELECT * FROM users WHERE id = 4";
If you have 1 million users, and the id column is not indexed, MySQL will look through all 1 million users to find all the rows with id = 4. However, if it is indexed, there is something called a b tree that MySQL makes (behind the scenes) which works similarly to how the indexing of a dictionary work.
If you try to find the world slowly in a dictionary, you might open the book in the middle, find words that start with the letter M and then look in the middle again of the pages on your right side hoping to find a letter closer to S. This method of looking for a word is much faster than looking at each single page from the beginning 1 by 1.
For that very reason, MySQL has created indexes to help performance and this feature should definitely be taken advantage of to help increase the speed of your queries.
Comparing it on MySQL-side should be fast. It should find the corresponding row by ID first (fast) and then compare the hash (also fast, since there will be only 1 row to check).
Try analyzing the query with EXPLAIN to find out the actual execution plan.
In my opinion it will be always faster to use WHERE clause no matter what (real) database server will be used. Database engines have strong algorithms for searching data written in language that is compiling to low-level code dedicated to platform, so it cannot be even compared with some loop written in interpreted PHP.
And remember that for PHP loop you will have to send all records from DB to PHP.
If you Data Base its on a separate server than you Apache PHP there is not doubt it would be faster if you write a query in MySQL.
If your PHP and MySQL server is on the same physical server probably PHP would be faster cause the comparison will be made on the RAM But have all the User Id array into RAM would be a waste of RAM so you can use Indexes that would speed up your query
ALTER TABLE table ADD INDEX idx__tableName__fieldName (field)

PHP loops and MySQL logic : how to?

I'm having trouble figuring out an efficient way to register a big number of data in my database, using php/mysql.
I have a list of phone numbers, which are stored in a number table.
PHONE_ID | PHONE_NUMBER | COUNTRY_ID
varchar
And a table linking a phone number with a "contact list group". Let's assume it's name is link_phonegroup.
For each phone/group link, I have a parameters list.
GROUP_ID | PHONE_ID | PARAMETERS_LIST
varchar
My script should be able to, given a group_id, compute through millions of numbers and :
retrieve the number_id associated with the number OR insert the number if it does not exist (and return the insert_id)
update the parameters_list associated with this group/number pair and if this pair does not exist, insert it
Currently, I loop (foreach) through my numbers, and, foreach number :
SELECT PHONE_ID FROM number WHERE PHONE_NUMBER = '$number'
If it does not exist, I INSERT INTO ... and retrieve this newly created id with mysql_insert_id()
Then, with this ID, I SELECT PARAMETERS_LIST FROM link_phonegroup WHERE GROUPE_ID = $group_id AND PHONE_ID = $phone_id.
If it does exist, I then UPDATE my parameters list, and if it does not, I INSERT a new row inside my link_phonegroup table.
My problem, as you may imagine, is that for each of my X millions numbers, I will fire 4 queries. That is slow, inefficient, and scary.
I learned about the INSERT INTO ON DUPLICATE KEY technique (MySQL manual page). My tests were super-slow, and i gave up.
I learned about the UPDATE CASE WHEN technique (Example).
Basically, my current goal is to fire ONE query each 200-ish loop (200 is a random number here, i'll do some tests with other values), which would insert/update/retrieveid/insert_into_this_other_table/make_me_a_sandwich/and_dont_forget_coffee, in a few words do all the work, which - I HOPE ! - will be a faster and less stressfull method for the database.
Is this the good way to go ? Is this the best way to go ?
And if it is, what would be the skeleton of this mecha-query-of-death ? I cannot figure out how to insert-or-retrieve the phone ID in the same request of the insert-or-update parameters_list given this phone ID in the same request of a hundreds of other similar requests ?
Is this even possible ?
I hope you understand my nerves here have given up since a long time.
I would be happy and thankful for any help you can give to me.
Thank you.
What you want can be done with stored procedures. I will direct you at a couple of resources first -- since you appear to know a bit about MySQL already it's probably of benefit to you to learn how stored procedures work and code it yourself rather than have someone else just feed you the stored procedure.
http://code.tutsplus.com/articles/an-introduction-to-stored-procedures-in-mysql-5--net-17843
http://www.mysqltutorial.org/mysql-stored-procedure-tutorial.aspx

preferred way to make a unique column id in sql database

Hi all I just wanted to know if there is a preferred way of creating a unique id within a sql table so far I have tried Auto-increment of the number and this started to cause problems in future planning, so I have thought about using the php Rand() and then turning this into a string and then insert this into a database but there is a higher chance off two numbers being the same with the amount of data that will be within the database.
I was just wondering if there any suggestions of a preferred way to create a unique column_id
im open to all suggestions there is just a couple things the id needs to be easy enough to be used within other tables within inner joins and left outer joins and also used a file name as well for a download section and a upload section.
use GUID
string com_create_guid ( void )
<?php
echo uniqid();
?>
Description

Check if Random Exist in the database before inserting

i made a small code that generates different type of code, but i'll make it simpler,
i have a registration form submitted while submitting i collect some info about the user and i create for him a random, but i want this random to be unique for this user.
so i have 3 cases :
$code_random = rand(1000,9999);
if($code_random < 0){
$code_random = -$code_random;
}
$random = $fname.$code_random; //case 1
$random = $lname.$code_random; //case 2
$random = $fname.lname.$code_random; //case 3
But i want to create case 1 check if this random exist in the database, if it does use the second case if it does use the third case, before submitting the form and without displaying anything for the user.
Thanks for your help in advance.
Don't reinvent the wheel - SQL databases have two great ways of assigning unique IDs to every row.
1) Auto-incrementing primary key - goes up by one for every new row. Managed by the database, guaranteed to not use the same value for two rows by mistake. Nice and small and simple. http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html
2) GUIDs (also known as UUIDs) - The algorithm used to generate GUIDs means that you'll never see the same one twice, ever. Over auto-incrementing integers, they have the advantage of being unpredictable, being generateable outside of the database and being meaningful outside of their database table context. http://www.php.net/manual/en/function.uniqid.php#94959 http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_uuid
If you really want to use a random integer, you can use the MySQL - rand() function for this
insert into users (id, ...) values (FLOOR(1000 + RAND() * (9999 – 1000)), ...)
There is a simple way of making infos unique: Create a unique index on the database column.
Then simply insert what you want and check if the database complains about violating the unique index. If this is the case, use one of your alternative queries and check again.
What if the last query still does not work?

MySQL Remove/Combine Similar Rows

I've got a problem that I just can't seem to find the answer to. I've developed a very small CRM-like application in PHP that's driven by MySQL. Users of this application can import new data to the database via an uploaded CSV file. One of the issues we're working to solve right now is duplicate, or more importantly, near duplicate records. For example, if I have the following:
Record A: [1, Bob, Jones, Atlanta, GA, 30327, (404) 555-1234]
and
Record B: [2, Bobby, Jones, Atlanta, GA, 30327, Bob's Shoe Store, (404) 555-1234]
I need a way to see that these are both similar, take the record with more information (in this case record B) and remove record A.
But here's where it gets even more complicated. This must be done upon importing new data, and a function I can execute to remove duplicates from the database at any time. I have been able to put something together in PHP that gets all duplicate rows from the MySQL table and matches them up by phone number, or by using implode() on all columns in the row and then using strlen() to decide the longest record.
There has got to be a better way of doing this, and one that is more accurate.
Do any of you have any brilliant suggestions that I may be able to implement or build on? It's obvious that when importing new data I'll need to open their CSV file into an array or temporary MySQL table, do the duplicate/similar search, then recompile the CSV file or add everything from the temporary table to the main table. I think. :)
I'm hoping that some of you can point out something that I may be missing that can scale somewhat decently and that's somewhat accurate. I'd rather present a list of duplicates we're 'unsure' about to a user that's 5 records long, not 5,000.
Thanks in advance!
Alex
If I were you I'd give a UNIQUE key to name, surname and phone number since in theory if all these three are equal then it means that it is a duplicate. I am thinking so because a phone number can have only one owner. Anyways, you should find a combination of 2-3 or maybe 4 columns and assign them a unique key. Once you have such a structure, run something like this:
// assuming that you have defined something like the following in your CREATE TABLE:
UNIQUE(phone, name, surname)
// then you should perform something like:
INSERT INTO your_table (phone, name, surname) VALUES ($val1, $val2, $val3)
ON DUPLICATE KEY UPDATE phone = IFNULL($val1, phone),
name = IFNULL($val2, name),
surname = IFNULL($val3, surname);
So basically, if the inserted value is a duplicate, this code will update the row, rather than inserting a new one. The IFNULL function performs a check to see whether the first expression is null or not. If it is null, then it picks the second expression, which in this case is the column value that already exists in your table. Hence, it will update your row with as much as information possible.
I don't think there're brilliant solutions. You need to determine priority of your data fields you can rely on for detecting similarity, for example phone, some kind of IDs, of some uniform address or official name.
You can save some cleaned up values (reduced to the same format like only digits in phones, concatenated full address) along with row which you would be able to use for similarity search when adding records.
Then you need to decide on data completeness in any case to update existing rows with more complete fields, or delete old and add new row.
Don't know any ready solutions for such a variable task and doubt they exist.

Categories