Add a unique key to database - php

I've got a form on my website for users to input their fname, sname, company,phone,email which then gets updated to a database on submit. I also have a field in my database for a unique userID to incase users have same name and company ect. When submitting my form how is it possible to add in this field, a unique number so that it is +1 from the fields taken already. At the minute there are only 3 userIDs so i need the next inputted one to be 4 and so on.
At the moment I have this.
require_once('dbConnect.php');
//taken from a smarty template form.
$addForename = $_POST['forename'];
$addSurname = $_POST['surname'];
$addCompany = $_POST['company'];
$addContact = $_POST['contact'];
$addEmail = $_POST['email'];
public function addUser($addForename,$addSurname,$addCompany,$addContact,$addEmail)
{
$sql = "INSERT INTO `Users` (`Forename`, `Surname`, `ComanyName`, `Phone`, `Email`) VALUES ('".$addForename."','".$addSurname."','".$addCompany."','".$addContact."','".$addEmail."')";
$databaseAccess = new DatabaseConnect();
try
{
$result = $databaseAccess->connect($sql, "add");
}
catch (Exception $e)
{
throw new Exception("Adding User Failed !!!");
}
if ($result)
{
return 1;
}
else{return 0;}
}
thanks

If you are using phpmyadmin there should be a checkbox when youre creating a new column with "A_I" or Auto_Increment.. you have to check that and then it will count your entrys.

Create the row as an auto_increment in the database:
create table someName (ID int primary key auto_increment, col1 int ...);
Then when you are inserting data, either pass it a null, or don't insert that field like this:
insert into someName (col1) values (3);
or
insert into someName (ID, col1) values (null, 3);
You can modify your current table with the following:
ALTER TABLE someName MODIFY COLUMN ID INT NOT NULL AUTO_INCREMENT , ADD PRIMARY KEY (ID);

create the ID:
ALTER TABLE users ADD ID INT UNSIGNED
NOT NULL AUTO_INCREMENT, ADD PRIMARY KEY (ID);
and start the auto-increment where you want
ALTER TABLE tbl AUTO_INCREMENT = 4;

Create a column set it as a primary key and auto increment. You can even write a stored procedure for inserting in the table. That way you don't have to write query every time and not have to worry about escape characters. If you want the particular no to be returned from stored procedure use SCOPE_IDENTITY() in the stored procedure.

Related

How to populate the child table with foreign key - MySql

