I'm trying to look up user's username using $_GET but not actually seing the result of the query. Here's the code:
<?php
$host = "localhost";
$username = "root";
$password = "toor"; // :)
$database = "db";
$link = mysql_connect($host, $username, $password);
if(!$link){
exit('Could not connect to database: '. mysql_error());
}
$email = mysql_real_escape_string(htmlspecialchars(stripslashes($_GET["e"])));
$query = "SELECT username FROM cc_card WHERE email = '$email'";
$result = mysql_query($query);
if(mysql_num_rows($result)){
$user = mysql_fetch_assoc($result);
echo $user['username'];
} else {
echo "Something's wrong";
}
it's only returnung "Something's wrong". I wanted it to display the username field of the cc_card table where email = email. What am I doing wrong?
If you're getting "Something's wrong" from the posted code it means nowhere in the cc_card table does the email column match the email value you specify in your query.
You need to verify that the contents of your sanitized $email variable do, in fact, exist somewhere in the table. Try:
} else {
echo "Something's wrong";
var_dump($email);
}
To see the contents of the sanitized $email variable and manually query the database from the shell (or phpmyadmin or whatever) to find whether the value you're specifying exists or not. I'm betting it doesn't exist.
You'd better add the error check after the query.
if (!$result) {
die('Error: ' . mysql_error());
}
If no error, then it means there is no matched email in your database.
Related
If I want to add content to the table using "INSERT INTO", I don't get an error message and the table is not filled. I'm new with PHP. explanations would be nice. The database runs on XAMPP.
I don't know what to try. I've already used another table, but it doesn't work. The user should have full access to the table. The names also match.
<?php
$username = $_POST["username"];
$passwort = $_POST["passwort"];
$mail = $_POST["mail"];
$passwort2 = $_POST["passwort2"];
$pass = sha1($passwort);
$db = mysqli_connect("localhost", "phptest1", "o84XM5wxo65QBjkF", "phptest1");
if($passwort == $passwort2) {
echo "Password is correct.";
$db = "INSERT INTO user (Username, Mail, Password) VALUES ('$username', '$mail', '$pass')";
} else if(!($passwort == $passwot2)) {
echo "Password is not correct";
} ?>
The variable $db actually contains information about the connection. You cannot insert a query into your database the way you are trying to
You can use $db (in your case) in order to check whether the connection has been correctly established or not and then if everything works correctly you can user mysqli_query() to inject the query into your database.
You can do it like so:
<?php
if(isset($_POST['submit'])){ //You have to check if your submit button is pressed
$username = $_POST["username"];
$passwort = $_POST["passwort"];
$mail = $_POST["mail"];
$passwort2 = $_POST["passwort2"];
$pass = sha1($passwort);
$db = mysqli_connect("localhost", "phptest1", "o84XM5wxo65QBjkF", "phptest1");
if(!$db){
die('Connection could not be established! Check provided information');
}
if($passwort == $passwort2) {
echo "Password is correct.Inserting query now";
$query = "INSERT INTO user (Username, Mail, Password) VALUES ('$username', '$mail', '$pass')";
$result = mysqli_query($db, $query); //keep $result for debugging purposes.
} else {
die("Password is not correct");
} //no need for else if as there are only 2 conditions.
if(!$result){ //check if query was successful.
die('Query Error');
}
echo "Query Updated successfully";
}
?>
This code is really simplistic and for testing purposes only.
I just wanted to show you the way you can send queries to your database. You better use other encryption techniques i.e. crypt() and of course functions like mysqli_real_escape_string() when retrieving data from users, in order to avoid potential injection attacks.
Check this post for more info about preventing injections.
Hope that helps.
I'm having problems with my log in php file. I completed my sign up form, which takes data and saves it in a database. I now want to be able to log in with the data from the db. This is my first log in form and I'm not sure if I have all the things needed to make it run or if there's just an error. A list of what is needed to make this log in form will help, Thank you. I would also like to mention that I have more data in the DB other than email/password.
<?php
$db = mysql_connect("127.0.0.1:3307", "root", "", "test");
if(!$db){die('could not connect:'.mysql_error());}
echo'connected successfully';
if (isset($_POST['submit'])) {
$username = $_POST['Email'];
$password = $_POST['Password'];
$username = mysql_real_escape_string($Email);
$password = mysql_real_escape_string($Password);
$sql = "SELECT * FROM people WHERE Email ='$Email' AND
Password='$Password'";
mysql_select_db('test');
$result = mysql_query($sql);
$count = mysql_num_rows($result);
if($count == 1) {
echo "<script> alert('You Have Successfully Logged In')</script>";
exit();
} else {
echo "<script> alert('Invalid Username and/or Password')</script>";
}
}
mysql_close($db);
?>
You parse the POSTed EMAIL to your $username variable, but in your SELECT statement, you use a $Email variable. Perhaps this should have been your $Username variable instead, as this seems to hold your emailadress.
So your problem is in mixing of email and username. Correct this and your script should work.
I have a little problem. I have a register form. It works almost perfectly, I can check the value of the input fields, I can check weather do we have the same username in the db, but if everything is OK I cannot send the datas to my db. I use it as administrator/root, so I have the privileges. What is the problem? Please, help!
<?php
// declaring variables from input fields
$email = $_POST['email'];
$username=$_POST['username'];
$password=$_POST['password'];
$password2=$_POST['password2'];
function registration ($username, $email, $password) {
//new user registering
//return true or errormessage
//connecting to database, YEAH IT WORKS!
$connection = connecting_to_db();
//checking unique of username and IT WORKS!
$result = $connection->query("SELECT * FROM user WHERE username='".$username."'");
if (!$result) {
throw new Exception ('We couldnt query. Sorry.');
}
if ($result->num_rows>0) {
throw new Exception ('We have already this username! Choose something else!');
}
// if it is OK send it to the DB AND THIS IS NOT WORKING :-(
$result = $connection->query("INSERT INTO user VALUES'".$username."', shal('".$password."'), '".$email."')");
// I get alwasy this way and get this message.
if (!$result) {
throw new Exception ('We couldnt save your datas in our database. Try it later!');
}
return true;
}
?>
it looks like you have shal(letter L) instead of sha1(# one) in your insert query. print out your result from the query and you should see your issue.
Connect the database and the table then get the data
$servername = "localhost";
$username = "root";
$password = "";
I'm in the process of adding password hashing and SQL injection defenses into my Login system. Currently, I've ran into an error.
<?php
session_start(); //start the session for user profile page
define('DB_HOST','localhost');
define('DB_NAME','test'); //name of database
define('DB_USER','root'); //mysql user
define('DB_PASSWORD',''); //mysql password
$con = new PDO('mysql:host=localhost;dbname=test','root','');
function SignIn($con){
$user = $_POST['user']; //user input field from html
$pass = $_POST['pass']; //pass input field from html
if(isset($_POST['user'])){ //checking the 'user' name which is from Sign-in.html, is it empty or have some text
$query = $con->prepare("SELECT * FROM UserName where userName = :user") or die(mysqli_connect_error());
$query->bindParam(':user',$user);
$query->execute();
$username = $query->fetchColumn(1);
$pw = $query->fetchColumn(2);//hashed password in database
//check username and password
if($user==$username && password_verify($pass, $pw)) {
// $user and $pass are from POST
// $username and $pw are from the rows
//$_SESSION['userName'] = $row['pass'];
echo "Successfully logged in.";
}
else {
echo "Invalid.";
}
}
else{
echo "INVALID LOGIN";
}
}
if(isset($_POST['submit'])){
SignIn($con);
}
?>
In the above code, when I enter a valid username and password, the system prints out "Invalid". It could be a error in the password_verify() in the if statement(because if I remove it, I login successfully). I'm pretty sure I've done the preparing, binding and execution of the query properly? Does anyone know why it is doing this?
Thanks!
You're doing a SELECT *, and using fetchColumn, so the results are dependent of the returned columns order. You should either select the specific columns you need, or fetch the whole row as an associative array , and access it by column name.
There are other two issues that you should fix:
You shouldn't be using mysqli_connect_error() as you're using PDO. The right function would be $con->errorInfo().
You're defining some constants with the connection settings, yet you don't use them on the PDO() call, repeating the values instead.
Use
// it will be an array('name' => 'John', 'password_hash' => 'abcd')
// or FALSE if user not found
$storedUser = $query->fetch(PDO::FETCH_ASSOC);
instead of
$username = $query->fetchColumn(1);
$pw = $query->fetchColumn(2);
Because fetchColumn moves cursor of result. So first call extracts 1 column of first row, and second call will extract data from SECOND row!
I have a registration script that doesn't work. It used to work but then suddenly it stopped working. I dont know what I've done or what happend. I have tried for like an hour now to find out where the problem is, but I can't seem to find it.
What happens? When I click register I don't get any errors but it doesn't upload to the database:
When I type: $res = mysql_query($query) or die ("ERROR"); it displays ERROR so I think it's related to that code:
//=============Configuring Server and Database=======
$host = 'localhost';
$user = 'root';
$password = '';
//=============Data Base Information=================
$database = 'login';
$conn = mysql_connect($host,$user,$password) or die('Server Information is not Correct'); //Establish Connection with Server
mysql_select_db($database,$conn) or die('Database Information is not correct');
//===============End Server Configuration============
//=============Starting Registration Script==========
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['pass1']);
$email = mysql_real_escape_string($_POST['email']);
$country = mysql_real_escape_string($_POST['country']);
$rights = '0';
$IP = $_SERVER['REMOTE_ADDR'];
//=============To Encrypt Password===================
//============New Variable of Password is Now with an Encrypted Value========
$query = mysql_query("SELECT username FROM users WHERE username = '".$username."'");
if (mysql_num_rows($query) > 0)
{
echo 'Username or email already in use.';
}
else{
if(isset($_POST['btnRegister'])) //===When I will Set the Button to 1 or Press Button to register
{
$query = "insert into users(username,password,email,country,rights,IP,registrated)values('$username','$password','$email','$country',$rights,$IP,NOW())" ;
$res = mysql_query($query);
header("location:load.php");
}
}
I think you are getting the error because you are missing some quotes in your query for two columns wich really looks like not integers
'$email','$country',$rights,$IP,NOW())" //$rights and $ip doesn't have quotes
so your query would look like
"insert into users(username,password,email,country,rights,IP,registrated)values('$username','$password','$email','$country','$rights','$IP',NOW())"
Use mysql_error() in order to see what the error message is. If you haven't changed anything in the script then it's either your database structure has changed or your rights have.
Update:
You don't have quotes around your IP value, which is surprising because you said that query worked until now. Anyway you should also consider saving IPs the RIGHT way. Good luck!