I'm trying to take input from form and compare to $username in database.
If the username does not exist it should print error.
elseif (($_POST['user']) != ($this->mysqli->query("SELECT * FROM users WHERE username='" . $username . "'"))) {
$json['message'] = "User does not exist";
}
This doesn't log a php error, but it doesn't work either.
Make sure you're receiving the correct username through the POST request, this is a common source of errors. Just log it and check the errors file.
Then, let's analyze your mysql query:
SELECT * FROM users WHERE ...
After the select keyword, you should specify which columns you want to be returned. An asterisk (*) means you want all of them, which is fine if you have a single column, the username, but I'm assuming you have more. In this case, notice in your code that you'll be comparing a bunch of columns against the username. It will fail.
Check out this tutorial, it will be helpful to get familiar with using php plus mysql.
I wrapped the snippet below to show you a way of doing this, there are many. It is just checking if the query returned zero rows, which indicates that no record with the given username exists. A better way would be using the mysql function EXISTS().
$username = $_POST["username"];
error_log("Checking if username:'$username' exists.", 0);
$conn = new mysqli($db_servername, $db_username, $db_password, $db_name);
$sql = "SELECT * FROM users WHERE username = '$username'";
$query = $conn->query($sql);
if ($query->num_rows == 0) {
error_log("The username does not exist.", 0);
}
Related
So I have an SQL database that has a table for accounts and info, and another one for storing comments on articles. I Have a form for submitting comments and it works just fine, but I wanted to implement a feature to prevent spam and non registered accounts. I was trying to find a way to make the following code work so that it would call upon my account table and check to see if the username section matches what was entered in the form.
I want it to check through my username column on the table to see if what was entered in the box is actually in the database as well, that way if it hasn't been registered it won't submit.
My problem I keep running into is that I try this
<?
if ($_POST['Uname']==`username`){
$strSQL="INSERT INTO `comments`
(`name`,`comment`,`date`,`#`) VALUES
('".$_POST['Uname']."','".$_POST['Comment']."',
'".$_POST['Date']."','".$_POST['#']."')";
}
else{
echo "Username invalid";
}
}
?>
But when I do this it thinks that "username" is what the username needs to be in order to submit properly.
I do not want every username to need to be "username" in order for them to submit, I just want it to check through my username column to see if what was entered is one of the registered usernames in the SQL column.
Im not sure if this is possible, or if I am making any sense, but this is my first post on this site and I would appreciate any help I could get.
Full code is below
<?
if ($_POST['Enter']=='Enter'){
$con = mysql_connect
("sql***.*******.com","*****","*******");
$db_selected = mysql_select_db("*********",$con); //My login
$test2=$_GET['ID']; //Ignore
$_POST['#']=$test2; //Ignore
$sql="Select * from `Articles` and `Accounts`"; //For pulling data
mysql_query($strSQL,$con);
if ( ? == ? ){ //What should go here?
$strSQL="INSERT INTO `comments`
(`name`,`comment`,`date`,`#`) VALUES
('".$_POST['Uname']."','".$_POST['Comment']."',
'".$_POST['Date']."','".$_POST['#']."')";
}
else{
echo "Username invalid";
}
}
?>
Edit
So after making the changes needed, should my previous code end up like this?
<?
if ($_POST['Enter']=='Enter'){
$con = mysql_connect
("*******","********","*****");
$db_selected = mysql_select_db("*****",$con);
$test2=$_GET['ID'];
$_POST['#']=$test2;
$username = $_POST['Uname'];
$sql = "Select `id` from `Accounts` where `username` = $username";
mysqli_num_rows($sql,$result);
$row_cnt = mysqli_num_rows($result);
printf("Result set has %d rows.\n", $row_cnt);
echo $result;
if ($row_cnt!=''){
$strSQL="INSERT INTO `comments`
(`name`,`comment`,`date`,`#`) VALUES ('".$_POST['Uname']."',
'".$_POST['Comment']."',
'".$_POST['Date']."',
'".$_POST['#']."')";
}
else{
echo "Username invalid";
}
}
?>
Obviously what you doing is not correct, as of now you are putting condition as :
if ($_POST['Uname']==`username`)
which means you saying any user who's name is 'username' should be able to comment, but what you want to achieve is, any user who is valid user and is exist in db should be able to comment. So for that you should write a select sql to check the user, :
$username = $_POST['Uname'];
$sql = "select id from yourusertable where username = $username";
then,
perform
mysqli_num_rows
to check if you get anything greater than zero. If yes, then allow to submit comments.
Simply apply the check that only loggedIn user can comment. So if the user will not exist in users table it will not be loggedIn nor can comment.
If statement logic in the inner line seems to work erroneously everytime (even when correct existing username and password are entered). I cannot find out why.
Code:
<?php
$conn = new mysqli("localhost", "root", "", "customerdirectory");
if($conn->connect_error) {
echo("Connection Failed " . $conn->connect_error);
exit();
}
if(isset($_POST["user"], $_POST["pass"])) {
$username = stripslashes($_POST["user"]);
$username = mysqli_real_escape_string($conn,$username);
$password = stripslashes($_POST["pass"]);
$password = mysqli_real_escape_string($conn,$password);
$result = "SELECT * FROM customer WHERE name=='$username' AND password=='$password'";
**if($conn->query($result) === TRUE)**
echo("Successful login: ".$username);
else
echo("The username or password are incorrect!");
$conn->close();
};
?>
According to the documentation:
For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries
mysqli_query() will return a mysqli_result object. For other
successful queries mysqli_query() will return TRUE.
Since you're executing a SELECT query, you should be expecting a mysqli_result object instead of TRUE. Should work if you change as follows:
if($conn->query($result))
echo("Successful login: ".$username);
else
echo("The username or password are incorrect!");
Your query is wrong. There is no == in mysql
Use this query
$result = "SELECT * FROM customer WHERE name='$username'
AND password='$password'";
MySQL (and other SQL languages) do not use the double equal sign syntax found in programming languages. So your query should be column = value not column == value.
insisted of writing name=='$username' AND password=='$password'; try this below query
select * from customer where name='$username' AND password='$password'";
I am having trouble returning the number of rows. I want my code to check if a username exists, and if it does then return an error. The way I am going about this is if num_rows returns a number larger than 0. I haven't implemented that part yet, I am just trying to get it to return the number of rows right now. Here is my current code:
$hostname = ''; //SET SERVER/HOSTNAME
$dbusername = ''; //SET DATABASE USERNAME
$dbname = ''; //SET DATABASE NAME
$dbpassword = ''; //SET DATABASE USERNAME
$link = mysqli_connect($hostname, $dbusername, $dbpassword, $dbname);
if (!$link)
{
$systemerror = 'Connect Error' . mysqli_connect_errno() . mysqli_connect_error();
$error = "there has been an error";
}
$sql = "SELECT username FROM affiliates WHERE username = $username";
$result = mysqli_query($link, $sql, MYSQLI_USE_RESULT);
if (!result)
{
$error = "There was an error with our system. Please contact All Choice Dental or wait a few minutes. Thank you.";
goto error;
}
$row_cnt = $result->num_rows;
echo $row_cnt;
I don't even get zero back for num_rows, so something has to be wrong. I know I can connect to the database, because I can Insert rows using the same connection.
$username is never defined in your code, so the query comes out as
SELECT username FROM ... username =
As well, since a username is likely to be a string, you're also lacking quotes around that variable, so even if it was set, the query would still be wrong. e.g.
$username = 'fred';
would produce
SELECT username FROM affiliates WHERE username = fred
and you're not likely to have a fred field in your affiliates table. The field should be quoted:
SELECT username FROM ... WHERE username = '$username';
and you should seriously consider using prepared statements instead, as this sort of construct is vulnerable to SQL injection attacks.
You're mixing MySQLi OOP and Procedural - which is bad coding style.
To get the number of rows procedurally, use mysqli_num_rows($result)
I will admit php is a new language to me.
Now I can get each of these working individually. In my prepare query SELECT * FROM... will allow my PDO fetch assoc while loop to work, but then fetch column doesn't work. And then I use SELECT COUNT(*) my fetch column works but then my fetch assoc doesn't.
So Is there away around this so both will work? As I need the fetch column to return how many rows there are as an integer value (1 or 0) to determine if the user has entered log in information. But then I need fetch column there to return back the string value of what is entered in my username section of the table in my database. So that I can use this information to check it against the input from the user to validate the user and password.
Thanks, here's my code. If you need it explained more clearly I'll have a go.
<?php
$config['db'] = array(
'host' => 'localhost',
'username' => 'root',
'password' => '',
'dbname' => 'inb271assignment'
);
$pdo = new PDO('mysql:host=' . $config['db']['host'] . '; dbname=' . $config['db']['dbname'], $config['db']['username'], $config['db']['password']);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try
{
$pdo->beginTransaction();
$username = $_POST['Username'];
$password = $_POST['Password'];
//Nicholas will be $dbUsername when fetch is working correctly.
$databaseusername = Nicholas;
if ($username&&$password)
{
$result = $pdo->prepare("SELECT COUNT(*) FROM members WHERE Username=?");
$result->execute(array($databaseusername));
$row = $result->fetchColumn();
if ($row!=0) {
while ($rows = $result->fetch(PDO::FETCH_ASSOC)) {
$dbUsername = $rows['Username'];
}
echo $dbUsername;
}
else
die("That user doesn't exist");
}
$pdo->commit();
}
catch(PDOException $pe)
{
echo($pe->getMessage());
}
?>
So currently I have SELECT COUNT(*) in there. So if I enter a username and password in my form on the page before it will return back as !=0 allowing the while loop to work. And the while loop normally works if I have SELECT *. But because I don't because I need the count it doesn't. So I can't retrieve the info I need from the database.
Use SELECT * FROM ... and PDO fetch assoc as normally and use $result->rowCount(); for returning all affected rows, which is equivalent with SELECT COUNT(*)
If you query with count(*) only to find out if there is a user with the given username in the database, then you don't need it. You could instead fetch the first row, and if it's empty then there is no user otherwise there is at least one. So you have implicitly your information.
$rowNum = 0;
foreach ($result->fetchAll(PDO::FETCH_ASSOC) as $row) {
$rowNum = $rowNum + 1;
$dbUsername = $row['Username']; // btw after the loop you have only the name of the last row
}
if ($row>0) {
echo $dbUsername;
}
First of all you need to understand the meaning of each operator you are using.
And then use it smart, only when required, instead of adding whatever operators just because you've seen them used somewhere.
As a matter of fact, you don't need neither COUNT(*) nor rowCount(), nor while. Only one row is supposed to be returned. That's enough.
Transaction and try..catch also counts.
What you really need is just a few lines of code:
if (isset($_POST['Username']))
{
$sql = "SELECT * FROM members WHERE Username=? AND Password=?";
$result = $pdo->prepare($sql);
$result->execute(array($_POST['Username'],$_POST['Password']));
return $result->fetch();
// or do whatever you want with returned data
}
that's all
The example of login has one big flaw, it picks the password from the $_POST and queries it directly to mysql.
Which means that the password is in clear in the database.
To apply best practices, you should hash+salt the passwords and encrypt all personal data.
Good overview on how to do it:
http://www.sitepoint.com/hashing-passwords-php-5-5-password-hashing-api/
I have a PHP login script. This is the part where the person can create a new user. My issue is I want to check if the user exists, and if the username does not exist the the table, than create the new user. However, if the user does exist, I want it to return an error in a session variable. Here is the code I have right now. This doesn't include my DB connections, but I know they do work. Its num_rows() that is being written as an error in the error_log file. Here is the code:
$username = mysql_real_escape_string($username);
$query = "SELECT * FROM users WHERE username = '$username';";
$result = mysql_query($query,$conn);
if(mysql_num_rows($result)>0) //user exists
{
header('Location: index.php');
$_SESSION['reg_error']='User already exists';
die();
}
else
{
$query = "INSERT INTO users ( username, password, salt )
VALUES ( '$username' , '$hash' , '$salt' );";
mysql_query($query);
mysql_close();
header('Location: index.php');
The error it is giving me is
mysql_num_rows(): supplied argument is not a valid MySQL result resource in [dirctory name]
mysql_num_rows()
Retrieves the number of rows from a result set. This command is only valid for statements like SELECT or SHOW that return an actual result set. To retrieve the number of rows affected by a INSERT, UPDATE, REPLACE or DELETE query, use mysql_affected_rows().
Instead of doing SELECT * and then mysql_num_rows(), you can do a SELECT COUNT(*) and then retrieve the number of rows, by fetching the field (that should be 0 or 1). SELECT COUNT will always return a result (provided that the query syntax is correct of course).
Also, change the query:
$query = "SELECT * FROM users WHERE username = '$username';";
into
$query = "SELECT * FROM users WHERE username = '"
. mysql_real_escape_string($username) . "';";
Just out of curiosity, have you ever heard of upserts? I.E., "insert on duplicate key". They'd be useful to you in this situation, at least if your username column is a unique key.
http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
$username = mysql_real_escape_string($username);
i think you have to replace the above to
$username = mysql_real_escape_string($_POST[$username]);