I am working on MySQL database. I am new to it that is why I am facing a problem. The problem is populating the child table with foreign key which is referencing to the parent table. I have two tables employee which contains following columns
id as a primary key,
first_name
last_name
birth_date
and a borrowed table which contains following columns
ref as a primary key
employId as a foreign key
book
The employeeId is referencing the primary key id of the employee table. So simply it means the one employee with same id can borrow multiple books. When I insert some data into the employee table It get inserted, but when I have to insert data into the borrowed table, I have to manually insert the value in employeeId column. Isn't it supposed to be populated automatically. or I am misunderstanding the concept of the foreign key.
My SQL Code
$uname = "root";
$pass = "";
$sname ="localhost";
$db ="nady";
//Making database connection
$con = mysqli_connect($sname,$uname,$pass,$db);
$t1 = "CREATE TABLE IF NOT EXISTS employee (
id smallint(5) unsigned AUTO_INCREMENT NOT NULL,
firstname varchar(30),
lastname varchar(30),
birthdate date,
PRIMARY KEY (id)
) ENGINE=InnoDB";
$con->query($t1);
$t2 = "CREATE TABLE IF NOT EXISTS borrowed (
ref int(10) unsigned NOT NULL auto_increment,
employeeid smallint(5) unsigned NOT NULL,
book varchar(50),
PRIMARY KEY (ref),
FOREIGN KEY (employeeid) REFERENCES employee(id) ON UPDATE CASCADE ON DELETE CASCADE
) ENGINE=InnoDB";
$con->query($t2);
if(!$con->query($t2)){
echo $con->error;
}
$i1 = "INSERT INTO employee VALUES(NULL,\"Nadeem\",\"Ahmad\",22)";
$con->query($i1);
$i2 = "INSERT INTO borrowed VALUES(NULL,1,\"Ahmad\")";
$con->query($i2);
if(!$con->query($i2)){
echo $con->error;
}
Simple what I need is ; For example an employee with id 1. Who borrowed 3 books. So in the borrowed table the employeeId column will have three rows with values 1 and different books name. My point is how would I populate the employeeId column when I am inserting the data into it. Let say, John have have borrowed three books and have id 1 then how would I insert data to borrowed table with employeeId of john. I need the query for it. and also query to retrieve the books borrowed by john.
The foreign key is used to link two tables, indicating that the field in a column
(employId from borrowed, in your case) refers to the PRIMARY KEY of another table (id from employee).
When you're inserting a new line in borrowed, you have to indicate the user that is taking that book, to insert it in that line. You have to know the user that is doing it. If you have foreign key, you need the id of that user, which is supposed to be his unique identifier. To insert that John has taken a book, you need to know that John's id is 1.
If the user is already in your employee table and you know his first and last name, you can get the id with a simple select...
SELECT id FROM employee WHERE first_name='John' AND last_name='Smith'
... and then you can do the insert with the id obtained.
If it's new user, you need to add the user first to employee, then get the new id and then insert the new line in borrowed, to do this without having to re-query to employee table to get the new id, you can use the PHP mysqli::$insert_id/mysqli_insert_id function, that gives you the PRIMARY key of the last query. For example...
$con->query("INSERT INTO employee (first_name,last_name) VALUES ('Mark','Whatever')");
$newemployeeid = $con->insert_id;
$con->query("INSERT INTO borrowed (employeeid,book) VALUES (".$newemployeeid.",'Awesome Book Title')");
I hope it helps
Your just need change these lines
$employee_id = $con->insert_id;
$i2 = "INSERT INTO borrowed VALUES(NULL,".$employee_id.",\"Ahmad\")"
first you get last insert id as $employee_id through a inser_id mysql predefined function then you add this $employee_id in borrowed table inserted query.
You can also use the MySQL-function LAST_INSERT_ID(). This function fetches the id from any previous INSERT statement, in the OPs case after inserting a new employee into employee table.
So the INSERT statement can be shortened to this:
INSERT INTO borrowed (employeeid, book) VALUES(LAST_INSERT_ID(),'Ahmad')";
Also note, that it is not required (and probably not even allowed) to fill the column 'ref' since it has AUTO_INCREMENT.
Here's the link to MySQL's documentation/function reference about LAST_INSERT_ID().

In a 1-1 relationship, why is my insert inserting two records in two tables?

I'm having trouble, as title says, when I INSERT a record in a table that has got a 1-1 relationship with another.
First things first, the SQL code that generates the tables:
DROP TABLE IF EXISTS Facebook_Info;
DROP TABLE IF EXISTS Conversations;
CREATE TABLE IF NOT EXISTS Conversations(
c_id INT AUTO_INCREMENT NOT NULL,
c_start TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
channel ENUM('desktop', 'facebook'),
u_name VARCHAR(20) DEFAULT NULL,
u_email VARCHAR(50) DEFAULT NULL,
PRIMARY KEY(c_id)
);
CREATE TABLE IF NOT EXISTS Facebook_Info (
c_id INT AUTO_INCREMENT NOT NULL,
f_id INT(12) NOT NULL,
PRIMARY KEY(c_id),
FOREIGN KEY(c_id) REFERENCES Conversations(c_id)
);
I assure you this code works: I tested it. I hope this is the best way to provide a 1-1 relationship between Conversations and Facebook_Info.
In any case, now I can introduce you my nightmare: I'm trying to insert a new record in Conversations via PHP (procedural style).
public function create_new_id_conv($channel = 1) {
$w_ch = '';
if ($channel == 2) {
$w_ch = 'facebook';
} else {
$w_ch = 'desktop';
}
$query = "INSERT INTO Conversations (c_id, c_start, channel) VALUES (NULL, CURRENT_TIMESTAMP,'$w_ch')";
$conn = mysqli_connect("localhost", Wrapper::DB_AGENT, Wrapper::DB_PSW, Wrapper::DB_NAME);
$res = mysqli_query($conn, $query);
$id_conv= mysqli_insert_id($conn);
mysqli_free_result($res);
return $id_conv;
}
The Wrapper:: * variables are all set well, in fact, an INSERT operation is done, but not only one! I'm having this situation after I call this function:
This is the content of Conversations table:
And here's the content of Facebook_Info:
What's happening?
I searched and searched...
Then I started to think about what I'm getting here: 2147483647. What represents this number? What's that? Seems like a big number!
And what if my script and my queries were correct but the mistake is the skeleton of my tables?
I must register a 14 digit integer, that is too large for the INT type.
So using BIGINT to store the f_id field made all correct and working!
Hope my mistake helps someone!

