I am a little confused about how $query works and how I can find a value... Say I have a checkuser.php script. The purpose here is to echo "Correct" if the user already exists. I have the columns (username, password, email). What I want to know is how can I search the column username for value $username? This is what I have currently:
$query = sprintf("SELECT * FROM users WHERE CONCAT(username) LIKE '$u'");
$result = mysql_query($query);
if(mysql_num_rows($result) != 1)
echo "Username Not Found";
Thanks!
This should work. However, I didn't test it:
$query = "SELECT * FROM users WHERE username = '$u'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0)
echo "Username Not Found";
In your query, you do not need to use the sprintf() function at all. an SQL query is inserted as a regular string.
Furthermore you don't need to use CONCAT() SQL function either.
Then if you want to check against an exact string you can just compare with the = operator instead of using SQL LIKE statement.
I haven't tested it, but this should work:
$q=mysql_query("select ysername from user where username='$u'");
$count=mysql_num_rows($q);
If ($count>0) { echo "usename fount";};
Related
I've found many similar questions regarding this but anything I try won't work.
I'm trying to run a MySQL query using the variable $epost. When I echo this variable it displays correctly, but the query returns nothing. Entering a fixed value for $epost like:
$epost='email#email.com'
Returns the correct query from the database.
$epost=mysqli_real_escape_string($conn,$_POST['email']);
echo $epost;
$sql = "SELECT memberID FROM Member WHERE email = '$epost' limit 1";
$result = mysqli_query($conn,$sql);
$row = mysqli_fetch_assoc($result);
echo $row["memberID"];
So I am trying to develop an app and I need an API, so I am trying now PHP in order to pass my variables from the app to the MYSQL. I am trying with $_GET first in order to see if everything works fine. I tried to pass variables to the database through MYSQL Workbench and then from the app and worked fine. But, when I emptied the table and tried again it didn't work! So I am guessing that my loop doesn't respond well to the fact that my table is empty(?)
This is the code that checks for the email and username if exists and if not insert the variables:
$result = 'notSet';
$query=mysql_query("SELECT * FROM project");
while ($row = mysql_fetch_assoc($query)) {
if(strcmp($row['email'],$email)==0){ //strcmp uses two strings and it returns an integer, if 0 then no differences if more than 0 then there are
$result = 'Email exists';
}else{
if(strcmp($row['username'],$username)==0){
$result = 'Username exists';
}else{
//encryption
$insert = mysql_query("INSERT INTO project VALUES ('$userid', '$fullname','$username','$password','$course','$year','$age','$email')");
$result = 'Registered';
session_start();
$session = session_id();
$SESSION['username']=$username;
}
}
}
Any ideas??
Your table is empty. $query is returning false. Because of this your loop is not executed. You should change the code like this:
if($query){
while(){
//check username and email
}
}
else{
// execute insert query
}
Can you try this code:
$result = 'notSet';
$query = mysql_query("SELECT * FROM project WHERE email = '$email' OR username = '$username' ");
if(mysql_num_rows($query) === 0 ){
$insert = mysql_query("INSERT INTO project VALUES ('$userid', '$fullname','$username','$password','$course','$year','$age','$email')");
$result = 'Registered';
session_start();
$session = session_id();
$SESSION['username']=$username;
}
else{
$result = 'Username or Email exists';
}
We should add single quotes ' only if field type is not integer type. For eg if userid field is integer type and rest of fields are not integer type then query will be
$insert = mysql_query("INSERT INTO project VALUES ($userid, '$fullname','$username','$password','$course','$year','$age','$email')") or die(mysql_error());
thanks
First: you should switch to PDO or mysqli, because the mysql_* functions are deprecated. Please follow the links in Shais comment.
To get the INSERT done, you've got to change your logic. With your code right now, it will never be executed for an empty resultset. You could do it so:
$query=mysql_query("SELECT * FROM project");
if (mysql_num_rows($query) > 0) {
// we've got results, let's loop through the resultset
while($row = mysql_fetch_assoc($query)) {
// do something with the result
}
}
else {
// we've got no results,
// do the insert
}
mysql_query will return a resource for SELECT type queries. A resource evaluates in PHP to true. You can use mysql_num_rows() to check, whether your resultset is not empty.
Excerpt from the linked manual:
Use mysql_num_rows() to find out how many rows were returned for a
SELECT statement
PS: Please consider the content of the red box.
<?php
$query=mysql_query("INSERT INTO project set id=$userid,
'fullname'=$fullname,
'username'=$username,
'password'=$password,
'course'=$course,
'year'=$year,
'age'=$age,
'email'=$email
");
?>
I am trying to show a user's data from my mysql table by selecting them by username using the
following code, however it outputs 'no selection'. Important to note here that when I replace the '$username' by the real username from the database it works fine. Here is the complete code.
<?php
mysql_connect("localhost", "root", "")or die("cannot connect");
mysql_select_db("my_databse")or die("cannot select DB");
mysql_query("SET CHARACTER SET 'utf8';")or die(mysql_error());
$username=$_POST['username'];
$username = mysql_real_escape_string($username);
$sql="SELECT * FROM cv_users WHERE username LIKE '$username'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if( mysql_num_rows( $result ) === 1 ){
$row = mysql_fetch_assoc( $result );
$email = $row[ 'email' ];
$cv_txt = $row[ 'cv_txt' ];
$cv_txt = mysql_real_escape_string($cv_txt);
}
else {
echo 'no selection';
}
?>
<?php
echo $row[ 'cv_txt' ];
?>
Your problem is you are looking for 1 result and also you are adding an extra '' around the php string var you can remove this '.
Your current query :
$sql="SELECT * FROM cv_users WHERE username LIKE '$username'";
This states that you will take everything where there is a username LIKE $username
This is also incorrect as you are not considering the php var inside the string.
You could change this to
$sql="SELECT * FROM cv_users WHERE username LIKE '".$username."'";
OR
$sql="SELECT * FROM cv_users WHERE username = '".$username."'";
This will return 1 user if the username matches and if it does not match there will be no results at all.
This will clean up on the later :
if( mysql_num_rows( $result ) === 1 ){
There is code duplication here when you are already defining $count as mysql_num_rows( $result.
Debugging should be done when running into issues like this, echoing the SQL query in your page then executing that directly into MySQL would produce the error for you.
Your issue is that you are looking for an anything that matches the username supplied.
$sql = "SELECT * FROM cv_users WHERE username LIKE '$username'";
What you should be doing is fetching the data where the username is as supplied:
$sql="SELECT * FROM cv_users WHERE username = '{$username}'";
Now this would be done a whole lot easier with PDO (see footnotes)
$db = new PDO("...");
$statement = $db->prepare("SELECT * FROM cv_users WHERE username = :username");
$statement->execute(array(':username' => $username));
$row = $statement->fetch(); // Use fetchAll() if you want all results, or just iterate over the statement, since it implements Iterator
I won't spoon-feed you all the code, the rest is up to you in your implementation :)
Footnotes
The whole php mysql_* api is depreciated and you should avoid using it at all.
This extension is deprecated as of PHP 5.5.0, and is not recommended
for writing new code as it will be removed in the future. Instead,
either the mysqli or PDO_MySQL extension should be used. See also the
MySQL API Overview for further help while choosing a MySQL API.
You should use either of the following two:
PDO
MySQLi
you need to understand the difference between " and '.
Simply put, the text between " will be parsed by the PHP-interpreter, while text between ' will just be text.
In your example MYSQL will search for a user with the username '$username' instead of searching for the value of the variable $username.
But in your case $username needs to be in quotes, otherwise MYSQL won't work. And here is how you do it:
$sql="SELECT * FROM cv_users WHERE username LIKE '".$username."'";
Hope this helps.
Are you sure php gets the username correctly? Maybe you can first try to echo the username(or debug), so you are certain you get the username.
It seemed that the problem is with the Post method, As I changet it to get it worked fine. Thanks for all of you
I am just trying to write a simple script that verifies the username and password of a user that has attempted to login...and then starts a session. However, I am running into some trouble.
When I try to run the script below, SUCCESS does not print out. As if the username and password is incorrect, however, I know for a fact that the username and passwords entered are, in fact, correct.
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query("SELECT * FROM users WHERE username='.$username.' AND password='.$password.'");
while($row = mysql_fetch_array($result)){
echo 'SUCCESS';
}
When I try to run the script below however, success prints out twice (which is the number of sample users I have in my db so far), which is correct.
I am guess I have a problem with the AND mySQL query above, however, it seems correct to me... is there a problem with my first query above? if not, than what else might be the problem?
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query("SELECT * FROM users");
while($row = mysql_fetch_array($result)){
echo 'SUCCESS';
}
You're parsing variables, not concatenating them, you don't need the ..
"SELECT * FROM users WHERE username='$username' AND password='$password'"
username is a protected keyword, try this:
$result = mysql_query("SELECT * FROM `users` WHERE `username`='$username' AND `password`='$password'");
Ignoring the gaping SQL injection vulnerability, you're constructing your query string incorrectly:
$result = mysql_query("SELECT * FROM users WHERE username='.$username.' AND password='.$password.'");
^ ^
You're still in "string mode" where the indicated periods are (and for the password section too), so you're embedding literal periods into your query string, instead of doing string concatenation.
Remote the periods, and you'll be better off (but still vulnerable to sql injection):
$result = mysql_query("SELECT * FROM users WHERE username='$username' AND password='$password'");
Try this instead:
$result = mysql_query("SELECT * FROM users WHERE username=\"$username\" AND password=\"$password\"");
Obviously, this isn't a great way of inserting data. You should look at mysqli to insert data as a minimum.
try this line instead:
$result = mysql_query("SELECT * FROM `users` WHERE `username`='".$username."' AND `password`='".$password."'");
Notice the extra "'s I've added in. before it was looking for '.$username.'
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.