MYSQL QUERY FALSE although syntax is right - php

Im a beginner in PHP learning how to combine PHP with mysql. I successfully made my login page, now im making my register page. Im now in the process of checking to see if the query is TRUE before i continue to program but i keep getting "false" when i do var_dump on the query. Im checking to make sure username don't = an existing one, than i'll move on to do the same for email.
<?php
require 'main.inc.php';
if(!checkuser()){
if(isset($_POST['register'])){
//Returning the value the user put if any
$username = $_POST['username'];
$password = $_POST['password'];
$password_again = $_POST['password_again'];
$email = $_POST['email'];
//CHeck to see if the user left any blank spaces
if( !empty($username) && !empty($password) && !empty($password_again) && !empty($email)){
if($password != $password_again){
echo '<strong>Password did not match</strong>';
}
else{
//Telling PHP what we want to get
$query = "SELECT username FROM users WHERE username=$username";
//Sending out the Query
$query_run = mysql_query($query);
var_dump($query_run);
}
}
else{
echo '<strong>Please Fill Out All Forms</strong>';
}
}
?>
<form action='register.php' method='POST'>
<p><input type='text' name='username' placeholder='username' /></p>
<p><input type='password' name='password' placeholder='Password' /></p>
<p><input type='password' name='password_again' placeholder='Confirm Password' /></p>
<p><input type='text' name='email' placeholder='Email' /></p>
<p><input type='submit' name='register' value='Create Your Account' /></p>
</form>
<?php
}
else {
echo 'You are already registered';
}
?>

$query = "SELECT username FROM users WHERE username='$username';
use this instead...

Related

How do I write my code to allow a user to change password or change username?