Use a variable as table name when creating a table in mysql

I have variable whos value is a random number between 0 and 1000, I would like to use this as the name when creating a new table. I have tried to do this by concatenating my sql with the variable that stores the random number, this hasn't worked, is there a way of doing this? Thanks
include 'includes/db_connect_ssg.php';
if (isset($_POST['new_user_name'])&&isset($_POST['new_user_password'])) {
$username = $_POST['new_user_name'];
$password = $_POST['new_user_password'];
$randID = rand(0,1000);
$sql = "INSERT INTO `Users`(`id`, `username`, `password`, `admin`, `href`) VALUES ('$randID','$username','$password','0','ssgprofile.php?id=$randID')";
$query = mysqli_query($dbc, $sql);
$id = (string)$randID;
$q = "CREATE TABLE CONCAT('userTable_',$id) (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";
$qquery = mysqli_query($dbc, $q);
if ($query&&$qquery) {
include 'admin_loadUsers.php';
}else{
echo "Could not connect sorry please try again later, for more info please contact BB Smithy at 0838100085";
}
}
You could just use:
$q = "CREATE TABLE `userTable_".$id."` (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";
But beware, creating a table with name containing a number is nearly always a sign of bad database design.
Instead of creating many tables with just one row, simply add columns firstname, lastname, email and reg_date to your table Users. Also your way of generating user ID by calling rand(0,1000) will result in collisions (rand will return a value which is already used as an ID in Users table). Use AUTO_INCREMENT for generating user IDs.
You do not have a valid table name
From the Mysql docs:
Identifiers may begin with a digit but unless quoted may not consist solely of digits

update then replace dies

