How to assign a unique ID to a database object - php

In my app, any user can create a post object which contains a title, description, and ID. These post objects are stored in a database within a server. However, I need a way to assign unique ID's to the posts, so I can assign the user to their post (only the ID of a post will be stored in the core data of the poster's phone).
Right now I'm using integers as the ID. For example, when a user submits a post, I have it so the database is queried and I find the ID of the last post submitted and then make the ID of the current post being submitted one more than the ID of the last one. Then the post is uploaded to the database.
I feel like this is bad practice because if 2 people coincidentally submit their post at the same time, their respective posts could be given the same ID.
So, what I'm asking is how should I assign some sort of ID to an object in the database to guarantee it to be unique? Should I assign it in a php script and then somehow return that ID back to Xcode? Sorry, I'm new to this.

You can simply use an auto increment id for your posts, so the database does that job for you.
CREATE TABLE post(
id INT NOT NULL AUTO_INCREMENT,
title VARCHAR(255) NOT NULL,
description VARCHAR(255),
PRIMARY KEY (id)
);
Simply check Auto increment example in the mysql documentation
after adding data to the table you can fetch the last id of the inserted post with the last_insert_id command.
so if you use PHP as programming language and you are using mysqli for the database access, you can use mysqli_insert_id to fetch the last id (see the example in the php.net documentation for better understanding)

Related

how to prevent MySQL primary key from duplication

I am creating user detail table in MySQL where user details are stored when user submits registration form.
In my user table user id field is primary key and auto increment.
My application should be used by many users from many locations. Now there is one scenario when it is possible that two user clicks on submit button at same time from anywhere. My primary key is of integer type and has length of 15, but when two user clicks at same time then which user should get first next id. Or it is possible that none of that get registered and get error.
so what can i do in this case
Your mySQL id field is good, so you should have no problem; however, when inserting a new record, then depending on what your insert SQL query looks like, make sure you leave the id undefined, or use something like:
insert into users values(NULL, "blah", "blah")
-where "NULL" is your first column / field.
This will only work the way you expect if the field (column) in place "NULL" is set (when created, or altered) to AUTO INCREMENT.
If these are set, the record id is incremented on each data entry, no matter if it happens at the same time; new records are always queued to be inserted one after the other.

Safe submitting primary keys

I don't know how to program webpages very well so I have the following question. I have a MySQL database which a user can manage. I have two tables: persons, videos.
I want my page for the user to select a person from the persons table (by name for example) and then associate this person with a video link.
Selecting the person from database is easy,
SELECT personID, name
FROM persons
WHERE name LIKE '%John%'
So now the user has to insert a video link to the videos table which has a foreign key the personID.
I could store the primary key of the person after the "select" in a hidden html input form but I assume this is not very secure as they can edit it?
My question is: Where would you store such a key value in between a select and an insert call?
Is it safer to store all this data in a session instead?
This sort of thing happens quite a lot, and it's completely fine as long as you don't mind people seeing your primary keys (if they're numbers, it shouldn't be anything to worry about).
Let's say you're retrieving a list of rows from a table, and displaying them in HTML. If you want each table row to have a 'delete' button for deleting that row, both from the DOM and in the Database, say via an XMLHttpRequest, it's typical for each row to have an "id" attribute, with the id being the primary key value of the row you wish to delete.
Typically, your primary key will be:
The id field in your table
The field with AUTO_INCREMENT set
In short, give each dropdown a data-id attribute, which you access in your JavaScript via the .data selector. That's good enough. Just make sure you're also protecting yourself from SQL Injection and using PDO and prepared statements, and you'll be fine.
For extra protection, and to make sure nobody has altered the data-id attribute client-side before submit, check that the id corresponds to the name field in the database, and you're golden.
I think storing this type of data in the session is secure and a good choice. After all, it's session-scoped, so there's no reason to output it.
It would be more secure to store it in the session and, ofcourse, easier to access and manage.

How to update two mySQL tables and input primary key from first table into second table?

