This is me experimenting with PHP I'm new to it. I'm trying to see if a given username is already found in a mysql database here is my current code:
<?php
// $uname is the username I am trying to see if is the database
$uname = "djm";
//server info
$servuser = "root";
$servpass = "";
$db = "toob";
$server = "127.0.0.1";
//connecting to server
$db_handle = mysql_connect($server, $servuser, $servpass);
$db_found = mysql_select_db("toob", $db_handle);
//checking to see if ocnnected
if ($db_found) {
print("connected");
//defining my sql statement
$sql = "SELECT username FROM users WHERE username = $uname";
$result = mysql_query($sql);
if ($result) {
print("Yes");
} else {
print("No");
}
} else {
print("Can't connect to server");
}
I always prints no, i have managed to make to print yes by replacing :
$sql="SELECT username FROM users WHERE username = $uname";
$result=mysql_query($sql);
with
$sql="SELECT username FROM users WHERE username = 'djm'";
$result=mysql_query($sql);
However i need if to work off variables.
You're missing the quotes:
It's a good idea to escape the input before passing them as a mysql query.
Try:
$sql = "SELECT username FROM users
WHERE username = '". mysql_real_escape_string($uname)."'";
Currently, it will say "yes" if the query is executed successfully. Replace if ($result) with if(mysql_num_rows($result) > 0) if you're trying to check if the record exists.
Unrelated: mysql_* functions are now deprecated, and I'd suggest switching to mysqli or PDO.
Firstly you should escape all user input:
$username = mysql_real_escape_string($uname);
then you need to wrap SQL values in quotes:
$sql="SELECT username FROM users WHERE username = '$username'";
A bit away from your question; something on mysql referenced from php's website: "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."
You would be better off using mysqli
replace this
if ($result)
with
if(mysql_num_rows($result) > 0)
Related
I am getting the error on line 26 as shown by my browser.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "tut";
$conn = mysqli_connect($servername, $username, $password, $database);
if (!$conn) {
die("Database connection failed: ".mysqli_connect_error());
}
if (isset($_POST['register']))
{
$user = $_POST['username'];
$pass = $_POST['password'];
$pass2=$_POST['password1'];
if(empty($username)||empty ($password)||empty($password1)){
echo "Oops! Can't leave any field blank";
}
elseif($pass!=$pass2){
echo "Passwords don't match";
}
else{
$phash = sha1(sha1($pass."salt")."salt");
$sql=IF NOT EXISTS (SELECT * FROM users WHERE username = '$user')
INSERT INTO users (id, username, password) VALUES ('', '$user', '$phash')
ELSE
RAISERROR 'Username exists, please select a different one';
$result = mysqli_query($conn, $sql);
}
}
?>
Is this not a correct way of writing the IF NOT EXISTS statement. Also when I try to execute this directly in XAMPP I get Unrecognised SQL statement error!
This is how to do it, I have test it and it works:
$sql = "
INSERT INTO users (username, password)
SELECT * FROM (SELECT '$user', '$phash') AS tmp
WHERE NOT EXISTS (
SELECT username FROM users WHERE username = '$user'
) LIMIT 1;
";
This solution is inspired from this answer.
The problem is that you can not combine PHP and MySQL statement like you did, you need to encapsulate all MySQL statements in quote ".
What comes RAISERROR, it is not MySQL function, it belongs to Microsoft.
You could easily make php if statement that checks if $sql contain valid username and return your message. That part is left to your fantasy.
XAMPP has no thing to do with the error, it just a software that provides an Apache and MySQL installation for Windows.
Note: P.S. please learn to use parameterized queries, because your
code is vulnerable to SQL injection. thanks to #BillKarwin for mentioning this.
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 trying to create a login form in PHP. i am passing the username and password that user had entered and check weather that exist in the data base.
i have done the coding, but IF EXIST query does not return any result.
can any one help me to fix this. or give me a alternate idea.. Thank you...
<?php
$name= $_POST["usname"];
$pass = $_POST ["password"];
$connection = mysqli_connect("localhost","sathya","sathya","learning1");
//mysqli_query($connection,"INSERT INTO user (name, password) VALUES ('".$name."', '".$pass."')");
$result = mysqli_query($connection, "IF EXISTS(SELECT * FROM user WHERE name='".$name."'AND password='".$pass."')");
mysqli_close($connection);
echo "result ".$result;
if($result == True){
header("Location: logedin.php");
//redirect_to('logedin.php');
}else{
echo "not logged in installed";
}
?>
This is a late answer, but there are a few things you need to be made aware of. (Not taking away from the accepted answer).
You will need to use if(mysqli_num_rows($result) > 0) because your query will always be TRUE if the username matches and the password does NOT, and vice-versa.
You are better off using mysqli_num_rows() rather than using if($result == True)
Sidenote: Consult my footnotes regarding password storage and SQL injection.
<?php
$DB_HOST = "xxx";
$DB_NAME = "xxx";
$DB_PASS = "xxx";
$DB_USER = "xxx";
$db = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($db->connect_errno > 0) {
die('Connection failed [' . $db->connect_error . ']');
}
$name = $_POST["usname"]; // See footnotes about this
$pass = $_POST ["password"]; // See footnotes about this
$result = mysqli_query($db, "SELECT EXISTS(SELECT * FROM users WHERE username='".$name."' AND password='".$pass."')");
// Works just as well
// $result = mysqli_query($db, "SELECT * FROM users WHERE username='".$name."' AND password='".$pass."'");
if(mysqli_num_rows($result) > 0){
echo "Both match.";
}
else{
echo "Sorry, there was not a perfect match.";
}
Footnotes:
You can also use:
$result = mysqli_query($db, "SELECT * FROM users WHERE username='".$name."' AND password='".$pass."'");
Which does the same for SELECT EXISTS(SELECT * while using less characters.
or choose actual columns:
$result = mysqli_query($db, "SELECT username, password FROM users WHERE username='".$name."' AND password='".$pass."'");
I suggest that you use prepared statements and sanitize your inputs. Not doing so will leave you open to SQL injection.
Here are a few tutorials on (mysqli) prepared statements that you can study and try:
Tutorial one
Tutorial two
Tutorial three
Here are a few tutorials on PDO:
PDO tutorial one
PDO tutorial two
PDO tutorial three
Passwords
I also noticed that you are storing passwords in plain text. This is not recommended.
Use one of the following:
CRYPT_BLOWFISH
crypt()
bcrypt()
scrypt()
On OPENWALL
PBKDF2
PBKDF2 on PHP.net
PHP 5.5's password_hash() function.
Compatibility pack (if PHP < 5.5) https://github.com/ircmaxell/password_compat/
Other links:
PBKDF2 For PHP
I can't say anything about the PHP part, but the query will surely result in a syntax error.
IF whatever ... is only allowed in stored procedures or functions, not in single queries. You can however replace the IF with SELECT like
$result = mysqli_query($connection, "SELECT EXISTS(SELECT * FROM user WHERE name='".$name."'AND password='".$pass."')");
This query would return either 0 (if no entry exists) or 1 (if an entry exists). It's also a good idea to use EXISTS as it stops the query as soon as an entry was found and does not return the whole dataset.
You can try this beside using 'IF EXISTS' function--
$result = mysqli_query($connection, "SELECT * FROM user WHERE name='".$name."'AND password='".$pass."'");
$count=mysql_num_rows($result);
if($count==1) // $count=1 if any row is present with mathing username and pwd in db
{
echo "user already logged in";
}
else
{
echo "user not exist";
}
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)
im having problems in PHP with selecting Infomation from a database where username is equal to $myusername
I can get it to echo the username using sessions from the login page to the logged in page.
But I want to be able to select things like 'bio' and 'email' from that database and put them into variables called $bio and $email so i can echo them.
This is what the database looks like:
Any ideas?:/
You should connect to your database and then fetch the row like this:
// DATABASE INFORMATION
$server = 'localhost';
$database = 'DATABASE';
$dbuser = 'DATABASE_USERNAME';
$dbpassword = 'DATABASE_PASSWORD';
//CONNECT TO DATABASE
$connect = mysql_connect("$server", "$dbuser", "$dbpassword")
OR die(mysql_error());
mysql_select_db("$database", $connect);
//ALWAYS ESCAPE STRINGS IF YOU HAVE RECEIVED THEM FROM USERS
$safe_username = mysql_real_escape_string($X);
//FIND AND GET THE ROW
$getit = mysql_query("SELECT * FROM table_name WHERE username='$safe_username'", $connect);
$row = mysql_fetch_array($getit);
//YOUR NEEDED VALUES
$bio = $row['bio'];
$email = $row['email'];
Note 1:
Dont Use Plain Text for Passwords, Always hash the passwords with a salt
Note 2:
I used MYSQL_QUERY for your code because i don't know PDO or Mysqli, Escaping in MYSQL is good enought but Consider Using PDO or Mysqli , as i don't know them i can't write the code with them for you
Simplistic PDO examples.
Create a connection to the database.
$link = new PDO("mysql:host=$db_server;dbname=$db_name", $db_user, $db_pw, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Use the $link variable when creating (preparing) and executing your SQL scripts.
$stmt = $link->prepare('insert into `history` (`user_id`) values(:userId)');
$stmt->execute(array(':userId' => $userId));
Code below will read data. Note that this code is only expecting one record (with 2 data elements) to be returned, so I'm storing whatever is returned into a single variable (per data element), $webId and $deviceId.
$stmt = $link->prepare('select `web_id`, `device_id` from `history` where `user_id` = :userId');
$stmt->execute(array(':userId' => $userId));
while($row = $stmt->fetch()) {
$webId = $row["web_id"];
$deviceId = $row["device_id"];
}
From the picture I can see you are using phpMyAdmin - a tool used to handle MySQL databases. You first must make a connection to the MySql server and then select a database to work with. This is shown how below:
<?php
$username = "your_name"; //Change to your server's username
$password = "your_password"; //Change to your server's password
$database = "your_database" //Change to your database name
$hostname = "localhost"; // Change to the location of your server (this will prolly be the same for you I believe tho
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
$selected = mysql_select_db($database, $dbhandle)
or die("Could not select examples");
?>
Then you can write something like this:
<?php
$bio = mysql_query("SELECT bio FROM *your_database_table_name* WHERE username='bob' AND id=1");
?>
and
<?php
$email = mysql_query("SELECT email FROM *your_database_table_name* WHERE username='bob' AND id=1");
?>
Where *your_database_table_name* is the table in the database you selected which you are trying to query.
When I was answering your question, I was referencing this site: http://webcheatsheet.com/PHP/connect_mysql_database.php. So it might help to check it out as well.