Get unique id of row just inserted into database - php

I have a form that submits super basic information, just a new name (the name gets assigned a unique id). What I am trying to make happen is when the user submits the name it gets submitted into the database and they get redirected to a new page card.php where they can add more specific information. However the unique id associated with the row that was just submitted needs to follow in the URL (id=$id)
$query = "INSERT INTO name VALUES(NULL, '$name')";
mysqli_query($conn, $query);
$query2 = "SELECT * FROM name ORDER BY id DESC LIMIT 1";
$result = mysqli_query($conn, $query2);
while($row = mysqli_fetch_array($result)) {
$id = $row['id'];
}
header("Location: http://localhost/card.php?id=$id");
Process
addName.php -> user submits new name -> add to database -> redirect to card.php WITH unique id value of name that is just submitted
1.) Is there a way to retain the id of the row just submitted? In the fluke chance 2 or more people submit at the same time the second query of getting the last row inserted into the database will return the wrong row id
2). Having a while loop return 1 piece of info seems like a shitty way to do things, this might be the most basic of shit but i cant seem to return the 1 piece of data without doing this

Try using mysqli_insert_id which returns the AUTO_INCREMENT ID generated from the previous INSERT operation.
$query = "INSERT INTO name VALUES(NULL, '$name')";
mysqli_query($conn, $query);
$id = mysqli_insert_id();
header("Location: http://localhost/card.php?id=$id");
Reference: http://us1.php.net/manual/en/function.mysql-insert-id.php

You could use the mysqli function to retrieve the last inserted id (check mysqli_insert_id as suggested in a comment), but I wouldn't recommend you using the user id in the URL, people can try to get in, using other ids
also you can use the php function to generate a custom is check out: uniqid

Related

Like system In Php

Hey I want to create like system in php But I am facing some problem on it ...
How can I create Like system that allow only one like per one user??
This is my code
<?php
if(isset($_POST['like'])){
$q = "SELECT * FROM likes WHERE `username` = '".$_SESSION['recieveruser']."'";
$r = mysqli_query($con, $q);
$count = mysqli_num_rows($r);
if ($count == "0") {
$q1 = "INSERT INTO likes (`username`, `likecount`)VALUES('".$_SESSION['recieveruser']."', '1')";
$result1 = mysqli_query($con, $q1);
} else {
while($row = mysqli_fetch_array($r)) {
$liked = $row['likecount'];
}
$likeus = ++$liked;
$q2 = "UPDATE likes SET likecount='".$likeus."' WHERE username = '".$_SESSION['recieveruser']."'";
$result2 = mysqli_query($con, $q2);
}
}
give me some suggestions
I want only one like per user
In this code every user can give Many likes to another user but I want only one like per one user and I want to display the name of the user who gave like if it's possible
This is only user like code...
I created simliar like system on my website. In my likes table, I had these columns:
Id of comment, that has been liked
Id of user who liked
Id of like (for removal)
When user clicked like, I inserted new row into likes table, with two known values. ID of like was autoincremented.
To show number of likes, I filtered by id of comment and grouped by users id (just to be sure). The number was obtained using count.
select count(*) from likes where comment_id = 666 group by user_id;
Even if you let user insert multiple times, the like counts only as one. But best would be to check, if current user already liked and dont let him do that. For this task, insert on duplicate key update could be used, to spare if exists db request (select).
You should not use the code you posted above. First of all, your code is vulnerable to SQL-Injections and therefore you should use Prepared Statements (https://www.php.net/manual/de/mysqli.quickstart.prepared-statements.php). Second, $_SESSION variables are depricated (https://www.php.net/manual/en/reserved.variables.session.php).
Lets assume you want users only to be able to like a post once. Then, instead of the column likecount you would need a post-id which uniquely identifies the post.
Define the combination post-id and username as a primary key in your database.
Now your code just have to check whether you find the username with the according post-id in the table likes.
In case you do not find the username with the according post-id in the table, you have to INSERT the username and the post-id

PHP function doesn't increment int as it should

On my XAMPP server I have a database table on phpMyAdmin. In that table, I have a few columns, and one of them is id column (Integer).
I want to get the latest added item's ID, increment it by one and then assign it to a new item that the function adds to the table.
The problem is that whenever there is a new item, it is automatically assigned with 1 as id, nothing above 1.
$sql = "SELECT * FROM items";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
if( $_SESSION["increment"] == "yes"){
$_SESSION["id"] = $row["id"];
}else
$_SESSION["id"]=$_SESSION["id"]+1;
}
} else {
$_SESSION["id"] = 1;
}
This will give you last increment Id.
$sql = "SELECT id FROM items order by id DESC LIMIT 0,1";
Then you dont want have a while loop to find last increment Id.
error reporting said what? and mysqli_error($conn)?
-- Fred-ii-
The above request by Fred -ii- sums it up, if your ->num_rows is returning zero or not a number (false) then you have an SQL error, so you need to check your error logs, and check your database connection.
Have you started your session with session_start?
Do you intend that the first else calls without brackets, only executing the single following line, $_SESSION["id"]=$_SESSION["id"]+1; ?
It seems to me that you need well known AUTO_INCREMENT functionality built inside MySQL database. Just define in your database schema for your table that column is AUTO_INCREMENT column type, and it will be automatically incremented by 1 upon each new insert into table.

Getting Auto Increment multiple times

