Checking if username exists in DB with PHP and MySQL [duplicate] - php

This question already has answers here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
How to check if a row exists in MySQL? (i.e. check if username or email exists in MySQL)
(4 answers)
How to prevent duplicate usernames when people register?
(4 answers)
How to include a PHP variable inside a MySQL statement
(5 answers)
Closed 1 year ago.
Been struggling with this for a few days, and read a ton of similar problems but still haven't been able to figure it out. I am trying to take user information via an html form and update my database with it, but only if the username doesn't already exist...
Issue 1: No matter what, it can keep creating entries with the same username
Issue 2: I keep getting the error Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, bool given
I am sure they are connected but for the life of me I can't figure out what the fix is.
<?php
//declare variables
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "mypassword";
$db = "user_info";
if (!empty($_POST)) {
//connect to mysqli
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $db);
//check connection
if ($mysqli->connect_error) {
die('Connect Error: ' . $mysqli->connect_errno . ': ' . $mysqli->connect_error );
}
//declare user variables
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$user_name = $_POST['user_name'];
$pass = $_POST['pass'];
$address = $_POST['address'];
$phone = $_POST['phone'];
//get data from form
$sql = "INSERT INTO users (first_name, last_name, user_name, pass, address, phone) VALUES
('{$mysqli->real_escape_string($first_name)}',
'{$mysqli->real_escape_string($last_name)}',
'{$mysqli->real_escape_string($user_name)}',
'{$mysqli->real_escape_string($pass)}',
'{$mysqli->real_escape_string($address)}',
'{$mysqli->real_escape_string($phone)}')";
// ** HERE IS WHERE I AM HAVING ISSUES **
//query to see if entered username already exists
$result = $mysqli->query("SELECT * FROM users WHERE user_name =$user_name");
//alert if user name taken
if (mysqli_num_rows($result) > 0) {
echo "<b>Username already taken! Please select another.</b>";
} else {
//continue to insert into database if username is unique
$insert = $mysqli->query($sql);
//print response from mysql
if ($insert) {
echo "Success! Row ID: {$mysqli->insert_id}";
} else {
die("error: {$mysqli->errno}");
}
}
//close our app
$mysqli->close();
}
?>

Try like this
<?php
if (!empty($_POST)) {
//connect to mysqli
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $db);
//check connection
if ($mysqli->connect_error) {
die('Connect Error: ' . $mysqli->connect_errno . ': ' . $mysqli->connect_error );
}
//declare user variables
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$user_name = $_POST['user_name'];
$pass = $_POST['pass'];
$address = $_POST['address'];
$phone = $_POST['phone'];
$query = $mysqli->prepare("SELECT count(*) FROM users WHERE user_name = ?");
$query->bind_param('s', $user_name);
$query->bind_result($cnt);
$query->execute();
$query->store_result();
$query->fetch();
$query->close();
if ($cnt > 0) {
echo "<b>Username already taken! Please select another.</b>";
} else {
$query = $mysqli->prepare("INSERT INTO users (first_name, last_name, user_name, pass, address, phone) VALUES (?,?,?,?,?,?)");
$query->bind_param('ssssss', $first_name, $last_name, $user_name, $pass, $address, $phone);
$query->execute();
if ($query->execute()) {
echo "Success! Row ID: {$query->insert_id}";
} else {
die("error: {$query->errno}");
}
$query->close();
}
}

Related

PHP inserting with bind_param

I am currently working trying to use the statements mysqli_prepare and bind_param in order to pass arguements more safely into my query. I was doing mysqli_query to execute them before which worked fine. My professor is requiring us to use prepare though. I currently am getting the proper values from my form but the data isn't being entered into customer table. Also, I have mysqli_error() on my execute() commands but I am not getting any errors at all which is making debugging difficult. Here is the php part located in register.php
<?php
require 'connection.php';
$result = "";
if(isset($_POST['register'])) {
#Fetch the data from the fields
$username = $_POST['username'];
$password = $_POST['password'];
$name = $_POST['name'];
$total = 0.0;
#echo $username . " " . $password . " " . $name . " " . $total;
#Prepare sql query to see if account already exists
$query = mysqli_prepare("SELECT * FROM customer WHERE username=?");
$query->bind_param("s", $username);
$query->execute() or die(mysqli_error());
if(mysqli_num_rows($query) > 0) {
#This username already exists in db
$result = "Username already exists";
} else {
$insert = mysqli_prepare("INSERT INTO customer(username, password, name, total) VALUES (?, ?, ?, ?)");
$insert->bind_param("sssd", $username, $password, $name, $total);
$insert->execute() or die(mysqli_error());
#$result = "Account registered!"
}
}
?>
I establish connection to my db like this in connection.php
$conn = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
Like I said before, I can get the query to execute with mysqli_query but for some reason I cannot get param to work. Also tried adding or die but no errors are being printed

PHP will not insert user data into SQL? [duplicate]

