How can I check for duplicate usernames using PHP and MySQL? - php

I'm just learning PHP and I thought it would be a good idea to learn some MySQL too.So I started working on the code and for some strange reason I keep getting duplicate users which is really really bad.
<?php
$link = mysqli_connect(here i put the data);
if(!$link)
{
echo "Error: " . mysqli_connect_errno() . PHP_EOL;
exit;
}
else
{
if(isset($_POST['user']))
{ echo "User set! "; }
else { echo "User not set!"; exit; }
if(isset($_POST['pass']) && !empty($_POST['pass']))
{ echo "Password set! "; }
else { echo "Password not set!"; exit; }
$num = mysqli_num_rows(mysqli_query("SELECT * FROM `users` WHERE ( username = "."'".$_POST['user']."' )"));
if($num > 0)
{ echo "Cannot add duplicate user!"; }
mysqli_close($link);
}
?>
For some strange reason I don't get the output I should get.I've tried some solutions found here on StackOverflow but they didn't work.

The first parameter of connectionObject is not given in mysqli_query:
$num = mysqli_num_rows(mysqli_query($link, "SELECT * FROM `users` WHERE ( `username` = '".$_POST['user']."' )"));
//----------------------------------^^^^^^^
Also, your code is vulnerable to SQL Injection. A simple fix would be:
$_POST['user'] = mysqli_real_escape_string($link, $_POST['user']);

mysqli_query must receive two parameters in order to work. In this case, your mysqli_connect.
$num = mysqli_num_rows(mysqli_query($link, "SELECT * FROM `users` WHERE ( username = "."'".$_POST['user']."' )"));
Also, you can be affected by SQL Injection, in this code.
Never add user input directly in your queries without filtering them.
Do that to make your query more readable and safe:
$u_name=mysqli_real_escape_string($link, $_POST['user']);
$num = mysqli_num_rows(mysqli_query($link, "SELECT * FROM `users` WHERE ( username = '$u_name' )"));

To use mysqli_* extension, you must include your connection inside of the parameters of all queries.
$query = mysqli_query($link, ...); // notice using the "link" variable before calling the query
$num = mysqli_num_rows($query);
Alternatively, what you could do is create a query() function within your website, like so:
$link = mysqli_connect(...);
function query($sql){
return mysqli_query($link, $sql);
}
and then call it like so:
query("SELECT * FROM...");

This could be a problem of race condition.
Imagine that two users wants to create the same username at the same time.
Two processes will execute your script. So both scripts select from database and find out that there is not an user with required username. Then, both insert the username.
Best solution is to create unique index on username column in the database.
ALTER TABLE users ADD unique index username_uix (username);
Then try insert the user and if it fails, you know the username exists ...

Here's how to write your code using prepared statements and error checking.
Also uses a SELECT COUNT(*)... to find the number of users instead of relying on mysqli_num_rows. That'll return less data from the database and just seems cleaner imo.
<?php
$link = mysqli_connect(here i put the data);
if(!$link) {
echo "Error: " . mysqli_connect_errno() . PHP_EOL;
exit;
}
else if(!isset($_POST['user'])) {
echo "User not set!"; exit;
}
echo "User set! ";
if(!isset($_POST['pass']) || empty($_POST['pass'])) {
echo "Password not set!"; exit;
}
echo "Password set! ";
$query = "SELECT COUNT(username)
FROM users
WHERE username = ?";
if (!($stmt = $mysqli->prepare($query))) {
echo "Prepare failed: (" . mysqli_errno($link) . ") " . mysqli_error($link);
mysqli_close($link);
exit;
}
$user = $_POST ['user'];
$pass = $_POST ['pass'];
if(!mysqli_stmt_bind_param($stmt, 's', $user)) {
echo "Execute failed: (" . mysqli_stmt_errno($stmt) . ") " . mysqli_stmt_error($stmt);
mysqli_stmt_close($stmt);
mysqli_close($link);
exit;
}
if (!mysqli_execute($stmt)) {
echo "Execute failed: (" . mysqli_stmt_errno($stmt) . ") " . mysqli_stmt_error($stmt);
mysqli_stmt_close($stmt);
mysqli_close($link);
exit;
}
$result = mysqli_stmt_get_result($stmt);
if ($row = mysqli_fetch_array($result, MYSQLI_NUM)) {
$num = $row[0];
if($num > 0) {
echo "Cannot add duplicate user!";
}
}
mysqli_stmt_close($stmt);
mysqli_close($link);
please do suggest fixes to syntax, this was typed from a phone