My first table contains all sorts of info about videos such as: video title, video thumbnail, video category, etc. My second table will store the key points of each video.. So one video may have three key points for example. These fields are added or deleted dynamically using jquery.
I'd like to submit all this information at once, and I'd like to link the videos and their key points using the video's primary key.
Alternatively I could link them using the video's file name or something like that. But it seems sloppy to do it that way.
here is some code:
if (isset($_POST['submit']))
{
$myvideo->addVideo ($sequence, $_FILES['fileName']['name'], $_POST['vidTitle'], $_POST['vidCat'], $_FILES['thumbName']['name']);
} else { echo $myvideo->error; }
}
this method is adding a video to the database.
i will probably introduce a method that adds the key points to the database like so:`
$myvideo->addPoints($keypoint, $minutes, $seconds);
I want this to go inside the same if statement as "addvideo" and I want this to be updated with the primary key from the first insert as a foreign key. how can I accomplish this?`
Check out mysql_insert_id(). It retrieves the most recent insert id of the current connection.
As far as a quick algorithm if all the data were submitted at one time:
Insert your video record
Get the last insert id
Loop over your video meta data and insert those records setting the foreign key from step 2.
If I am understanding correctly, you may want to consider creating a primary key on the video record and then use that as a Foreign Key in the second table. Not 100% certain if this satisfies your wish to do it all at once.
Here is a link to some information on setting Foreign Keys using PHP: http://www.codingforums.com/archive/index.php/t-161945.html

How to create member 'profiles' in PHP?

What is the best way to create member profiles in PHP? For instance, some websites read in the address bar: profile.php?id=11233 and then profile.php?id=13563. How is this actually done? As of now, I am saving such types of URL's in MySQL, but where will I write the actual code? Will I have to write the code in profile.php? Or will I have to make separate files for each id? How does it work?
Will I have to write the code in
profile.php?
Yes. Visitors will be visiting profile.php and there will be a default variable set named $_GET['id'] that has the value in the URL, like 11233 or 13563. You can then query the database for the user with that id and display the proper information.
If there is more than one variable, like profile.php?id=123&type=cake, then you will have two variables: $_GET['id'] = 123, $_GET['type'] = 'cake'. It is stored in $_GET because GET is the method used to access the page. Find out more at http://php.net/get
There is also another common method, called POST. This is used when forms are submitted with method=POST. In that case, the information will be stored in the $_POST array.
Yes, in those example URLs, the database id is being sent as a parameter which would be parsed by PHP.
The basic steps would be
get database id (from what's called the $_GET superglobal in this case). Make sure it's an integer, using intval() or (int)
set up your database connection (I use PDO)
build a query, something like select * from profile where id=?.
execute the SQL query
check your results
if you have valid results, print out the information in the profile
The details of how to do each of those steps is the meat of the matter, of course. I'm sure folks around here would be more than happy to answer questions about how to connect to and set up a database, and use the results in PHP.
A simple example database would be set up something like
CREATE TABLE profile(
id int NOT NULL AUTO_INCREMENT,
user_name varchar(32),
bio varchar(1024),
favorite_flavor enum('chocolate','vanilla','fruity'),
image_id int default null,
primary key(id)
);

I have an issue in mysql that i have a field id which is auto increment and some other fields

I have an issue in mysql that i have a field id which is auto increment and some other fields. where the id field should not be autoincremented while enterting the null values and should be autoincremented while entering values insert values in the same row while giving not null values .
It sounds like you need to generate the value for the id field yourself, in your own code, rather than having the database generate it.
If you create an identity field in the database, the database will create the field automatically. Generally this occurs when the record is saved, whether there are null fields present or not. If you need more control than this, you have to generate the id values yourself.
If you need to know what the next id number is, you can get it with SELECT MAX(id_field);
Robert Harvey's answer tackles the problem but I would also suggest looking at what you are saving and see if there is another approach. Perhaps the null values should be saved in another table? Perhaps the column you have as auto-increment isn't the primary key.
This may not be the direction but in this case it's worth stepping back and re-examining.

Categories