I am trying to create a simple process that checks if a username is taken already during the login process.
I have a simple php script that querys the database and then i check to see if there are any results and echos a response to the user
the full error that i get is:
mysql_num_rows(): supplied argument is not a valid MySQL result resource in /home1/tbronson/public_html/sandbox/uname_check.php on line 9
The entire php script is:
<?php
$user = "(removed for security)";
$pass = "(removed for security)";
$db = "budgetbidders_users";
$con = mysqli_connect($host,$user,$pass,$db);
$uname = strip_tags( trim( $_POST['uname'] ) );
$result = mysqli_query($con,"SELECT * FROM `users` WHERE uname = '" .$uname . '");
$numrows = mysql_num_rows($result); //line 9
if ($numrows > 0) {
$end_result = "Username already taken";
}
else {
$end_result = "";
}
echo $end_result;
?>
I have searched for hours and tried multiple variations, this seems to be the closest to correct that i can find, thank you for your help!
There were a few errors in your code.
The following line has a missing double-quote before the single quote for $uname:
$result = mysqli_query($con,"SELECT * FROM `users`
WHERE uname = '" .$uname . '");
^
However it would be better to use prepared statements or PDO along or you can use:
WHERE uname = '$uname' // instead
Plus, you're mixing the deprecated mysql_* function with the mysqli_* functions.
mysqli_query and mysqli_num_rows() where mysql_num_rows() needs to be changed to mysqli_num_rows
I also suggest you change:
$uname = strip_tags( trim( $_POST['uname'] ) );
to:
$uname = mysqli_real_escape_string($con, $_POST['uname']);
And:
WHERE uname = '" .$uname . "'
to:
WHERE uname = '$uname'
You can make any modifications you wish, both will work. Do read this article on SO on how to prevent SQL injection.
Give this a try now:
<?php
$user = "(removed for security)";
$pass = "(removed for security)";
$db = "budgetbidders_users";
$con = mysqli_connect($host,$user,$pass,$db);
// the line below is better to use
$uname = mysqli_real_escape_string($con, $_POST['uname']);
// this is your original line of code which will work also
// $uname = strip_tags( trim( $_POST['uname'] ) );
$result = mysqli_query($con,"SELECT * FROM `users` WHERE uname = '" .$uname . "' ");
$numrows = mysqli_num_rows($result); //line 9
if ($numrows > 0) {
$end_result = "Username already taken";
} else {
$end_result = "";
}
echo $end_result;
?>
That is beacase u are using mysql_ instead of mysqli_
try this
$numrows = mysqli_num_rows($result):
You cannot mix mysql_* and mysqli_* syntax.
In your case you need:
$numrows = mysqli_num_rows($result);
And you have a syntax error on the line before it (a missing quote).
Related
This question already has an answer here:
I cannot get my login form to connect interact properly with mySQL database [closed]
(1 answer)
Closed 6 years ago.
I am very new to php and I am trying to create a login system. Here is my code
<?php
$con=mysqli_connect("XXXXXXX","XXXXXXXX","XXXXXXXXX","XXXXXXXXXX");
if (!$con)
{
echo "failed to connect";
}
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT userID FROM users WHERE username = $username and password = $password;";
if (!$sql) {
echo 'query invalid'.mysql_error();
}
$result = mysql_query($sql);
echo "$result";
$row = mysqli_fetch_array($sql, MYSQLI_ASSOC);
$active = $row['active'];
$count = mysqli_num_rows($result);
mysql_close($con);
?>
I am sure there is no problem with the connection. But my result is not showing up and there is no error message. Previously I had an IF statement that perform further action if the result comes back. Since I am trying to figure out what is going on, I just deleted that part. Somebody please help. Many thanks
You're missing the single quotes around the variables, and also you're using mysql mixed with mysqli, which will not work.
$sql = "SELECT userID FROM users WHERE username = '$username' and password = '$password';";
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_assoc($sql); // same as fetch_array with MYSQLI_ASSOC
$active = $row['active'];
$count = mysqli_num_rows($result);
You don't need mysql_close at the end, but if you want to use it, it's mysqli_close($con);
Keep in mind this is unsafe.
Use this function to filter user input:
$username = mysqli_real_escape_string($con, $_POST['username']);
$password = mysqli_real_escape_string($con, $_POST['password']);
Read this to make sure your code follows the security standards.
I recommend this.
$sql = "SELECT userID FROM users
WHERE username = " ._sql($username) ." and password = " ._sql($password);
// generate sql safe string function
function _sql($txt) {
if ($txt === null || $txt === "")
return "NULL";
if (substr($txt, 0, 2) == "##")
return substr($txt, 2);
//$txt = str_replace("'", "''", $txt);
$txt = mysql_real_escape_string($txt);
return "'" . $txt . "'";
}
I have tryed this many many times and i don't get why this don't work. Because of this my registeration pages pass all usernames. I have no idea what is wrong. Sorry about my bad english i am really tired and desperate
function user_exists($username){
$username = htmlspecialchars($username);
$sql = "SELECT username FROM ***** WHERE username = '$username'";
$result = mysqli_query($GLOBALS['$db'], $sql);
if(mysqli_num_rows($result) > 0){
$errors[] = 'Käyttäjätunnus \''. $_POST['username'] . '\' on jo otettu.';
}
}
I am calling that function like this:
if(user_exists($_POST['username']) === true){
$errors[] = 'Käyttäjätunnus \''. $_POST['username'] . '\' on jo otettu.';
}
Well, let's clean this up some
function user_exists(mysqli $db, $username){
$username = htmlspecialchars($username);
$sql = "SELECT username FROM ***** WHERE username = ?";
$prep = $db->prepare($sql);
$prep->bind_param('s', $username);
$prep->execute();
$result = $prep->get_results();
$errors = [];
if($result->num_rows > 0){
$errors[] = 'Käyttäjätunnus \''. $username . '\' on jo otettu.';
}
return $errors;
}
First, you need to inject your DB connection into the function. Avoid using globals.
Second, we're switching to a prepared statement. Solves the SQL injection problem.
Third, we're returning an array. Your errors will never show up the way you were doing it. You can pick how/what gets returned, but, again, we don't want globals.
I send a password to php to get compared to the hash stored in the database.
my php is:
$enteredUser = $_POST["username"];
$enteredPass = $_POST["password"];
$query = mysqli_query($con, "SELECT passhash FROM user WHERE `username` = '$enteredUser'");
$passHash = mysql_result($query, 0);
if(password_verify($enteredPass, $passHash)){
echo "success";
}else{
echo "failure";
}
I also tried using mysqli_fetch_array() as well, but it still doesn't work. Does anyone know why this isn't working? thanks in advance to anyone who can help. (on a side note, $passHash returns null)
You are mixing two extensions, mysqli and mysql - mysqli_query and then mysql_result.
You are also open to SQL injection and should be sanitising your POST input before passing it directly to MySQL.
mysqli_query returns a result object and you then need to fetch the results from that object.
mysqli_fetch_row will return one row.
$enteredUser = $_POST["username"];
$enteredPass = $_POST["password"];
//...
$resultset = mysqli_query($con, "SELECT passhash FROM user WHERE `username` = '$enteredUser'");
$result = mysqli_fetch_row($resultset);
if(password_verify($enteredPass,$result[0])){
echo "success";
}else{
echo "failure";
}
I did solve my own problem with a simple while loop, i guess it will work fine, thanks everyone for your input:
$passHash = '';
while ($row = mysqli_fetch_array($query)) {
$passHash .= $row["passhash"];
}
Give this a try:
$enteredUser = mysqli_real_escape_string($con,$_POST["username"]);
$enteredPass = mysqli_real_escape_string($con,$_POST["password"]);
$sql = "SELECT * FROM `user` WHERE `username` = '$enteredUser'";
$result = $con->query($sql);
if ($result->num_rows === 1) {
$row = $result->fetch_array(MYSQLI_ASSOC);
if (password_verify($enteredPass, $row['passhash']))
{
echo "Success";
}
else {
echo "Sorry";
}
I am trying to return a username when a user forgets their username. I have it validating again their email address but for some reason it just keeps saying 'Error: cannot find username'. I am using the correct mysqli syntax I hope.
if (isset($_POST['user'])) {
$email = mysqli_real_escape_string($con, $_POST['email']);
$username = "";
if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)) {
$errmsg = 'Error: ' . $email . ' is not a valid email address';
} else {
$query = "SELECT email FROM admin WHERE email = '$email'";
$results = mysqli_query($con, $query);
$query2 = mysqli_fetch_array($results);
if ($query2 == 0) {
$errmsg = 'Error: ' . $email . ' is not found, please try again';
}
if (!errmsg) {
$getuname = "SELECT * FROM admin WHERE email = '$email'";
if (!mysqli_query($con, $getuname)) {
die('Error: ' . mysqli_error($con));
}
$row = mysql_fetch_array($getuname);
}
$username = '<div class="registersuccess">Your username is: ' . $row['username'] . '</div>';
}
$username = '<div class="registererror">Error: cannot find username</div>';
mysqli_close($con);
}
I am a noob when it comes to this but am pretty sure this is correct. if not where did i go wrong?
These are some of the errors I noticed:
You're doing if (!errmsg) but there's no such constant and you want if (!$errmsg) instead.
As Marc B pointed out, you're doing $row = mysql_fetch_array($getuname); but you want $row = mysqli_fetch_array($getuname); instead.
Also, the specific problem you're describing is probably because of the $username declaration just before the mysqli_close statement. You're resetting the value of $username there and it'd always echo out the same message regardless of the result of your database query.
$username = "";
if(condition)
{
# code ...
}
else
{
# code ...
}
$username = '<div class="registererror">Error: cannot find username</div>';
mysqli_close($con);
That's one of the many logical mistakes in your code. Structure the if-else blocks with proper indentation and you shouldn't have this issue.
I found some mistake in your code, you can see the mistake in Mark B and Amal Murali's answer. Let me make your else block simple and more clear. you can use only 1 query instead of 2 queries.
else {
$query = mysqli_query("SELECT * FROM admin WHERE email = '$email'");
$row = mysqli_fetch_array($query);
$numrows = mysqli_num_rows($query);
if (!$errmsg){
if($numrows == 0) {
$errmsg = 'Error: '.$email.' is not found, please try again';
// or here you can add message like Cannot find username
}
else
{
$username = '<div class="registersuccess">Your username is: '.$row['username'].'</div>';
}
}
Your code is a disaster. You're using ereg, which has been deprecated since the stone age. You're mixing calls to the mysql (no i) and the mysqli (with i) libraries. They are NOT interchangeable and are NOT compatible with each other.
You need to switch over to the preg functions, and standardize on a SINGLE mysql library. Since mysql is deprecated as well, use mysqli ONLY.
$row = mysql_fetch_array($getuname);
^^^---note the LACK of an i
if (!errmsg){
^^^--note the lack of a $ sign, meaning this is undefined/undeclared constant.
Change this section of code:
if (!errmsg){
$getuname = "SELECT * FROM admin WHERE email = '$email'";
if (!mysqli_query($con,$getuname))
{
die('Error: ' . mysqli_error($con));
}
$row = mysql_fetch_array($getuname);
}
$username = '<div class="registersuccess">Your username is: '.$row['username'].'</div>';
}
$username = '<div class="registererror">Error: cannot find username</div>';
to:
if (!errmsg){
$getuname = "SELECT * FROM admin WHERE email = '$email'";
$uresult = mysqli_query($con, $getuname);
if (!$uresult))
{
die('Error: ' . mysqli_error($con));
}
$row = mysqli_fetch_array($uresult);
if ($row) {
$username = '<div class="registersuccess">Your username is: '.$row['username'].'</div>';
} else {
$username = '<div class="registererror">Error: cannot find username</div>';
}
}
Your mistakes:
You were calling mysql_fetch_array instead of mysqli_fetch_array.
You were passing the SQL string to mysql_fetch_array, not the result of mysqli_query.
You weren't checking whether a row was returned, you were just setting $username unconditionally -- first to the success message, then to the failure message.
I have been trying for the past four days to get this working. It's just a simple logon page, where no sensitive information is stored, but I'm having problems with the PHP.
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$uname = $_POST["login"];
$pword = $_POST["pass"];
$uname = htmlspecialchars($uname);
$pword = htmlspecialchars($pword);
$user_name = "bradf294_access";
$password = "********";
$database = "bradf294_clients";
$server = "localhost";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
print(mysql_errno());
print($db_found);
if(isset($db_found)){
print($db_found."Success");
$SQL = "SELECT * FROM basicinfo WHERE ref = $uname AND pass = $pword";
$result = mysql_query($SQL);
print("Query made");
print(mysql_errno());
if ($result) {
print("result:".$result);
}
else {
print("Incorrect Login Details");
}
if ($result > 0) {
print("found user");
$errorMessage= "logged on ";
session_start();
$_SESSION['login'] = "1";
header ("Location: progressuser.php");
}
else {
print("Invalid Logon");
}
} else {
print("Database not found. The Webmaster has been notified. Please try again later");
$subject = "Automated login error" ;
$message = "An error occured whilst trying to connect to the MySQL database, to login to the progress checker" ;
mail("a-bradfield#bradfieldandbentley.co.uk", $subject, $message);
}
From the output on the page which I've been using to debug, it appears to be the lines which don't seem to be working, which are giving a 1054 error - "Unknown column '%s' in '%s'"
$SQL = "SELECT * FROM basicinfo WHERE ref = $uname AND pass = $pword";
$result = mysql_query($SQL)
even though I copied and pasted the $SQL string into phpMyAdmin and it worked perfectly?
Is there anything blatantly obvious I'm doing wrong? Go to http://www.bradfieldandbentley.co.uk/test/progress.php and enter the details Reference: TST001 and pass: dnatbtr121 to see the output for yourselves.
You need to quote out the variables:
$SQL = "SELECT * FROM basicinfo WHERE ref = '$uname' AND pass = '$pword'";
HOWEVER
The mysql_* functions are being deprecated - you should look at moving to PDO or mysqli_* instead. Those both make it a lot easier for you to write secure code, as well as fixing the quoting problem for you.
Should the value in your WHERE conditions not be surrounded by quotes, like in a normal MySQL statement? Yes. Also, you are going to get a bunch of comments about SQL injection.