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]);
Related
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);
}
For some reason, the query when run through PHP will not return the results. I have tried both queries in the MySQL command line, and they work perfectly there. Here is the code (mysql_connect.php is working perfectly, to clarify).
<?php
error_reporting(-1);
// retrieve email from cookie
$email = $_COOKIE['email'];
// connect to mysql database
require('mysql_connect.php');
// get user_id by searching for the email it corresponds to
$id = mysqli_query($dbc,"SELECT user_id FROM users WHERE email=$email")or die('couldn\'t get id');
// get data by using the user_id in $id
$result = mysqli_query($dbc,"SELECT * FROM users WHERE user_id=$id")or die('couldn\'t get data');
//test if the query failed
if($result === FALSE) {
die(mysql_error());
echo("error");
}
// collect the array of results and print the ones required
while($row = mysql_fetch_array($result)) {
echo $row['first_name'];
}
?>
When I run the script, I get the message "could not get id", yet that query works in the MySQL command line and PHPMyAdmin.
Your code won't work for 2 reasons - $id will not magically turn into integer, but a mysqli result. And email is a string so it should be quoted.
But...
Why is all of that?
If you want to fetch all the data for user, for certain email, just make you second query fetch data by email and remove the first one:
SELECT * FROM users WHERE email='$email';
And don't forget to escape your input, because it's in cookie. Or, use prepared statements as suggested.
Your query is not valid, you should rewrite it with the following and make sure your you have mysqli_real_escape_string of the $email value before you put it into queries:
SELECT user_id FROM users WHERE email='$email'
Better approach is to rewrite your queries using MySQLi prepared statements:
Here how to get the $id value:
$stmt = mysqli_prepare($dbc, "SELECT user_id FROM users WHERE email = ?");
mysqli_stmt_bind_param($stmt, "s", $email);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $id);
mysqli_stmt_fetch($stmt);
You wrote
mysqli_query($dbc,"SELECT user_id FROM users WHERE email=$email");
that is similar to
mysqli_query($dbc,"SELECT user_id FROM users WHERE email=example#example.com");
but it should be
mysqli_query($dbc,"SELECT user_id FROM users WHERE email='example#example.com'");
so you have to do this
mysqli_query($dbc,"SELECT user_id FROM users WHERE email='$email'");
or better
mysqli_query($dbc, 'SELECT user_id FROM users WHERE email=\'' . $email . '\'');
Beside this minor bug
You should be aware of SQL injection if someone changes the value of your cookie.
Hello I’m working on a project (I’m a total newbie), here ‘s how the project goes…
I’ve created a Create User page, the user puts in the credentials and click on Create Account.
This redirects to another page (process.php) where all MySQL queries are executed-
Note: ID is set to Auto Increment, Not Null, Primary Key. All the data is inserted dynamically, so I don’t know which Username belongs to which ID and so on.
$query = “INSERT INTO users (Username, Something, Something Else) VALUES (‘John’, ‘Smith’, ‘Whatever’ )”
Everything gets stored into the “users” table.
Then it gets redirected to another page (content.php) where the User can review or see his/her credentials.
The problem is, I use SELECT * FROM users and mysql_fetch_array() but it always gives me the User with ID = 1 and not the current User (suppose user with ID = 11). I have no idea how to code this.
There are suppose 50 or more rows,
how can I retrieve a particular row if I don’t know its ID or any of its other field’s value?
You may use:
mysql_insert_id();
Get the ID generated in the last query. Reference: http://us1.php.net/mysql_insert_id
This function return the ID generated for an AUTO_INCREMENT column by the previous query on success, 0 if the previous query does not generate an AUTO_INCREMENT value, or FALSE if no MySQL connection was established.
Now you have the id, add that to your WHERE clause.
Note: It would be better if you use mysqli.
You are using mysql_fetch_array() just once, so it is getting you just one row.
what you are writing:
<?php
include('connection.php'); //establish connection in this file.
$sql = "select * from users";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
echo(row['id']);
?>
What should be there to fetch all the rows:
<?php
include('connection.php'); //establish connection in this file.
$sql = "select * from users";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
echo(row['id']);
}
?>
Now, what you need, is to get the user id of the registered user at that time.
For that, you need to create a session. Add session_start(); in your process.php and create a session there. Now to get the last id you have to make a query:
select *
from users
where id = (select max(id) from users);
Now this will give you the last id created. Store that in a session variable.
$_SESSION['id']=$id;
Now, on content.php add this:
session_start();
echo($_SESSION['id']);
You have to use WHERE:
SELECT * FROM users WHERE ID = 11
If you dont use WHERE, it will select all users, and your mysql_fetch_assoc will get you one row of all (ie. where ID = 1).
PS: mysql_* is deprecated, rather use mysqli_*.
Using mysql_ commands:
$query = "INSERT INTO users (`Username`, `Something`, `Something Else`) VALUES ('John', 'Smith', 'Whatever' )";
$result = mysql_query($query) or die( mysql_error() );
$user_id = mysql_insert_id();
header("Location: content.php?id=".$user_id);
Or another way to pass $user_id to your next page
$_SESSION['user_id'] = $user_id;
header("Location: content.php");
Using mysqli_ commands:
$query = "INSERT INTO users (`Username`, `Something`, `Something Else`) VALUES ('John', 'Smith', 'Whatever' )";
$result = mysqli_query($dbConn, $query) or die( printf("Error message: %s\n", mysqli_error($dbConn)) );
$user_id = mysqli_insert_id($dbConn);
I have written a code to check whether the username exists in the database or not. It seems to return that there is no such username exists even if there's a same username existing.
$conu=mysqli_connect("localhost","db_user","db_pass","db_name");
$result = mysql_query("SELECT 1 FROM member WHERE username = $username");
if ($result && mysql_num_rows($result) > 0) {
$user_err = "<i><span class='error'>Usernme already exists</span></i>";
$errflag = true;
}
elseif(preg_match("/^[0-9a-zA-Z_]{5,}$/", $username) === 0) {
$user_err = "<i><span class='error'>Usernme must be bigger than 5 chararacters and can contain only digits, letters and underscore</span></i>";
$errflag = true;
}
Try
mysql_query("SELECT username FROM member WHERE username = '$username' LIMIT 1;");
SELECT 1 is not actually using the database; it's always returning 1, hence why your result is always the same regardless of the contents of the member table.
Usernames I take it are some sort of varchar? If that is the case, you might want to put its value in quotes:
$result = mysql_query("SELECT `username` FROM `member` WHERE `username` = '".$username."' LIMIT 1;");
your query is subject to sql injections btw.
At first, you are trying to return a column that probably doesn't exist: "1"
Second, I hope that you are cleaning the $username or else you are allowing anyone to inject your database.
The correct query is
mysql_query("SELECT * FROM `member` WHERE `username`='$username'");
You are using mysqli to connect, but mysql to perform your query.
When you SELECT 1 FROM member WHERE username = $username, the result will always be 1.
You need to put $username in the query in quotes. Something like SELECT username FROM member WHERE username = '$username'.
You forgot to include the part of the code for when there is no such username in your posting.
I want have an insert query, but before inserting I check whether the username and email are used by someone else. If used, I want to cancel insert query and echo a message to say whether username or email is in use.
Here my code:
$sql = "SELECT 1 FROM user WHERE username='".$_POST['username']."'";
if(!$result = mysql_query($sql))
die(mysql_error());
while($row = mysql_fetch_array($result))
die('This username is already exists');
$sql = "SELECT 2 FROM user WHERE email='".$_POST['email']."'";
if(!$result = mysql_query($sql))
die(mysql_error());
while($row = mysql_fetch_array($result))
die('This email address is already exists');
$sql = "insert into user (username,email,password,tel,type) values ('".$_POST['username']."','".$_POST['email']."','".$_POST['password']."','".$_POST['telnumber']."','member')";
if(!mysql_query($sql))
die(mysql_error());
I want these three sql statements in one. It can be either using cases or something else that you suggest. So,
Is it possible to zip this code into one sql query?
As a result what I need is
sql = "sql_query"
if(!$result = mysql_query($sql))
die(mysql_error());
while($row = mysql_fetch_array($result)){
if($row['result']==1)
die('This username is already exists');
else if($row['result']==2)
die('This email is already exists');
}
die('you have succesfully registered');
thanks for any advice.
While I suggest you follow #cularis' answer, you may be interested in the following alternative:
Give email and username the UNIQUE constraint, by creating a unique index for both of these.
run your INSERT query, and if this fails... (due to duplicate keys)
run the suggested combined SELECT, to determine which field existed (username or email)
You can combine the first two queries like this:
$sql = "SELECT * FROM user WHERE username='".$_POST['username']."' OR email='".$_POST['email']."'";
Have look at mysql_real_escape string to sanatize your input.
Assuming you don't care about a more specific error case you could probably just do the following:
$sql = "SELECT * FROM user WHERE username='".$_POST['username']."' OR email='".$_POST['email']."'";
if(!$result = mysql_query($sql))
die(mysql_error());
while($row = mysql_fetch_array($result))
die('The username or email address is already being used');
$sql = "insert into user (username,email,password,tel,type) values ('".$_POST['username']."','".$_POST['email']."','".$_POST['password']."','".$_POST['telnumber']."','member')";
if(!mysql_query($sql))
die(mysql_error());
This isn't the best of designs if you're looking for, as I said, specific error cases. So if you are okay with just telling the person there is an error that one or both are in use then that should work.
I am not sure as I am very rusty in PHP/MySQL but I assume that if such cases of both exist then multiple rows may be returned and I forget exactly how mysql_fetch_array works but I assume it's an array of all results valid for the query so you should be set. As long as the array exists, you know there was a hit in the db.