This question already has answers here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
How can I prevent SQL injection in PHP?
(27 answers)
Reference - What does this error mean in PHP?
(38 answers)
Closed 4 years ago.
I have created this for a user registration. I am testing this to be input into the SQL database prior to going further. For some reason, this will not input into my database. Any ideas?
I appreciate your assistance.
<?php
$uid = $_POST['uid'];
$pwd = $_POST['pwd'];
$email = $_POST['email'];
if (!empty($uid) || !empty($pwd) || !empty($email)) {
$host = "localhost";
$dbUsername = "connectg";
$dbPassword = "";
$dbname = "my_connectg";
//create connection
$conn = new mysqli($host, $dbUsername, $dbPassword, $dbname);
if (mysqli_connect_error()) {
die('Connect Error('. mysqli_connect_errno().')'. mysqli_connect_error());
} else {
$SELECT = "SELECT email From users Where email = ? Limit 1";
$INSERT = "INSERT Into users (uid, pwd, email) values(?, ?, ?)";
//Prepare statement
$stmt = $conn->prepare($SELECT);
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->bind_result($email);
$stmt->store_result();
$rnum = $stmt->num_rows;
if ($rnum==0) {
$stmt->close();
$stmt = $conn->prepare($INSERT);
$stmt->bind_param("ssi", $uid, $pwd, $email);
$stmt->execute();
echo "New record inserted sucessfully";
} else {
echo "Someone already register using this email";
}
$stmt->close();
$conn->close();
}
} else {
echo "All field are required";
die();
}
?>

Resolve MySQLi empty query error [duplicate]

This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 6 years ago.
Warning received:
Warning: mysqli::query(): Empty query in C:\wamp\www\otp-task\welcome.php on line 62
My database connection is here:
function insertDB($email, $OTP , $phonenumber )
{
$servername = "localhost";
$username = "root";
$password = "";
$db = "dbotp";
$conn = new mysqli($servername, $username, $password, $db);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// insert to db and close the connection, default time attribute is 60 mins
// the table name is onetime and will hold the otp and phonenum and email
$res = mysqli_query($conn, "INSERT INTO onetime (otpnum,email,phoneNum,action) VALUES ('$OTP' , '$email' , '$phonenumber','success')");
// $res = "INSERT INTO onetime (otpnum,email,phoneNum,action) VALUES ('$OTP' , '$email' , '$phonenumber', 'success')";
if ($conn->query($res) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $res . "<br>" . $conn->error;
}
$conn->close();
}
The following two is just a different format for the same thing:
$conn->query(...)
and
mysqli_query($conn, ...)
Once you executed one of them, use the return value of it instead of re-executing the query:
$res = $conn->query(...)
if ($res) {
// ...
}
Please also read about prepared statements: http://php.net/manual/en/mysqli-stmt.prepare.php

How should I "sanitize" my data inputs to fight against SQL injections? [duplicate]

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 7 years ago.
I've been working on a project for a website idea, but I noticed that I can actually perform SQL injections on my site. This isn't good, because if I can, then anyone can. What's the "best" way to sanitize data inputs for a php site?
<?php
$servername = "localhost";
$username = "myusername";
$password = "mypassword";
$dbname = "users";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$pnum = $_POST['pnum'];
$cc = $_POST['cc'];
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "INSERT INTO Users (fname, lname, cc, pnum, username, password) VALUES ('$fname', '$lname', '$cc', '$pnum', '$username', '$password')";
$result = $conn->multi_query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
header('Location: registered.html');
}
$conn->close();
?>
Use prepared statements, which are designed to prevent injection.
http://php.net/manual/en/pdo.prepared-statements.php

PHP registered user check

I have PHP + AS3 user login&register modul.I want to check registered user by username.But can't do it because I'm new at PHP.If you can help it will helpfull thx.(result_message part is my AS3 info text box.)
<?php
include_once("connect.php");
$username = $_POST['username'];
$password = $_POST['password'];
$userbio = $_POST['userbio'];
$sql = "INSERT INTO users (username, password, user_bio) VALUES ('$username', '$password', '$userbio')";
mysql_query($sql) or exit("result_message=Error");
exit("result_message=success.");
?>
Use MySQLi as your PHP function. Start there, it's safer.
Connect your DB -
$host = "////";
$user = "////";
$pass = "////";
$dbName = "////";
$db = new mysqli($host, $user, $pass, $dbName);
if($db->connect_errno){
echo "Failed to connect to MySQL: " .
$db->connect_errno . "<br>";
}
If you are getting the information from the form -
$username = $_POST['username'];
$password = $_POST['password'];
$userbio = $_POST['userbio'];
you can query the DB and check the username and password -
$query = "SELECT * FROM users WHERE username = '$username'";
$result = $db->query($query);
If you get something back -
if($result) {
//CHECK PASSWORD TO VERIFY
} else {
echo "No user found.";
}
then verify the password. You could also attempt to verify the username and password at the same time in your MySQL query like so -
$query = "SELECT * FROM users WHERE username = '$username' AND password = '$password';
#Brad is right, though. You should take a little more precaution when writing this as it is easily susceptible to hacks. This is a pretty good starter guide - http://codular.com/php-mysqli
Using PDO is a good start, your connect.php should include something like the following:
try {
$db = new PDO('mysql:host=host','dbname=name','mysql_username','mysql_password');
catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
Your insert would go something like:
$username = $_POST['username'];
$password = $_POST['password'];
$userbio = $_POST['userbio'];
$sql = "INSERT INTO users (username, password, user_bio) VALUES (?, ?, ?)";
$std = $db->prepare($sql);
$std = execute(array($username, $password, $userbio));
To find a user you could query similarly setting your $username manually of from $_POST:
$query = "SELECT * FROM users WHERE username = ?";
$std = $db->prepare($query)
$std = execute($username);
$result = $std->fetchAll();
if($result) {
foreach ($result as $user) { print_r($user); }
} else { echo "No Users found."; }
It is important to bind your values, yet another guide for reference, since I do not have enough rep yet to link for each PDO command directly from the manual, this guide and website has helped me out a lot with PHP and PDO.

Categories