Browser executes most, but not all of my php - 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.).

Related

INSERT INTO not working for Mysql database

I'm a novice at mysql having trouble with inserting fields. I have created a login form and a homepage form for users to enter personal details. The login form submitted to mysql database fine, but the personal details form refused to submit; only when I specified the same fields as the first form did the form submit. Obviously, I would like to add new data in the second form, and I would appreciate tips on organizing my database, which consists of a single table profile.It stores info on every user including fields: id,username,password,avatar,location,goal, etc.
Appreciate your help & patience. I will combine the info from the two forms into a user record eventually. Right now, though, I would like to know why no new entry is created or error message displayed even though my error display is turned on.
EDIT:: sorry for not including whole code
loginform.php (works fine)
<?php
require("connect.php");
session_start();
$query = "SELECT * FROM `profile`";
if ($query_run=mysqli_query($cnn,$query))
{
echo "
<h1>Sign up for Runners World</h1>
<form action='' method='post'>
Username: <input type='text' name='username'><br>
Email: <input type='text' name='email'><br>
Password: <input type='text' name='pw'><br>
<input type='submit' name='submit' value='submit'>
</form>
";
}
else {
die("<br>could not connect to table");
}
?>
<?php
if (isset($_POST['submit']))//if you submitted the form
{
$username = $_POST['username'];
$password = $_POST['pw'];
$email = $_POST['email'];
if ($username and $password and $email)
{
$addLogin = "INSERT INTO profile (username,email,password) VALUES ('$username','$email','$password')";
$success = $cnn->query($addLogin);
if ($success)
{
$_SESSION['name']="$username";
echo("<script>location.href = 'homePage.php';</script>");
}
else
{
die("login data failed to reach database");
}
}
else {echo "please fill out all the fields";}
}
else {
$submit=null;
echo 'no form submitted';
}
?>
addDetails.php (not submitting)
<?php
session_start();
error_reporting(E_ALL);
ini_set("display_errors",1);
require("connect.php");
require("login.php");
echo "<h1>Welcome ".$_SESSION['name']."</h1>";
echo "<form action='' method='post'>
Avatar: <input type='text' name='avatar'><br>
Location: <input type='text' name='location'><br>
Descripiton: <input type='text' name='about'><br>
Daily Goal: <input type='text' name='goal'><br>
<input type='submit' value='submit' name='submit'>
</form>
";
$avatar = $_POST['avatar'];
$location = $_POST['location'];
$goal = $_POST['goal'];
$about = $_POST['about'];
if (isset($_POST['submit']))
{
$sql = "INSERT INTO profile (avatar,location,goal) VALUES ('$avatar','$location','$goal')";
if ($cnn->query($sql)===TRUE)
{echo "you have inserted profile fields";}
else
{echo "sqlQuery failed to insert fields";}
}
?>
If you want to add data to a row that already exists, look up the UPDATE command in SQL
You should change the Sql statement in 'addDetails.php' to:
UPDATE profile
SET avatar={$avatar}, location={$location}, goal={$goal}
WHERE id={$id}
By the way you should never ever use this statement in your production, it is not safe, you should keep in mind to prevent Sql injection.

PHP - Allowing only one admin registration for page

I'm trying to create a form for admin registration. The code works correctly but more than one admin can register for this page. How can I make it so that only one admin can register?
<html >
<head>
<title></title>
</head>
<body>
<?php
print ("<form action='admin.php' method='post'>
<p>Name
<input type='text' name='firstname' />
</p>
<p>Surname
<input type='text' name='lastname' />
</p>
<p>Username
<input type='text' name='username' />
</p>
<p>Password
<input type='password' name='password' />
</p>
<p>Email <input type='text' name='email'/> </p>
<input type='submit' value='Register'/>
</form>
");
if( !($database=mysql_connect("localhost","root",""))||!(mysql_select_db("st_login",$database)) )
print("Could not connect");
if(isset($_POST['firstname'] )&&isset($_POST['lastname'])&&isset($_POST['username'])&&isset($_POST['password'])
/*&&isset($_POST['notat'])&&isset($_POST['lendet'])*/&&isset($_POST['email'])){
$firstname=$_POST['firstname'];
$lastname=$_POST['lastname'];
$username=$_POST['username'];
$password=md5($_POST['password']);
$email=$_POST['email'];
/*
$notat=$_POST['notat'];
$lendet=$_POST['lendet'];
*/
$query = "INSERT INTO login (firstname, lastname, username,password,email,admin) VALUES ('$firstname', '$lastname',
'$username','$password','$email',1)";
}
if ( !empty($firstname)&&!empty($lastname)&&!empty($username) &&!empty($password)&&!empty($email))
{
if(!($result=mysql_query($query,$database)))
{
print("Could not execute query");
die (mysql_error());//ose error
}
echo "YOU HAVE BEEN REGISTERED SUCCESSFULLY!You are the admin of this page";
}
else echo 'Fill in all the blank fields';
mysql_close($database);
?>
</body>
</html>
Here is my database
Add a check when inputting user data to the form. Check whether there are any rows where the field admin is set to 1 (or whatever you use)
Sample code for that
$result = mysql_query("SELECT firstname FROM mytable WHERE admin=1");
if(mysql_num_rows($result)== 0) {
//check if the post variables are set and input the values to the table
} else {
// Admin already exist
}
As mentioned in comments, you should stop using mysql_, and use mysqli_ or PDO with prepared statements instead, an example is given below. Keep in mind that you cannot mix APIs, so your entire code will have to be converted from one to the other.
$mysqli = new mysqli("host", "user", "password", "database");
$result = $mysqli->query("SELECT firstname FROM mytable WHERE admin=1");
if ($result->num_rows == 0)
//check if the post variables are set and input the values to the table
} else {
// Admin already exist
}
Reference
Why shouldn't I use mysql_* functions in PHP?
How can I prevent SQL injection in PHP?
Choosing an API
$mysqli->prepare (for prepared statements)

MYSQL QUERY FALSE although syntax is right

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...

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.

Categories