Related

I want to implement something that doesn't allow the user to rate more than once

I have used someone else's code that uses the ipaddress way. However, I would like to use a code that checks for the current userid and the id number.
$ipaddress = md5($_SERVER['REMOTE_ADDR']); // here I am taking IP as UniqueID but you can have user_id from Database or SESSION
/* Database connection settings */
$con = mysqli_connect('localhost','root','','database');
if (mysqli_connect_errno()) {
echo "<p>Connection failed:".mysqli_connect_error()."</p>\n";
} /* end of the connection */
if (isset($_POST['rate']) && !empty($_POST['rate'])) {
$rate = mysqli_real_escape_string($con, $_POST['rate']);
// check if user has already rated
$sql = "SELECT `id` FROM `tbl_rating` WHERE `user_id`='" . $ipaddress . "'";
$result = mysqli_query( $con, $sql);
$row = mysqli_fetch_assoc();//$result->fetch_assoc();
if (mysqli_num_rows($result) > 0) {
//$result->num_rows > 0) {
echo $row['id'];
} else {
$sql = "INSERT INTO `tbl_rating` ( `rate`, `user_id`) VALUES ('" . $rate . "', '" . $ipaddress . "'); ";
if (mysqli_query($con, $sql)) {
echo "0";
}
}
}
//$conn->close();
In your database table, set the user_id column as UNIQUE KEY. That way, if a user tries to cast a second vote, then the database will deny the INSERT query and you can just display a message when affected rows = 0.
Alternatively, (and better from a UX perspective) you can preemptively do a SELECT query for the logged in user before loading the page content:
$allow_rating = "false"; // default value
if (!$conn = new mysqli("localhost", "root","","database")) {
echo "Database Connection Error: " , $conn->connect_error; // never show to public
} elseif (!$stmt = $conn->prepare("SELECT rate FROM tbl_rating WHERE user_id=? LIMIT 1")) {
echo "Prepare Syntax Error: " , $conn->error; // never show to public
} else {
if (!$stmt->bind_param("s", $ipaddress) || !$stmt->execute() || !$stmt->store_result()) {
echo "Statement Error: " , $stmt->error; // never show to public
} elseif (!$stmt->num_rows) {
$allow_rating = "true"; // only when everything works and user hasn't voted yet
}
$stmt->close();
}
echo "Rating Permission: $allow_rating";
And if they already have a row in the table, then don't even give them the chance to submit again.

MYSQL assign column name to variable?

I have a database table which has two columns, business and tourist.
I ask a user to select one of them from dropdown list, then use the result in a SELECT statement in MySQL. I assign this column to $cclass, then I make this statement SELECT $cclass FROM flights ....
But it always returns NULL. Why does it return NULL and how do I fix this?
My code:
$check = mysql_query("SELECT $cclass FROM flights WHERE flight_no = '$flightno'");
while ($result = mysql_fetch_assoc($check))
{
$db_seats = $result['$cclass'];
}
you should replace this line:
$db_seats = $result['$cclass'];
with this:
$db_seats = $result[$cclass];
string between 2 single quotes doesn't parsed:
Strings
Have you tried doing the following:
$check = mysql_query("SELECT".$cclass." FROM flights WHERE flight_no = '$flightno'");
First of all, this code has a serious security issue, as it is vulnerable to SQL Injection. You should be using the MySQLi extension instead, and properly filtering your input.
Try something like this:
<?php
/* Create the connection. */
$mysql = new mysqli("localhost", "username", "password", "myDB");
if ($mysql->connect_error)
{
error_log("Connection failed: " . $mysql->connect_error);
die("Connection failed: " . $mysql->connect_error);
}
/* Sanitize user input. */
if (!in_array($cclass, array('business', 'tourist')))
{
error_log("Invalid input: Must be 'business' or 'tourist'");
die("Invalid input: Must be 'business' or 'tourist'");
}
$statement = $mysql->stmt_init();
$statement->prepare("SELECT $cclass FROM flights WHERE flight_no = ?");
$statement->bind_param("s", $flightno);
if (!$statement->execute())
{
error_log("Query failed: " . $statement->error);
die("Query failed: " . $statement->error);
}
if ($statement->num_rows < 1)
{
echo "No results found.";
}
else
{
$statement->bind_result($seats);
while ($statement->fetch())
{
echo "Result: $seats";
// Continue to process the data... You can just use $seats.
}
}
$mysql->close();
However, the reason your original example is failing, is that you're quoting $cclass:
$db_seats = $result[$cclass];
However, please do not ignore the serious security risks noted above.

