Unique entry verification using MySQL and PHP - 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();
}

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.

SQLiteResult::numColumns returning 1 when the database is empty (PHP)

I'll start this by saying that I am very new to SQLite (this is basically my first time properly trying it out), but I am familiar with SQL via MySQL and have used that plenty.
I have verified that my SQLite 3 database is working using a program called "DB Browser For SQLite". Right now it's empty, and I'm testing a user sign up system. I'm trying to do a check where I take the e-mail and username provided and check them against the database to confirm they haven't already been used by counting the returned rows. Seeing as my database is empty at the moment, I would expect a result of 0 regardless of what I submit, but I keep getting a result of 1.
$db = new SQLite3('database.db');
$email = SQLite3::escapeString($_POST['email']);
$username = SQLite3::escapeString($_POST['username']);
// check if email already exists
$email_query = $db->query("SELECT email FROM users WHERE email='$email' LIMIT 1;");
$email_exists = $email_query->numColumns();
// check if username already exists
$username_query = $db->query("SELECT username FROM users WHERE username='$username' LIMIT 1;");
$username_exists = $username_query->numColumns();
When I run those queries in "DB Browser For SQLite", I get the expected results. I'm not getting any PHP errors either. My one theory is that the 1 that is being returned by numColumns() is actually error code 1, but when I use SQLite3::lastErrorCode(), I get 0, meaning no errors. I'm lost...would really love some insight here!
The number of columns is just the number of fields you requested. If you had done SELECT username, email ... it would have returned 2 because you selected 2 columns.
If you want to know if there are any matches, you should count the number of rows, not columns. But the SQLite3 extension doesn't provide a numRows method. You could change your query so you do:
SELECT COUNT(*) AS count FROM users WHERE email = '$email'
and then see whether $row['count'] is greater than 0. Or you could use your existing query and try to fetch the result.
$email_exists = !empty($email_query->fetchArray());
When there are no rows, numColumns() will return 1. The solution, is to do this:
if ($username_query->numColumns() && $username_query->columnType(0) != SQLITE3_NULL) {
// Rows exist
} else {
// No data
}
Credit goes to Jon Scully.
Other comments suggest though that columnType may always return SQLITE3_NULL, and to instead do this to determine if there are rows:
if ($result->fetchArray()[0] == null) {
// No rows
}
$email_query = $db->query("SELECT email FROM users WHERE email='$email' LIMIT 1;");
if($email_query->fetchArray(SQLITE3_ASSOC)){
//email exists
}

Get unique id of row just inserted into database

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

mySQL fetch column based on another column in PHP

I'm trying to write my first PHP script with mySQL and I desperately need some help. I'm sure this is relatively simple, but if I have one field in my table (username, for example), and I want to fetch another field (name, for example), that is in the same row as the given username, how do I do that?
Again, I'm sure this is easy, but I'm lost, so I'd really appreciate any help. Thanks!
$sql = "SELECT username, name FROM table";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)) {
echo "This {$row['username']} has the name {$row['name']}\n";
}
halfdan's answer sort of works, but it fetches all rows and displays them. What you want is a WHERE clause, which lets you filter the contents of the table so the query only returns the row(s) you want:
SELECT username, name
FROM sometable
WHERE (username = 'johndoe');
This will return only the rows where the username field is equal to 'johndoe'. Conceptually, it's equivalent to:
$results = mysql_query("SELECT username, name FROM table");
while($row = mysql_fetch_assoc($results)) {
if ($row['username'] == 'johndoe') {
// do something, this is a row you want
} else {
// not a row you want. ignore it, or deal with it some other way
}
}
the main difference is that for large data sets in the database, doing client-side filtering like this is expensive, as the entire contents of the table has to be transferred over. Using a WHERE clause to limit things to just what you want is far more efficient in the long run.

Categories