I'm hoping someone can help me figure out what I thought would be really easy.
I have a form that I dynamically add rows to. When I add the row, I want to display a unique value, and am using the MySql table primary key - called ID. Because there will be multiple users, I want to immediately reserve that ID, so it doesn't get reused. Since a user may decide to add another item to the list, and add another dynamic row, I want to repeat the process (get the new Auto Increment value from that table, and immediately reserve it).
Unfortunately, I continue to get the same ID value, even though I have confirmed the auto increment value has increased.
This is what I am using inside my "add row" function before I use the DOM Element to add the row:
$result = mysql_query("SHOW TABLE STATUS LIKE 'table'");
$row = mysql_fetch_array($result);
$nextId = $row['Auto_increment'];
$query = "INSERT INTO table (id, identifier1, identifier2) VALUES ('".$nextId."','".$identifier1."','".$identifier2."')";
$result = mysql_query($query) or die(mysql_error());
I have tried adding immediately before them the following in the hopes that it will blank everything and pull all new values:
$nextId = 0;
$row = "";
$result = "";
$query = "";
I am hoping someone out there can see something simple or suggest a better way that will work.
Thanks in advance.
Ok as your comment shows you have a slight mistake in your INSERT, try this:
$query = "INSERT INTO table (identifier1, identifier2)
VALUES ('".$identifier1."','".$identifier2."')";
$result = mysql_query($query) or die(mysql_error());
$nextId = mysql_insert_id()+1; //you also need to +1 to get the next number
But there is NO guarentee that the next id will be +1 from the last.

Show data from a specific row in MySQL

I'm building a simple bug tracking tool.
When you create a new project, all the info you fill in in the form, gets stored in the database.
When you create the new project you get redirected to a unique project page.
On top of the page it shows the name of the project, but it's not the name of the project I just created, it always shows the name of the first project in the MySQL table.
How can I show the name of the project I just created?
With this query I retrieve the data from the database.
$query = "SELECT CONCAT(name)
AS name FROM projects";
$result = #mysql_query ($query)
With this I show the project name, but it always shows the name of the first record in the table.
<?php
if ($row = mysql_fetch_array ($result))
echo '<h5>' . $row['name'] . '</h5>';
?>
It isn't yet SQL Injection prove and is far from complete... But I'm really struggling with this problem.
You need an AUTO_INCREMENT field on your table for a unique identifier (at least, you really should). Then you can do something like this:
<?php
$sql = new MySQLi('localhost', 'root', '', 'database');
$sql->query('INSERT INTO `projects` (`name`) VALUES ("Test Project");');
$projectID = $sql->insert_id; // Returns the auto_increment field value of the last insert query performed
// So this assumes you have a field in your table called "id" in this example
$res = $sql->query('SELECT CONCAT(`name`) AS `name` FROM `projects` WHERE `id` = '.$projectID.';');
if ($row = $res->fetch_assoc()) {
echo '<h5>'.$row['name'].'</h5>';
}
?>
Since you were calling for a redirect to the unique project page, you should have something like this: header("Location: project.php?id=$projectID");
Then, on project.php, you can attempt to fetch the project with the query above, only your query's WHERE clause should be something like:
'`id` = '.intval($_GET['id']).';'
Technically, you could pass all the project info along to the next page as a request or a session cookie and save yourself a query altogether. Just make sure you keep the id handy so it's easy to update the record.
Try using ORDER BY.
$query = "SELECT CONCAT(name)
AS name FROM projects ORDER BY id DESC";
This would show the most recent project (assuming you have an ID column).
However, a much better way is to have an ID variable on the page.
$query = "SELECT CONCAT(name)
AS name FROM projects WHERE id=?";

Unique entry verification using MySQL and PHP

I need to verify that a user registering for a website enters a unique 16 digit number that no one else prior to him/her has entered.
The relevant database information is that the 16 digit numbers are stored in a column called card1, the name of the entire table is users, and the user-entered number is stored in $card1.
Here is what I have so far...
$query2 = "SELECT card1 FROM users WHERE card1='$card1' LIMIT 1";
$result2 = smart_mysql_query($query2);
if (mysql_num_rows($result2) != 0)
{
header ("Location: register.php?msg=exists");
exit();
}
The idea is that it will find any examples already in the database and if it finds a duplicate, it will display and error message.
The problem is that it is continuing to allow users to register(submit their registration form to the db) even when there is a duplicate. Immediately after this block of code is the insertion call to the db with all of the user information collected from the form.
NOTE: I'm not very familiar with handling PHP error messages and what I've used is just an example that I found in another instance in the example code.
Make the if statement like this:
$query2 = "SELECT * FROM users WHERE card1='$card1'";
$result2 = mysql_query($query2);
if ($result2 !== false)
{
header ("Location: register.php?msg=exists");
exit();
}
Should fix the problem:)
The correct way to do this is to add a unique index on the field that holds the number that the use has entered (card1).
You will then try and INSERT the new row without trying to SELECT it first, and if this operation fails you redirect the user to the msg=exists page. This lets the database handle the duplicate detection and removes the problem inherent in your method - if two users submit the same number at the same time, there is no guarantee that SELECT -> INSERT will detect it. A unique index will detect and prevent this.
This will also have the advantage of reducing database traffic, since only one query is executed in order to get this happen.
First of all, create unique index in DB on this column.
This is best practice:
ALTER TABLE `users`
ADD UNIQUE INDEX `card1` (`card1`);
I should modify your SQL as follows:
$query2 = "SELECT COUNT(1) FROM users WHERE card1='$card1'";
$res = mysql_query($query2);
$data = mysql_fetch_array($res);
if ($data == 1)
{
header ("Location: register.php?msg=exists");
exit();
}
It will check for existence of row within table and return 0 or 1.
If exists (1) then it will redirect you.
try this one
$query2 = "SELECT card1 FROM users WHERE card1='".$card1."' LIMIT 1";
$result2 = mysql_query($query2);
if (mysql_num_rows($result2) > 0)
{
header ("Location: register.php?msg=exists");
exit();
}

Categories