check username in databse and update[html,mysql,php]

i have been trying since yesterday, and almost covered all questions regarding this matter in Stackoverflow plus googling, but so far nothing is working with me, i try to check username availability before updating the username in database, however, it wont check and always update the username directly without error message regarding not availability of the name..
here my code
//new connection
$con = new mysqli("localhost", "student", "student", "C14D5");
if ($con->connect_errno) { //failed
echo "Failed to connect to MySQL: (" . $con->connect_errno . ") " . $con->connect_error;
}
//success
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['clientN'])) {
$query = mysqli_query("SELECT client_name FROM clients WHERE client_name='".$_POST['clientN']."'");
if (mysqli_num_rows($query) != 0) {
echo "<script>
alert('Username is not available, please select another username.');
</script>";
header('Location: '. $_SERVER['HTTP_REFERER'] );
} else {
// run sql
$sql ="UPDATE `clients` SET `client_name` = '".$_POST['clientN']."' WHERE `client_ID` = '".$_POST['SelectClient']."'";
if ($con->query($sql) === TRUE) {
echo "<h3> New record created successfully</h3>";
header('Location: '. $_SERVER['HTTP_REFERER'] );
} else {
echo "Error : " . $sql . "<br>" . $con->error;
}
$con->close();
}
}
You can use the mysqli_num_rows() function to avoid data duplication in your database
use this code :
//specify the database connection factors as usual ,then
$uname = $_POST['your_username_field'];
$sql = "SELECT * FROM your_db where username='$uname'";
//the variable 'sql' will store the resultset of the query
$num_row = mysqli_num_rows($sql);
// the 'num_row' will store the number of rows which matches your $sql resultset. So if it is greater than '0' then the data already exists
if( $num_row > 0)
{
// display 'username exists error'
}
else
{
// Insert user name into your database table
}
If the num_rows is greater than 0 ,then the username is already present in your database table . So at that case throw error. else INSERT the user name into your database and display success message .

How do I redirect with PHP and save the link in SQL?

