Getting ID of the row as its being written - mysqli - php

Can this be done in a single query? The table has an auto increment field which I need to know the number to fill url field in the table.
Table
id(AI) | title | url
What I am expecting is something like
INSERT INTO table (title,url) VALUES ('name','CONCATENATION OF title AND ID');
I am currently doing this using 2 queries.
1.Writing the fields except URL.
Getting the id using mysqli_insert_id()
2.Updating the above written row.
P.S : The Table has other fields as well so changing the db design isnt really possible in this case.

It can't be done atomically. In theory, you could SELECT MAX(id) + 1 FROM yourtable, but please, please don't - although this is not guaranteed to give you the right result and is definitely not a safe approach.
This seems like bad practice, anyway. Why not concatenate the title and ID when you fetch it? Why must it be concatenated on insert?

I will not comment on the design of your database -- you are the judge of that. Just bear in mind that the following command gets the next auto-increment-ID for the specified table, and that this number could change in an instant if another user accesses the table before your code can use it.
I am using this code myself in a project for a similar reason to your own, and it works for me because the table is updated only a few times per day and never by more than one person at a time.
SELECT Auto_increment FROM information_schema.tables WHERE
table_name = '$name_of_your_table';
To be clear, this code gets the auto-increment ID that will be given to the next table entry for the specified table.

Related

How can I restart my autoincrement in phpmyadmin?

I have some tables in my phpmyadmin with one column that is auto incremented.
The problem is that when I delete some rows from the table (For example the element Car, with index auto incremented 1) and I create another row into the table, the new row have the index 2, but in the table there is only one row.
I want that this second element created to have the index equal to the position of the row, for example, if I have 3 rows that the third element will have the index equals to 3.
I was looking for a method that let me to use my phpMyAdmin like this but I couldn't find anything.
Is it possible? If it is true, what should I have to do? Do I have to create the table again?
This is generally a bad idea. Auto increment is used for creating unique ID of the row. Imagine you have a record "1 - John". Then you delete it and add another "1 - Jack". From the point of common database logic, it will seem that John was renamed to Jack (it has the same ID = it is the same entity) rather than it is another record. You should let DB assign new ID to each new record, even with leaving gaps after deleted records.
If you really want to do so, you can modify auto increment value using this query:
ALTER TABLE users AUTO_INCREMENT=123
but it is still not the way auto increment is designed for.
It is possible, but you shouldn't do that on production.
The SQL query is:
ALTER TABLE tablename AUTO_INCREMENT = 1
The most important part of this is to prevent overriding. For example you have an user and this user has id of 81 and if you delete this user and the database doesn't remember that this id 81 has ever been taken by an user (and for example, you have some relations - like friend lists) the user that is going to have the same ID will probably have the same data.
So basically, you don't want to reset auto increment values.
Execute this SQL sentence:
ALTER TABLE tablename AUTO_INCREMENT = 1
I struggled with this a bit too, then found in the "Operations" tab, there is a setting under "Auto Increment" where you can set the number it will start from, so you can roll it back if you want to do that.
It is possible. It is not a feature of phpmyadmin, but of mysql. Execute this
ALTER TABLE tablename AUTO_INCREMENT = 1
More info on this on stackoverflow
And in the mysql reference

How do i set the increment value of autoincrement in mysql