A part of a website I am making gives the option to the user to change their password. I have configured this code and it works fine.
I now want to add a form to the same page, that gives the user an option to change their USERNAME instead. (Individually, so they change their username but don't change the password).
Do I need to repeat the exact same following code and paste it beneath it, obviously adapting particular words to be for the username not password, or is there a way I can ADD to the existing code so that its one single processing code? How do I do this? So for example the first line:
if ($submit == 'Change Password') {,
in my head in English language, I'd like the code to say IF 'change password' OR the 'change username' button is submitted... do the following code etc.
//processing code
<?php
require_once('checklog.php');
require_once('functions.php');
// Grab the form data
$submit = trim($_POST['submit']);
$password = trim($_POST['password']);
$newpassword = trim($_POST['newpassword']);
$repeatpassword = trim($_POST['repeatpassword']);
// Create some variables to hold output data
$message = '';
// Start to use PHP session
session_start();
if ($submit == 'Change Password') {
include_once('connect.php');
mysqli_select_db($db_server, $db_database) or die("Couldn't find db");
//clean the input now that we have a db connection
$password = clean_string($db_server, $password);
$newpassword = clean_string($db_server, $newpassword);
$username = $_SESSION['username'];
$repeatpassword = clean_string($db_server, $repeatpassword);
if ($password && $newpassword) {
if ($repeatpassword == $newpassword) {
if (strlen($newpassword) > 25 || strlen($newpassword) < 6) {
$message = "Password must be 6-25 characters long";
} else {
// check whether username exists
$password = salt($password);
$query = "SELECT username FROM users WHERE username='$username' and password='$password'";
$result = mysqli_query($db_server, $query);
//if theres a result change password to new password
if ($row = mysqli_fetch_array($result)) {
$newpassword = salt($newpassword);
$repeatpassword = salt($repeatpassword);
//update password
$query = "UPDATE users SET password='$newpassword' WHERE username='$username'";
mysqli_query($db_server, $query) or die("Update failed. " . mysqli_error($db_server));
$message = "<strong>Password change successful!</strong>";
} else {
$message = "User account not found.";
}
mysqli_free_result($result);
}
} else {
$message = "Password must match";
}
} else {
$message = "Please enter all fields";
}
include_once('db_close.php');
}
include_once('header_logged.php');
?>
// the forms to change the password or username
!--change password form -->
To change your Password:
<form method="post" action="changepassword.php">
Current password: <input type='password' name='password'>
<br>
<br>
New Password: <input type='password' name='newpassword'>
<br>
<br>
Repeat New Password: <input type='password' name='repeatpassword'>
<input type='submit' name='submit' value='Change Password'>
<input type='reset' name='reset' value='Reset'>
</form>
<p><strong><?php
echo $message;
?></strong></p>
<!--change username form -->
To change your Username:
<form method="post" action="changepassword.php">
Current Username: <input type='username' name='username'>
<br>
<br>
New Username: <input type='username' name='newusername'>
<br>
<br>
Repeat New Username: <input type='username' name='repeatusername'>
<input type='submit' name='change' value='Change Username'>
<input type='reset' name='reset' value='Reset'>
</form>
Thanks for any help, very much appreciated.
use this:
if(isset($_POST['submit']) || isset($_POST['change'])){
//write your code here
}

Browser executes most, but not all of my php

I was wondering if someone could give me a hand. My browser is executing most of my php code, but when it gets to certain line, it prints the code instead of executing it.
My code is:
<!DOCTYPE html>
<html>
<body>
<?php
//Display registration form
function register_form(){
$date = date('D, M, Y');
echo <form action='?act=register' method='post'>
Username: <input type='text' name='username' size='30'><br>
Password: <input type='password' name='password' size='30'><br>
Confirm your password: <input type='password' name='password_conf' size='30'><br>
Email: <input type='text' name='email' size='30'><br>
<input type='hidden' name='date' value='$date'>
<input type='submit' value='Register'>
</form>;
}
?>
<?php
//Register users data.
function register(){
//Connecting to database
$connect = mysql_connect("localhost", "username" "password");
if(!$connect){
die(mysql_error());
}
//Selecting database
$select_db = mysql_select_db("database", $connect);
if(!$select_db){
die(mysql_error());
}
?>
<?php
//Collecting info
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
$pass_conf = $_REQUEST['password_conf'];
$email = $_REQUEST['email'];
$date = $_REQUEST['date'];
//Check input fields
if(!empty($username)){
die("Please enter your username!<br>");
}
if(!empty($password)){
die('Please enter your password!<br>');
}
if(!empty($pass_conf)){
die("Please confirm your password!<br>");
}
if(!empty($email)){
die("Please enter your email!");
}
?>
<?php
//Check username availability
$user_check = mysql_query("SELECT username FROM users WHERE username='$username'");
$do_user_check = mysql_num_rows($user_check);
//Check if email availability
$email_check = mysql_query("SELECT email FROM users WHERE email='$email'");
$do_email_check = mysql_num_rows($email_check);
//Display errors
if($do_user_check > 0){
die("Username is already in use!<br>");
}
if($do_email_check > 0){
die("Email is already in use!");
}
//Check if passwords match
if($password != $pass_conf){
die("Passwords don't match!");
}
?>
<?php
//Register user
$insert = mysql_query("INSERT INTO users (username, password, email) VALUES ('$username', '$password', '$email')");
if(!$insert){
die("There's little problem: ".mysql_error());
}
echo $username.", you are now registered. Thank you!<br><a href=login.php>Login</a>" ;
}
?>
<?php
switch($act){
default;
register_form();
break;
case "register";
register();
break;
}
?>
</body>
</html>
It prints a lot of the closing ?> tags, but if I remove the tag as well as its opening counterpart, it prints all the code that was between. I've been stuck on this for the last few days and really need some help. Thanks in advance.
UPDATE
I figured it out. I was executing from the directory instead of the address. (not sure if I worded that right). So instead browser pointing to registration page from "http://localhost:port/register.php" it was pointing to "file:///C:/xampp/htdocs/register.php"
Put double quotes around anything you to be echoed since there are single quotes used inside the strings. A simple example:
Ps. you have some other syntax errors as well, but if only you care.
One of them on line 45: $connect = mysql_connect("localhost", "username" "password"); this is definitely not the way it should be. Even if it was;
Notice the missing comma after `"username". Should have been like:
$connect = mysql_connect("localhost", "username", "password");
For the current problem, try this:
<?php
//Display registration form
function register_form(){
$date = date('D, M, Y');
echo "<form action='?act=register' method='post'>
Username: <input type='text' name='username' size='30'><br>
Password: <input type='password' name='password' size='30'><br>
Confirm your password: <input type='password' name='password_conf' size='30'><br>
Email: <input type='text' name='email' size='30'><br>
<input type='hidden' name='date' value='$date'>
<input type='submit' value='Register'>
</form>;";
}
?>
You need to put double quotes around your echoed strings. (double, since you use single quotes inside your tags). If you remove the php-tags, it will be interpreted as just HTML i.e. it will just be sent out to the browser.
If for some reason you hate quotes, you might like to do it as a here document:
echo <<<EOF
<form action='?act=register' method='post'>
Username: <input type='text' name='username' size='30'><br>
...
EOF
There's also at least one missing comma in you code, which will keep that part from executing (in mysql_connect).
B.t.w. you shouldn't use the mysql_*-type functions anymore. They are marked deprecated and are prone to make your code succeptible to SQL injection attacks. I recommend working into PDOs.
And just for wiw, as someone already mentioned in the comments it is not the browser that executes this code. PHP is interpreted by the webserver. The only scripting language that is actually executed browserside is still javascript (correct me if I'm wrong.).

Simple login with PHP check against Microsoft Access

i'm new to PHP. I created a microsoft access database with user A and pw 123 (testing). I tried to find on the website but unfortunately I can't find any that can actually lead me to authenticate against MS Access, most of the website is purely about SQL, which is what i really do not want, please help!
Currently here are my codes
Login.php
<html>
<body>
<?php
session_start();
// dBase file
include "database.php";
<form id='login' action='login.php' method='post' accept-charset='UTF-8'>
<fieldset >
<legend>Please log in your employee ID and Password to apply for leave.</legend>
<input type='hidden' name='submitted' id='submitted' value='1'/>
<div class='short_explanation'>* required fields</div>
<br>
<label for='username'>UserName*:</label>
<input type='text' name='username' id='username' maxlength="50" />
<br>
<label for='password'>Password*: </label>
<input type='password' name='password' id='password' maxlength="50" />
<br><br>
<input type='submit' name='Submit' value='Submit' />
</fieldset>
Database.php
<?php
// This part sets up the connection to the
// database (so you don't need to reopen the connection
// again on the same page).
$conn=odbc_connect("employee","","") or die (odbc_errormsg());
if (!$conn )
{
exit
("Error connecting to database: ".$conn);
}
// Then you need to make sure the database you want
// is selected.
$sql = "SELECT * FROM empTable";
$rs=odbc_exec($conn,$sql);
?>
How do i continue from here? Thank you! Please note that I can only authenticate everything with MS Access 2003.
session_start();
// Get the data collected from the user
$Username =$_POST["username"];
$Password =$_POST["password"];
if (!$conn = new COM("ADODB.Connection"))
exit("Unable to create an ADODB connection");
$strConn = "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=" . realpath("DATABASEFILE");
$conn->open($strConn);
$strSQL = "SELECT username, password FROM accounts WHERE username = '$Username' AND password = '$Password'";
$rs = $conn->execute($strSQL);
if (!$rs->EOF)
{
if ( $rs->Fields["Username"]->value
&& $rs->Fields["Username"]->value == $Username
&& $rs->Fields["Password"]->value
&& $rs->Fields["Password"]->value == $Password
)
{
$_SESSION["authenticatedUser"] = $Username;
// Relocate to the logged-in page
header("Location: loggedon.php");
}
}
else
{
$_SESSION["message"] = "Login Error as $Username. " ;
header("Location: admin.php");
}

PhP Login/Register system

I found this good tutorial on creating a login/register system using PhP and MySQL.
The forum is around 5 years old (edited last year) but it can still be usefull.
Beginner Simple Register-Login system
There seems to be an issue with both login and register pages.
<?php
function register_form(){
$date = date('D, M, Y');
echo "<form action='?act=register' method='post'>"
."Username: <input type='text' name='username' size='30'><br>"
."Password: <input type='password' name='password' size='30'><br>"
."Confirm your password: <input type='password' name='password_conf' size='30'><br>"
."Email: <input type='text' name='email' size='30'><br>"
."<input type='hidden' name='date' value='$date'>"
."<input type='submit' value='Register'>"
."</form>";
}
function register(){
$connect = mysql_connect("host", "username", "password");
if(!$connect){
die(mysql_error());
}
$select_db = mysql_select_db("database", $connect);
if(!$select_db){
die(mysql_error());
}
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
$pass_conf = $_REQUEST['password_conf'];
$email = $_REQUEST['email'];
$date = $_REQUEST['date'];
if(empty($username)){
die("Please enter your username!<br>");
}
if(empty($password)){
die("Please enter your password!<br>");
}
if(empty($pass_conf)){
die("Please confirm your password!<br>");
}
if(empty($email)){
die("Please enter your email!");
}
$user_check = mysql_query("SELECT username FROM users WHERE username='$username'");
$do_user_check = mysql_num_rows($user_check);
$email_check = mysql_query("SELECT email FROM users WHERE email='$email'");
$do_email_check = mysql_num_rows($email_check);
if($do_user_check > 0){
die("Username is already in use!<br>");
}
if($do_email_check > 0){
die("Email is already in use!");
}
if($password != $pass_conf){
die("Passwords don't match!");
}
$insert = mysql_query("INSERT INTO users (username, password, email) VALUES ('$username', '$password', '$email')");
if(!$insert){
die("There's little problem: ".mysql_error());
}
echo $username.", you are now registered. Thank you!<br><a href=login.php>Login</a> | <a href=index.php>Index</a>";
}
switch($act){
default;
register_form();
break;
case "register";
register();
break;
}
?>
Once pressed the register button the page does nothing, fields are erased and no data is added inside the database or error given.
I tought that the problem might be the switch($act){ part so I removed it and changed the page using a require
require('connect.php');
where connect.php is
<?php
mysql_connect("localhost","host","password");
mysql_select_db("database");
?>
Removed the function register_form(){ and echo part turning it into an HTML code:
<form action='register' method='post'>
Username: <input type='text' name='username' size='30'><br>
Password: <input type='password' name='password' size='30'><br>
Confirm your password: <input type='password' name='password_conf' size='30'><br>
Email: <input type='text' name='email' size='30'><br>
<input type='hidden' name='date' value='$date'>
<input type='submit' name="register" value='Register'>
</form>
And instead of having a function register(){ I replaced it with a if($register){
So when the Register button is pressed it runs the php code, but this edit doesn't seem to work either. So what can the problem be? If needed I can re-add this code on my Domain
The login page has the same issue, nothing happens when the button is pressed beside emptying the fields.
Did you echo the $_REQUEST data and checked if they are being grabbed correctly?
<?php
if (!isset($_POST))
register_form();
else
register();
Change switch part with the code above.
Nevermind guys I found a different tutorial with video demonstration. Works like a charm.
My Page
Added the Login/Register system.
Tutorial if anyone needs it. Thanks for answering tho I appreciate it and will +1 them.

Need PHP HTML help with register form

here is some code that I plan on using in a registration form for my site
<?php
session_start();
include ("includes/config.php");
if ($Authenticated == False) {
?>
<div id="register">
<form action="index.php?page=register" method="post">
<lable id="registerStuff"> Name: </>
<input id="registerIn" type='text' name='name' maxlength="20" />
<br/>
<lable id="registerStuff"> Surname: </>
<input id="registerIn" type='text' name='surname' maxlength="20" />
<br/>
<lable id="registerStuff"> Username: </>
<input id="registerIn" type='text' name='username' maxlength="20" />
<br/>
<lable id="registerStuff"> Password: </>
<input id="registerIn" type='password' name='password' maxlength="20" />
<br/>
<lable id="registerStuff"> Retype Password: </>
<input id="registerIn" type='password' name='passwordcheck' maxlength="20" />
<br/>
<input type='submit' value='Register'>
<br/>
</form>
</div>
<?php
$name = mysql_real_escape_string($_POST['name']);
$surname = mysql_real_escape_string($_POST['surname']);
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string(md5($_POST['password']));
$passwordcheck = mysql_real_escape_string(md5($_POST['passwordcheck']));
if ($username OR $password OR $passwordcheck != null) {
if ($password == $passwordcheck) {
$query = "INSERT INTO users (name, surname, username, password) VALUES ('" . $name . "', '" . $surname . "', '" . $username . "', '" . $password . "')";
$result = mysql_query($query);
if (!$result) {
echo "Username wrong";
}
} else {
echo "passwords didnt match";
}
}
}
if ($Authenticated == True) {
header("Location: index.php");
}
?>
I cant seem to get proper error messages working, I need to check if the 2 passwords entered are identical, I also need to make sure that no blanks can be entered into the DB. If anyone could help me at all it would be much appreciated
You made quite a common mistake I guess. Most beginners seem to want to write as little code as possible. However, in this case that doesn't work. You will have to check each variable for emptiness.
Your code would be correct when you changed your if construct:
if ($username != "" AND $password != "" AND $passwordcheck != "") {
}
However, to make the code look a bit slighter, it's probably best to just use the function empty() that returns TRUE if the variable is empty:
if (!empty($username) AND !empty($password) AND !empty($passwordcheck)) {
}
Very interesting code you have there. I would suggest, before asking people here to write more than half of your script, to Google "PHP Login Script" - this is the number one result and the answer to your question.
$sql="SELECT * FROM $tbl_name
WHERE username='$myusername' AND password='$mypassword'";
$result=mysql_query($sql);
With that said, this is the incorrect way of doing it and you should look into prepared statements. Since you're starting off, you probably should start of with a security mindset.

Categories