I have XAMPP and I want to write a simple PHP page, that redirects me to the link that I specify, and also saves the link in an SQL database.
Let's say I want to visit www.google.com:
I'd visit something like:
localhost:80/redirect.php?url=https://google.com
And PHP would redirect me there and also save the www.google.com link in an SQL table.
Can you help me out?
Considering how you formed your question, it looks as if you had an idea an just want someone to give you the solution without you even making an effort (please correct me if I'm wrong but that's how it seams...)
The task you are trying to achieve is a simple one, and it's only fair to point you in the right direction. your "task" can be broken into several smaller ones:
Create database / table for storing data | PHP Create MySQL Tables
Get URL parameter in PHP
PHP Insert Data Into MySQL
How to make a redirect in PHP
Sorry if this is not the kind-a answer you are looking for, but I figure the point of this website is for people to learn something and not just copy+paste. The provided links can be used to solve your task problem.
This is what I came up with, after MySQLi Object-oriented did not validate this:
$sql = "SELECT * FROM logging WHERE link=$link";
if ($conn->query($sql) === TRUE) {}
It still increments the number of visits sometimes by +2. I don't know why.
<?php
$servername = " ";
$username = " ";
$password = " ";
$dbname = " ";
$datetime = date_create()->format('Y-m-d H:i:s');
$datetime = "'".$datetime."'";
$link_clean = $_GET['link'];
$link = "'".$link_clean."'";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM logging WHERE link=$link";
if ($result = mysqli_query($conn, $sql))
{
if(mysqli_num_rows($result)>0)
{
$sql="UPDATE logging SET last_visit_date = $datetime, visit_count = visit_count + 1 WHERE link=$link";
if (mysqli_query($conn, $sql)) {
$conn->close();
header("Location: https://$link_clean");
exit;
} else {
echo "1Error: " . $sql . "<br>" . mysqli_error($conn);
$conn->close();
exit;
}
}
else
{
$sql="INSERT INTO logging (link, last_visit_date, visit_count) VALUES ($link , $datetime , 1)";
if (mysqli_query($conn, $sql)) {
mysqli_close($conn);
header("Location: https://$link_clean");
exit;
} else {
echo "2Error: " . $sql . "<br>" . mysqli_error($conn);
mysqli_close($conn);
exit;
}
}
}
else
{
echo "3Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>

Cant track error cause in PHP page updating a MS SQL database

Simple PHP page (I'm no PHP expert, just learning) to update a MS SQL database. The following code generates an error that I dont know how to solve.
include '/connections/SFU.php';
$query = "UPDATE Person SET PhotoURL = '".$file["name"]."' WHERE USERID='".$_REQUEST['user_id']."';";
if ($result = odbc_exec($dbconnect, $query)) {
echo "// Success!";
}
else {
echo "// Failure!";
}
odbc_close($dbconnect);
//End Update
This fails every time in the "if ($result ..." section
However, if I run virtually the same code
include '/connections/SFU.php';
$query = "UPDATE Person SET PhotoURL = '89990.jpg' WHERE USERID='80'";
if ($result = odbc_exec($dbconnect, $query)) {
// Success!
}
else {
// Failure!
}
odbc_close($dbconnect);
//End Update
It works just fine. I have echoed the $query string to the screen and the string is the same for both. I can't figure out why it fails in one and not the other?
Also weird is when I use a parameterized query such as
include '/connections/SFU.php';
$query = "UPDATE dbo.Person SET PhotoURL=? WHERE USERID=?";
if ($res = odbc_prepare($dbconnect,$query)) {
echo "Prepare Success";
} else {
echo "Prepare Failed".odbc_errormsg();
}
$uid = $_REQUEST['user_id'];
$fn = $file["name"];
echo "query=".$query." userid=".$uid." filename=".$fn;
if ($result = odbc_exec($res, array($fn, $uid))) {
echo "// Success!";
}
else {
echo odbc_errormsg();
echo "// Failure!";
}
odbc_close($dbconnect);
The query fails in the prepare section above, but fails in the odbc_exec section below:
include '/connections/SFU.php';
$query = "UPDATE Person SET PhotoURL=? WHERE USERID=?";
if ($res = odbc_prepare($dbconnect,$query)) {
echo "Prepare Success";
} else {
echo "Prepare Failed".odbc_errormsg();
}
$uid = "80";
$fn = "samplefile.jpg";
echo "query=".$query." userid=".$uid." filename=".$fn;
if ($result = odbc_exec($res, array($fn, $uid))) {
echo "// Success!";
}
else {
echo odbc_errormsg();
echo "// Failure!";
}
odbc_close($dbconnect);
In all cases I do not get any odbc_errormsg ().
Remove the extra ; from your query.
$query = "UPDATE Person SET PhotoURL = '".$file["name"]."' WHERE
USERID='".$_REQUEST['user_id']."';";
^
So your query should be,
$query = "UPDATE Person SET PhotoURL = '".$file["name"]."' WHERE
USERID='".$_REQUEST['user_id'];
Also have practice of using odbc_errormsg() so you can have a better idea why your query gets failed.
Warning: Your code is vulnerable to sql injection attacks!

Categories