I am trying to develop a system to assign room numbers to tenants of a hostel upon registration, using the auto increment feature of sql.
However, it automatically increases by one after every entry. Because the hostel accommodates four people in one room, I want to change this to 4, so that after every 4 entries I get only one id/room number.
How do I go about this? I am using php and sql. If the autoincrement feature is not possible can you please suggest another way to achieve this? Thanks.
You would need:
http://dev.mysql.com/doc/refman/5.1/en/replication-options-master.html#sysvar_auto_increment_increment
It works like this:
mysql> SET ##auto_increment_increment=4;
So when you insert 4 rows, the auto increment column will be:
4,8,12,16
as best of my knowledge you cannot change the steps of auto-increment field. I suggest add another field and write a trigger to update its value based on auto-increment field (auto-increment/4).
I don't think this is possible with autoincrement..
Maybe you can do something like this:
//Pseudo code
//First you get the count of the highest id, to see how many users are in the last room.
SELECT COUNT(*) FROM table WHERE id=(SELECT id FROM table ORDER BY id DESC LIMIT 1)
//If the result of the last query is >= 4 then insert the next customer with id +1
Don't use auto_increment for this - it can't handle a situation where multiple records will share the same number and although you can reset it manually (see below) it's also not designed for a situation where numbers may get reused in a random order.
You could just have a room_number field with one of the mysql integer types (e.g. tinyint, smallint, mediumint…) or you could separate your database into two tables, one for people (each of whom have an id) and a second to map those ids to rooms.
However you do it, you'd then write a select query to check which room numbers are available before you add the person's details to the database.
You may need to read up on relational databases if that doesn't sound very clear.
If you do need to reset the auto_increment (sometimes it's nice to do it if you've filled a database with test data which you're about to wipe, and you want the real "production" data to begin at 1) you can use:
ALTER TABLE [tablename] AUTO_INCREMENT = 1
https://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html

Find the size of an SQL column with PHP?

I'm trying to build a very simple login system for my site (just for practice for a project i'm working on). The way I've decided to implement it is use a table with fields for ID, Name, Password, and username and search for the entered information in the existing table.
For registration, it simply injects the information supplied into the table, and I would like to assign a customer ID number. My idea for assigning an ID number is to simply find the size of the ID column (which will contain the ID's 1,2,3..etc up to the end) and assign the new registration to the length +1. For this purpose i'll need a way to get the size of the column, but I'm just learning php and sql so i'm not sure what the syntax would be.
TLDR; is there a funtion in sql that I can use in php to get the length of a particular column? (i.e the number of entries stored in that column?)
Set the ID column to Primary and Auto increment.
you don't include that in your query it is created on its own.
You'd probably be better off just using an IDENTITY or AUTO_INCREMENT column. The problem with checking for the "size of the column" (by which I assume you mean the count of rows in that column) is that you could end up inserting duplicate IDs, for example:
ID | ...
---------
1
2
4
So if you did a SELECT COUNT(ID)+1 FROM MyTable, it would return 4, and you have an ID collision.
You could do something like SELECT MAX(ID)+1 FROM MyTable, but even then there could be concurrency problems (process A and process B both try to run that query at the same time, before either has a chance to insert the new ID of 5). You're really best off just letting your RDBMS take care of it..

PHP/MySQL how can I select a value from a MySQL database?

I was wondering how can I select a value from a database that a user just entered it into and then add it to another mysql table all in the same script before the script is finished running.
You're probably looking for an insert ... select statement.
If you're talking about adding a value that a user just entered into a form, to something, and then putting that into the database, you should do the addition while in PHP. There's no point in going to the database after you've just inserted the value for this purpose.
If I'm misunderstanding something, please elaborate your question and let us know WHY you would want to figure out a just-inserted database value and do an operation on it, rather than trying to do it before you insert in the first place.
Also, if it's a fairly simple modification consider using an UPDATE statement, not a select --> insert.
Like nash said, you perform a select.
But to get the data from the row that the user just entered, you'll need:
mysql_insert_id()
Which grabs the last ID inserted (this is assuming you have an increment id column)
So assuming just entered his first and last name in a form, you'd insert his first and last name in the database(which i assume you know how since the title of this question is "SELECT a value from MySQL database"), you can get what he just entered by:
$last_id = mysql_insert_id();
If there are no rows on that table yet, then this will return 1. $last_id is now 1 (one).
To select:
SELECT * FROM users WHERE userID = "$last_id"
this will grab what the user just inserted....however, this seems pointless as you can use the variables from the form he just filled
enter code here
In the PHP MySQL module, you normally perform a mysql_select_db() to switch database.
You can insert your data into tables in different databases by switching between them with that function.
However, you can insert data into any table of any database (which the user has access to) by prefixing the database name to the table like so:
INSERT INTO test_db.test_table (`column1`,`column2`) VALUES ('abc',123);
You can use that also to insert data from one table into another using:
INSERT INTO `db1`.`myTable` (`column1`,`column2`) SELECT `column1`,`column2` FROM `db2`.`myTable` WHERE `id`= 5
The WHERE id part should obviously match the id of a row in db2.myTable
If you use doctrine you have the inserted data in the object representing the table and in addition you have primary key assigned for the record inside the object.
Con is doctrine is huge database abstraction layer, so if your application is not big doctrine is hammer for mosquito.
what is the structure of your database? The names of your tables, columns?
Some tutorial that you may want to look at: (grabbed from google)
http://www.phpf1.com/tutorial/php-mysql-tutorial.html
In theory you perform a select, take the data you need and perform an insert.

splitting data into multiple tables

I am building a employees page.
Some of the information goes into an 'employees' table but some of it goes into a 'availability' table that is referenced to the 'employee' table:
availability:
id / employeeid (unique id from employees table) / monday available / and on and on /
So I don't have that unique ID from the employees table until I create them.
Is it fine to do a query where I set the employee info and then a query to get the last created row in the employee table and then use the unique id from that to set the availability...
Or is that messy and should I have a create employee page and THEN a set availability page?
So basically I want to know if it is cleaner and 'better' coding to separate the two functions?
Adding to #Quassnoi's answer:
You would add the employee record, then use the MySQL LAST_INSERT_ID() function to find the autoincremented unique id for the employee record you added. You can then feed that value back into the availability INSERT statement.
More details are on the MySQL manual page at http://dev.mysql.com/doc/refman/5.1/en/example-auto-increment.html
It's important that you not use a SELECT statement (e.g. SELECT MAX(employee.id)) since there might be other uses adding records as well. LAST_INSERT_ID() is specific to your connection
Of course create employee first, availability then.
If your tables are InnoDB, you can do it in a transaction so that you can rollback the whole update if something goes wrong.
Is it fine to do a query where I set
the employee info and then a query to
get the last created row in the
employee table and then use the unique
id from that to set the
availability...
Yes, that sounds OK. If you use an autoincrement column for employeeid, you can then use mysql_insert_id() or equivalent to retrieve that last inserted id safely. Don't do SELECT MAX(employeeid) FROM ...., because you might get problems when loads of people are using it concurrently.
You can easily get the last insered record via
mysql_insert_id()
After that, you can insert an availability record for the desired employee.
Note: I would choose a framework that takes care of these issues, like Symfony or Cake.
Using the "last created row" may not always work the way that you're expecting and may complicate things in the future if there's growth or if another programmer assumes the project. If I understand what you're looking for, you should instead have 3 tables. One table for employees, one table for availability, and a third table should be used to store unique records for the association. In the association table each row will have columns for : a unique ID, the employee id, the availability id.

Categories