If there is a row for user_id then I want to update, if not insert (but I was told to use replace). In the table there is id (which is primary key, auto inc) and user_id (index, session relates to). I have a form that when the data is changed it should be changed in the database for that particular user in session, otherwise it is just added for that particular user in session
if (empty($err)) {
$thesis_Name = mysql_real_escape_string($_POST['thesis_Name']);
$abstract = mysql_real_escape_string($_POST['abstract']);
$query="UPDATE thesis SET thesis_Name ='$thesis_Name',
abstract='$abstract' WHERE id='$_SESSION[user_id]'
IF ROW_COUNT()=0
REPLACE INTO thesis (thesis_Name,abstract)VALUES ('$thesis_Name', '$abstract')
";
mysql_query($query) or die();
// query is ok?
if (mysql_query($the_query, $link) ){
// redirect to user profile
header('Location: myaccount.php?id=' . $user_id);
}
With this the page just dies.
EDIT:
`thesis` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`thesis_Name` varchar(200) NOT NULL,
`abstract` varchar(200) NOT NULL,
PRIMARY KEY (`id`),
KEY `user_id` (`user_id`)
)
Thanks so much
You don't need to do the UPDATE first - REPLACE handles all of this for you. From the MySQL manual:
REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted. See Section 13.2.5, “INSERT Syntax”.
Therefore, so long as id is a unique key in your thesis table, the only SQL you need is:
REPLACE INTO thesis (id, thesis_Name, abstract)
VALUES ('$_SESSION[userid]', '$thesis_name', '$abstract');
There are a few things in your code that pose problem. First you don't have to do an insert and a replace in the same query : replace will insert if there is no row to replace (besides, I'm not even sure the sql syntax you're using is correct)...
Then you do a mysql_query($query) or die() which is probably where your code dies (maybe due to the fact that the sql syntax you used could be incorrect).
Right after that, you do a mysql_query again, which would reexecute the query a second time. Anyway, if your query didn't work, your code would have died on the previous line...
What you could do would be
$query = "REPLACE INTO blablabla";
if (!mysql_query($query))
echo "the query failed";
else header ("location:blabla");
but your query should mention for which user_id you want to update like this
REPLACE INTO thesis (id, thesis_Name, abstract)
VALUES ('{$_SESSION[userid]}', '$thesis_name', '$abstract');
INSERT
INTO thesis (id, abstract, thesis)
VALUES ('$_SESSION[user_id]', '$abstract', '$thesis_Name')
ON DUPLICATE KEY
UPDATE
abstract = VALUES(abstract),
thesis_Name = VALUES(thesis_Name)
You can do it with prepared statements.You can see an example sql ;
DROP PROCEDURE IF EXISTS `UPDATETHESIS`
|
CREATE PROCEDURE `UPDATETHESIS` (IN _id VARCHAR(50), IN _thesis_name VARCHAR(50), IN _abstract VARCHAR(50))
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY INVOKER
IF EXISTS (SELECT * FROM thesis WHERE id = _id)
BEGIN
UPDATE thesis SET thesis_Name = _thesis_name,
abstract = _abstract WHERE id = _id
END
ELSE
BEGIN
INSERT INTO thesis (thesis_Name,abstract) VALUES (_thesis_name, _abstract)
END
You can call this like CALL UPDATETHESIS(userid, thesis_name, abstratc);

counting the number of updates to a row in my mysql table

I have a simple mysql DB and use this PHP code to update it.
mysql_query("REPLACE INTO `$db_table` (username, live, datetime, ip)
VALUES ('$username', '1', '$timeofentry', '$ip')");
I use REPLACE INTO along with a primary key on "username" to let users bump themselves to the top of the most recent list...
I would like to add a bump count. The number of times an entry has been updated (or "replaced into").
How would I go about doing this?
Thanks a lot!
You can use INSERT ... ON DUPLICATE KEY UPDATE which performs an actual update of existing rows.
$mysql = mysql_connect(..
...
$username = mysql_real_escape_string(...
$ip = mysql_real_escape_string(...
...
$query = "
INSERT INTO
`$db_table`
(username, live, datetime, ip)
VALUES
(
'$username',
'1',
'$timeofentry',
'$ip'
)
ON DUPLICATE KEY UPDATE
ip = '$ip',
bumpCount = bumpCount + 1
";
$result = mysql_query($query, $mysql);
First, you need to add another column to your table to keep the count.
Second, you should probably use the UPDATE statement instead of REPLACE.
REPLACE will actually delete the row, then INSERT a new one which isn't very efficient.
UPDATE `$db_table` SET datetime = NOW(), ip = '$IP',
bumpCount = bumpCount + 1 WHERE username = '$username' LIMIT 1;
#dot
You'd define your bumpCount field as another column in the table. I'd recommend setting it to a default value as well.
Then your table definition would be sometime like:
CREATE TABLE my_table
(username varchar(255) not null primary key,
live int,
datetime datetime not null,
ip varchar(15) not null,
bumpCount int unsigned not null default 1);
And your insert/update would be something like:
INSERT INTO my_table (username,live,datetime,ip)
VALUES
('$username',1,now(),'$ip')
ON DUPLICATE KEY UPDATE datetime=now() ip='$ip', bumpCount=bumpCount + 1;

Categories