HTML will not display after php validation? [duplicate] - php

This question already has answers here:
How can I get useful error messages in PHP?
(41 answers)
Closed 3 years ago.
My HTML on my page is eliminated after running my PHP validation on the input form.
HTML: InsertUser.php
<?php
session_start();
require_once('File Below');
echo $errors; //Errors is local variable within insertBackend.php i know. i just wanted this example to be exact compared next to my code.
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script
</head>
<body>
<div class="container">
<form class="form-horizontal" role="form" method="post" action="InsertUser.php">
<div class="form-group">
<label for="txtName" class="col-sm-2 control-label">Name:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputName" name="txtName" placeholder="Name" value="">
</div>
</div>
<div class="form-group">
<label for="txtPassword" class="col-sm-2 control-label">Password:</label>
<div class="col-sm-10">
<input type="password" class="form-control" id="inputPassword" name="txtPassword" placeholder="Password" value="">
</div>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<input id="btnSubmit" name="insert_form" type="submit" value="Submit" class="btn btn-primary">
</div>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<input id="btnCreate" onclick="location.href = 'createUser.php';" name="createUser" type="button" value="Create User" class="btn btn-primary">
</div>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<input id="btnsame" onclick="location.href = 'InsertUser.php';" name="InsertUser" type="button" value="Insert User" class="btn btn-primary">
</div>
</div>
</form>
</div>
</body>
</html>
PHP Page: InsertBackend.php
<?php
session_start();
require_once('*DIRECTORY CONTAINING SQL CONNECTION*'); //works fine
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
if(isset($_POST['insert_form']))
{
$_SESSION['InsertUser'] = "Insert User Pass"; //This ensures i make it INTO the method
$name= "";
$password = "";
$nameInsert = mysqil_real_escape_string($_POST['txtName']);
//^This right here. mysqli_real_escape_string();
$passInsert = mysqil_real_escape_string($_POST['txtPassword']);
//^This right here. mysqli_real_escape_string();
$errors = array();
if(empty($nameInsert))
{
array_push($errors, "Please enter your Name");
}
if(empty($passInsert))
{
array_push($errors, "Please enter your password");
}
if(count($errors = 0))
{
$name = mysqil_real_escape_string($con, $_POST['txtName']);
$password = mysqil_real_escape_string($con, $_POST['txtPassword']);
$hashPass = password_hash($password, PASSWORD_DEFAULT);
$sqlInsert = "INSERT INTO Table (Name, Phash)
VALUES ('$name', '$hashPass')";
$_SESSION['VerifyHash'] = $hashPass; // Super security issue using a hashed password as a flag? I know. Just wanted visual representation of pass to compare next to my database
if ($con->query($sqlInsert) === TRUE)
{
header('location: InsertUser.php');
echo "New record created successfully <br>";
}
else
{
header('location: InsertUser.php');
echo "Error: " . $sql . "<br>" . $con->error;
}
}
}
echo "Connected"; //Flag to verify Database connection throughout usage. If it makes it here then its connected. End flag.
//CLOSE DATABASE CONNECTION
mysqli_close($con);
?>
When I run all of this together and enter test data. It arrives on: InsertUser.php. and directs properly. However it displays nothing. No code, no Sessions, no HTML. Nothing? However when I simply refresh the page without navigating anywhere it displays the entire insert form fine. And 2 of my flags display:
ConnectedInsert User Pass
I then proceed to eliminate session data. Then I just see
Connected
above the login form. After this all takes place there is no change in my Database? And no users are actually added.
Using this information I can deduce that:
my form submits to my InsertBackend.php file when called from the form.
is connected to my database appropriately.
And that my Backend script is:
Not correctly inserting into the database.
Not properly hashing my password input.
Not rendering the HTML when called back to the insert form.
I have tried really hard to figure out where exactly in this chain of events things are going awry. However I have been unable to figure out why it is not all calling properly, and why my inserts are not working at all.
I really tried finding something on here that would help me figure it out. Unfortunately I was unable to locate anything that gave me clarity. And after the last few hours i have decided to see if anyone here might have any helpful insight into my issue. Just to even have a second set of eyes on it.

This was just poorly built with no session checking. The session cannot be created if it already exists i suppose.
Using
print_r(error_get_last());
Provides me with
Array ( [type] => 8 [message] => session_start(): A session had already been started - ignoring [file] => *InsertBackend.php* [line] => 2 )
Maybe? I guess i have to test this theory. I will update code as i progress until page is all displaying and inserting into database in case anyone else runs into a similar issue down the road.

Related

PHP form validation not functioning having copied the tutorial code

I am hoping the community can give me a little insight into what is not working with my code, I am following a Udemy course. I have followed the accompanying video which developed an undefined variable error, which after doing some research I believe I have fixed by declaring variables as empty strings being able to be over-ridden by the form data.
The form sends data to the database if both are completed, and if one of the fields is empty then it doesn't, which is as it should be.
If one of the fields is empty it should return a statement asking the user to enter data into the respective field, but nothing is being sent.
The only difference between the tutorial and my code is I have used the materialize framework, where the tutorial used bootstrap, but I can't see that being the issue.
I have attached my code, and commented out redundant parts.
<?php
include('php/connection.php');
//validates data for create user form
if( isset( $_POST["createUserBtn"])){
$createUsername = "";
$createUserPassword = "";
function validateFormData( $formData ) {
$formData = trim( stripcslashes( htmlspecialchars( $formData)));
return $formData;
}
if( !$_POST["createUsername"]){
$createUsernameError = "Enter a username <br>";
} else {
$createUsername = validateFormData( $_POST["createUsername"]);
}
if( !$_POST["createUserPassword"]){
$createUserPasswordError = "Enter a Password <br>";
} else {
$createUserPassword = validateFormData( $_POST["createUserPassword"]);
}
if( $createUsername && $createUserPassword) {
$query = "INSERT INTO users (user_id, userName, userPassword) VALUES (NULL, '$createUsername', '$createUserPassword')";
// if( mysqli_query( $connection, $query)){
// echo "New User added";
// } else {
// echo "Error: ".$query."<br>".mysqli_error($connection);
// }
}
}
?>
<!DOCTYPE html>
<html lang="en">
<?php require('static/header.php'); ?>
<?php
$createUsernameError = "";
$createUserPasswordError = "";
?>
<div class="col s8 m8 l5 valign-wrapper">
<div class="container">
<form action="<?php echo htmlspecialchars( $_SERVER["PHP_SELF"] ); ?>" method="post">
<div class="row">
<div class="col s12">
<span><h4>Create your user account - create user.php</h4></span>
<div class="row form-font">
<div class="col s12">
<div class="input-field">
<a class="red-text"><?php echo $createUsernameError; ?></a>
<input placeholder="Enter your username" type="text" name="createUsername">
<label for="email">Username</label>
</div>
<div class="input-field">
<a class="red-text"><?php echo $createUserPasswordError; ?></a>
<input placeholder="Enter your password" type="password" name="createUserPassword">
<label for="password">Password</label>
</div>
<div class="row left-align">
<div class="col s2"></div>
<div class="col s8">
<button class="btn-flat waves-effect waves-custom" type="submit" name="createUserBtn"><i class="material-icons left">create</i>Create Account</button>
</div>
<div class="col s2"></div>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
<?php require('static/footer.php'); ?>
</html>
Look carefully at your code and the places where you make use of - for example - the $createUsernameError variable.
If there's an error, you set a message in it with this line: $createUsernameError = "Enter a username <br>";. Great, just what you wanted.
However, later on in the code, you run $createUsernameError = "";, which resets it to empty again. And that happens in all circumstances, whether an error was identified or not. And it happens before you try to echo that variable onto the page.
So basically you're setting the value and then immediately blanking it again before you output it. You need to make sure it's only set blank in situations where there's no error. It's the same problem for the password error message.
An easy way to do that would simply be to set the value blank before you run the error checks. Then it'll stay blank if there's no error, but it won't overwrite any error messages which do get set.
So just move these lines:
$createUsernameError = "";
$createUserPasswordError = "";
to the top of your script.
P.S. Please pay attention to the security warnings posted in the comments and urgently fix your code to remove these vulnerabilities before using this code in any kind of live environment. Even if you don't plan to use this code for real, you should still fix these issues so that you learn to do things the correct, safe, reliable way and don't get into bad habits. If you copied this code from a course online, I suggest finding a better course.

Updating data fields using PHP

I am a complete beginner when it comes to PHP. I have successfully created a login form/page that requires a user to enter his/her username and password which is then added to a database. I have also managed to create a page (using php) to display the data contained in all the data fields. I have the db connection file separately which works well. I have a functions.php file which contains the functions.
Now, I have created a php file in which I should be able to update the data in the various fields in the database. Instead of updating/replacing the existing data (username & password) in the selected row (targeting the id) it creates a new row in the db with the new username & password. Herewith my code to update existing data fields.
<?php include "db.php";?>
<?php include "functions.php";?>
<?php
if (isset($_POST['submit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$id = $_POST['id'];
$query = "UPDATE users SET ";
$query .= "username = '$username', ";
$query .= "password = '$password', ";
$query .= "WHERE id = $id ";
$result = mysqli_query($connection, $query);
if(!$result) {
die("QUERY FAILED" . mysqli_error($connection));
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="col-sm-6">
<form action="login_create.php" method="post">
<div class="form-group">
<label for="username">Username</label>
<input type="text" name="username" class="form-control">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" name="password" class="form-control">
</div>
<div class="form-group">
<select name="id" id="">
<?php
showAllData();
?>
</select>
</div>
<input class="btn btn-primary" type="submit" name="submit" value="UPDATE">
</form>
</div>
</div>
</body>
</html>
I can simply not find the problem. Since people use PHP differently I am unable to find a solution based on the specific coding I have tried.
Update
Kindly note that I am working on a localhost as part of learning php and have not yet started looking at security. I am initialising the $connection via a different file (db.php) which I am calling in the first line of my previous code.
<?php
$connection = mysqli_connect('localhost', 'root', '', 'loginapp');
if(!$connection) {
die("Database connection failed");
}
?>
Since you didn't say what does the login_create.php do and what is the filename of that php code in your post. I can only guess that your login_create.php file is to create a new account not update it. Perhaps your file with that UPDATE query is not named login_create.php. Hence, my guess is that you put a wrong filename in your <form action="login_create.php" method="post">
(Posted solution on behalf of the question author).
The problem was with the incorrect naming of the form action. I used
<form action="login_create.php" method="post">
instead of
<form action="login_update.php" method="post">

Trying to add reply system and get posts in real time on my comment system

I have been working all week on getting a working comment system on my page, looking around at scripts and trying to learn as much as I can (at one time I was good at this, certified and everything, but I seem to have lost it).
I finally got this to work - it connects to my db not problem and my db accepts data inserted from the form .
However, my issues is that the comments do not show up on my site in real time. Can anyone point me in the right direction to adding this functionality?
My connect.php is as follows:
<?php
$connection = mysqli_connect('localhost', '', '', 'london34_db1');
if(!$connection){
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
}
My commentform.php is as follows:
<?php
require('connect.php');
if(isset($_POST) & !empty($_POST)){
$name = mysqli_real_escape_string($connection, $_POST['name']);
$email = mysqli_real_escape_string($connection, $_POST['email']);
$subject = mysqli_real_escape_string($connection, $_POST['subject']);
echo $isql = "INSERT INTO comments (cid, name, email, subject, status) VALUES ('$id', '$name', '$email', '$subject', 'draft')";
$ires = mysqli_query($connection, $isql) or die(mysqli_error($connection));
if($ires){
$smsg = "Your Comment Submitted Successfully";
}else{
$fmsg = "Failed to Submit Your Comment";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Home Page</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" >
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" >
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<link rel="stylesheet" href="styles.css" >
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" ></script>
</head>
<body>
<div class="container">
</div>
<div class="container">
<div class="col-md-8">
<div class="panel panel-default">
<div class="panel-heading">Submit Your Comments</div>
<div class="panel-body">
<?php if(isset($smsg)){ ?><div class="alert alert-success" role="alert"> <?php echo $smsg; ?> </div><?php } ?>
<?php if(isset($fmsg)){ ?><div class="alert alert-danger" role="alert"> <?php echo $fmsg; ?> </div><?php } ?>
<form method="post">
<div class="form-group">
<label for="exampleInputEmail1">Name</label>
<input type="text" name="name" class="form-control" id="exampleInputEmail1" placeholder="Name">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" name="email" class="form-control" id="exampleInputEmail1" placeholder="Email">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Subject</label>
<textarea name="subject" class="form-control" rows="3"></textarea>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
<div class="col-md-4">
</div>
</div>
</body>
</html>
Is anyone able to point me in the right direction?
Thank you,
For it to work "real time" you need one of two things.
Refresh your page after post (window.location.reload()). You could also throw in a name anchor. However, this is outdated, and not recommended.
Use AJAX to solve your issue. You have three options, XMLHttpRequest, fetch(), or if you are using jQuery, $.ajax().
Using ajax should be standard now a days. As it allows for much smoother overall flow of the front end and the back end. You said to have the comments working, so I will continue on that assumption.
Say you have your comment form:
<div class="panel-heading">Submit Your Comments</div>
<!--- code --->
<form id="comment_form" method="post">
<!--- more code --->
</form>
</div>
Now let's say when the comment is made, instead of return simple html you return a json_encoded object.
Friendly reminder, don't $_POST to self. It just mixes things up and makes the waters dirty. We want clean code. Create a file else where with the POST handler.
<?
if($_POST) {
// handle the comment $_POST
// when complete
if( success ) {
print_r(json_encode([
'success' => true,
'comment_body' => $_POST['comment']
]));
} else {
print_r(json_encode([
'success' => false,
'message' => 'Something went wrong'
]));
exit;
}
}
You can add a simple fetch() script to your page:
<script>
var form = document.querySelector('#comment_form'),
// You need a comment section. Since I didn't see one, I will make my own.
comment_section = document.querySelector('#comment_section');
form.addEventListener('submit', e => {
e.preventDefault();
var data = new FormData(form);
fetch('path/to/your/script.php', {
body: data,
method: form.method,
credentials: 'same-origin'
})
.then(response => response.json()) // this is data from the server, you really want the response from your own page. Thus, the second `then` clause.
.then(data => {
// right here is where the magic begins
// lets assume data to be a json object
if( data.success == true ) {
// create a new comment element. This is just an example empty div
var comment = document.createElement('<div>');
comment.className = "comment new-comment";
comment.innerHTML = data.comment_body;
comment_section.appendChild(comment);
} else {
// handle a failed comment
}
})
.catch(err => console.warn(err));
});
</script>
Basically what happens here is, user post the comment, you handle it the same way you would.
However, in the response you gather the data submitted to you, then appendChild to a comment master div. Which you can set to have the comments by default on there.
This is very basic, and just a proof of concept. Do some more research on it. But I hope this guides you.
PHP is server side, so you would either need to auto refresh the page, or use some Javascript.
To autorefresh:
<meta http-equiv="refresh" content="<?= $seconds?>;URL='<?= $page?>'">
Using jQuery, you could poll a script which responds with new comments, something like this:
function doPoll(){
$.post('ajax/test.html', function(data) {
alert(data); // process results here
setTimeout(doPoll,5000);
});
}
The best option however for auto loading fresh comments is to use something like NodeJs. This involves running node on your server, and some js on the page. Rather than the js polling the script, the node server notifies the client, so it's the other way around. I can't give an example of that as I haven't used it, but I'm sure it isn't hard to find examples online.
Good luck!

undefined index error while trying to get value returned from the link?

I know its a duplicate one but i'm getting this error while trying to fetch data passed from a link..I dont know how to resolve it.
here is my code:
add_package.php
echo "<td><a href='delete.php?name3=" . $row['package_type']."&id3=".$row['p_id']."'>Delete</a></td>";
echo "<td><a href='edit_package.php?name3=" . $row['package_type']."&id3=".$row['p_id']."'>Update</a></td>";
here the delete link works perfectly but when i click update it takes to the edit_package page where i'm getting an undefined error..
code for edit_package.php:
<?php
include('db.php');
$id4 = $_GET['id3'];//update the page
$name4 = $_GET['name3'];//helps to update the package
echo $id4;
echo $name4;//getting values here correctly..
if(isset($_POST['submit']) )
{
$package=$_POST['package'];
if (ctype_alnum($package) && !empty($id4) && !empty($name4))
{
$sql13="select package_type,id from tbl_package where package_type='".$package."'";
$retvali=mysql_query($sql13,$conn);
$num_rows1 = mysql_num_rows($retvali);
if ($num_rows1 == 0 || $num_rows1=="")
{
$sql = "Update tbl_package set package_type='".$package."' where package_type='".$name4."' and p_id='".$id4."'";
$retval = mysql_query( $sql, $conn );
?><script>alert("Updated Successsfully");window.location ='http://localhost/demo/add_package.php';
</script><?php
}
else
{
?><script>alert("Already Exists");window.location ='http://localhost/demo/add_package.php';
</script><?php
}
}
else
{
?><script>alert("enter only letters and numbers")</script><?php
}
}
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<form id="form-validation" action="edit_package.php" method="post" class="form-horizontal" enctype="multipart/form-data" novalidate="novalidate">
<div class="col-md-6">
<div class="block" style="height:500px;">
<div class="block-title">
<h2><strong>State the Package For Tour</strong></h2>
</div>
<fieldset>
<div class="form-group">
<label class="col-md-4 control-label" for="val_username">Update Package <span class="text-danger">*</span></label>
<div class="col-md-6">
<div class="input-group">
<input type="text" id="package" name="package" class="form-control" required >
<span class="input-group-addon"><i class="fa fa-user"></i></span>
</div>
</div>
</div>
<div class="form-group form-actions">
<div class="col-md-8 col-md-offset-4">
<input type="submit" class="btn btn-info btn-primary " value="Update" name="submit">
</div>
</div>
</fieldset>
</form>
When i press update button i'm getting an undefined error i dont know why?..Thanks in advance
I'm attaching an image to it..
Try to change the <form>'s action URL to include your GET varaibles:
<form id="form-validation" action="edit_package.php?id3=<?php echo $_GET['id3']; ?>&name3=<?php echo $_GET['name3']; ?>" method="post" class="form-horizontal" enctype="multipart/form-data" novalidate="novalidate">
PLEASE NOTE: This is extremely unsafe! You need to sanitize ALL user input before using it. My example above, dis-regards security, and simply is to demonstrate my point. GET and POST data, are user variables. A malicious user could put bad code in the URL (ie ?name3=<badcode>) and it would be printed on the page, well in the source code, which they could easily pop out of. Also, in SQL queries, you need to escape the data or use prepared statements.
You should not be using mysql functions, switch to MySQLi or PDO. MySQL has been killed for a while now..
These are just asking for you to get hacked:
$sql13="select package_type,id from tbl_package where package_type='".$package."'";
and..
$sql = "Update tbl_package set package_type='".$package."' where package_type='".$name4."' and p_id='".$id4."'";
You are vulnerable to SQL injections, would could easily allow a malicious attacker to add/edit/view/delete data in your database.
The problem is, you have $package (which is raw data from POST) and $id4 and $name4 (which is raw data from GET) in your SQL query.
You would use mysql_real_escape_string() on them, but you should be using mysqli or PDO anyways...
Example:
$name4 = mysql_real_escape_string($_GET['name3']);
It's confusing, I don't know what the GET variable is called name3 but you assign it the variable $name4.. Whoever (even you) comes along later on will be lost in your code.
Updated:
Try this code. I swapped your GET for POST in your php code, and passed the GET variables from your URL as hidden fields in your form.
<?php
include('db.php');
if(isset($_POST['submit']) )
{
$package = mysql_real_escape_string($_POST['package']);
$id4 = mysql_real_escape_string($_POST['id3']); // why is variable named id4 but its id3??
$name4 = mysql_real_escape_string($_POST['name3']); // why is variable $name4 but its name3??
if (ctype_alnum($package) && !empty($id4) && !empty($name4))
{
$sql13 = "SELECT package_type,id FROM tbl_package WHERE package_type='$package' LIMIT 1";
$retvali = mysql_query($sql13, $conn);
$num_rows1 = mysql_num_rows($retvali);
if ($num_rows1 == 0 || $num_rows1=="")
{
$sql = "Update tbl_package set package_type='$package' WHERE package_type = '$name4' AND p_id='$id4'";
$retval = mysql_query( $sql, $conn );
echo '<script>alert("Updated Successsfully");window.location = "http://localhost/demo/add_package.php";</script>';
} else {
echo '<script>alert("Already Exists"); window.location = "http://localhost/demo/add_package.php";</script>';
}
} else {
echo '<script>alert("enter only letters and numbers");</script>';
}
}
?>
<form action="edit_package.php" method="post" enctype="multipart/form-data" novalidate="novalidate">
<input type="hidden" name="id3" value="<?php echo htmlspecialchars($_GET['id3'], ENT_QUOTES | ENT_HTML5); ?>" />
<input type="hidden" name="name3" value="<?php echo htmlspecialchars($_GET['name3'], ENT_QUOTES | ENT_HTML5); ?>" />
Update Package: <input type="text" id="package" name="package" class="form-control" required >
<input type="submit" class="btn btn-info btn-primary " value="Update" name="submit">
</form>
I removed your HTML formatting from the form. You had div tags that didn't match up.. I can't see your whole code, but it looks like you have a bunch of div's that are messed up (ie: not closed where they should be). I also added mysql_real_escape_string() to the passed variables, and htmlspecialchars() to the GET variables echo'd in the hidden fields of your form. It's a start.
You might be able to make better sense of your code and troubleshoot errors, if you wrote your code a bit cleaner. Not trying to bash you :) Proper indentation, spacing, and formatting go a long way. It makes it easier on your eyes, and on yourself, in times like these..
I left your <script> tags because I assumed there was a reason your wanted to popup a message box.. I would just use header('Location: /path/to/where.php'); and pass your error message through a session variable or something, like an array of errors, which you get, clear, and show on the page the errors.

Weird PHP within html

I've written some html code, and once i tried to place some PHP inside it, anything below this sign ?> wouldn't appear!!! I have some pictures and text that wouldn't appear unless I place it above. I'm writing with Bootstrap 2.3 and phpMyAdmin 4.10. all languages. Thank you for your time in advance.
here is my code so far:
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="bootstrap/css/bootstrap.css">
<link type="text/css" rel="stylesheet" href="bootstrap/css/myStyle.css">
<title>OJRA - Registration</title>
</head>
<body>
<div style="width:400px; height:400px; border-radius:5px; background-color:#aaa; margin-left:100px;">
<form action="" method="post" style="margin-left:20px;">
<h6>Username</h6>
<input type="text" name="username" placeholder="Your Username">
<h6>Password</h6>
<input type="password" name="usrPassowrd" placeholder="Your password">
<h6>Email</h6>
<input type="email" name="usrEmail" placeholder="Your Email"><br>
<input class = "btn btn-default" type="submit" value = "Register">
</form>
</div>
<div style="width:400px; height:400px; border-radius:5px; background-color:#aaa; margin-left:100px;">
<form action="" method="post" style="margin-left:20px;">
<h6>Username:</h6> <input type="text" name="username" placeholder="Your username">
<h6>Password:</h6> <input type="password" name="usrPassowrd" placeholder="Your password">
<input class = "btn btn-default" type="submit" value="Sign in">
</form>
<?php
define('INCLUDE_CHECK',true);
require 'connect.php';
$username = $_POST['username'];
if($username == "")
{
die("cannot go empty");
header("location:index.php");
exit;
}
$password = $_POST['usrPassword'];
$email = $_POST['usrEmail'];
$query = "insert into tz_members values('$username', '$password', '$email')";
mysql_query($query) or die(mysql_error());
?>
</div>
<img src="sexymotivation.jpg" style="margin-top:-800px; margin-right:10px;" class="pull-right">
</body>
</html>
A few things have already been outlined (as answers) that do make sense, however I spotted a few typos in your inputs that will prevent your form from working, plus a few other points.
Here are a few of my recommendations:
First, this (in 2 instances) has a typo in it name="usrPassowrd" which should read as name="usrPassword" to go with your existing $password = $_POST['usrPassword'];
As I stated in my original comments:
Comment #1: die("cannot go empty"); header("location:index.php"); exit; Your header won't do anything, because it DIE()'d and that will cease to go any further.
Comment #2: What I suspect is going on is, because you've got your entire code inside one big clump, and that if certain conditions aren't met... it still wants to keep going. Now, I suggest that you put a conditional statement wrapped around your PHP....
such as if(isset($_POST['submit'])){ // PHP } then add this to your submit button name="submit" --- I also suggest you split up your form and your PHP/SQL altogether and make it submit to another page instead, with the same conditional statement I've already outlined.
If you absolutely want to execute everything in one page, try the following:
Note: I borrowed the img src from user3009875's answer also.
(Rewrite)
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="bootstrap/css/bootstrap.css">
<link type="text/css" rel="stylesheet" href="bootstrap/css/myStyle.css">
<title>OJRA - Registration</title>
</head>
<body>
<div style="width:400px; height:400px; border-radius:5px; background-color:#aaa; margin-left:100px;">
<form action="" method="post" style="margin-left:20px;">
<h6>Username</h6>
<input type="text" name="username" placeholder="Your Username">
<h6>Password</h6>
<input type="password" name="usrPassword" placeholder="Your password">
<h6>Email</h6>
<input type="email" name="usrEmail" placeholder="Your Email"><br>
<input class = "btn btn-default" type="submit" value = "Register">
</form>
</div>
<div style="width:400px; height:400px; border-radius:5px; background-color:#aaa; margin-left:100px;">
<form action="" method="post" style="margin-left:20px;">
<h6>Username:</h6> <input type="text" name="username" placeholder="Your username">
<h6>Password:</h6> <input type="password" name="usrPassword" placeholder="Your password">
<input class = "btn btn-default" name="submit" type="submit" value="Sign in">
</form>
<?php
// this below, will prevent a premature execution of code
if(isset($_POST['submit'])){
define('INCLUDE_CHECK',true);
require 'connect.php';
$username = $_POST['username'];
if($username == "")
{
die("cannot go empty");
// header("location:index.php"); // commented out
exit;
}
$password = $_POST['usrPassword'];
$email = $_POST['usrEmail'];
$query = "insert into tz_members values('$username', '$password', '$email')";
mysql_query($query) or die(mysql_error());
} // end brace for if(isset($_POST['submit']))
?>
</div>
<!-- commented out original img src -->
<!--
<img src="sexymotivation.jpg" style="margin-top:-800px; margin-right:10px;" class="pull-right">
-->
<!-- new img src by user3009875 in an answer given -->
<img src="sexymotivation.jpg" style="margin-top:100px; margin-right:10px;" class="pull-right">
</body>
</html>
You can't use header() there to perform a redirection because you've already outputted some HTML and PHP has flushed HTTP headers.
The reason that <img> disappeared is probably that you called die(). This function terminates the whole page at once.
If you see cannot go empty, you should check the form to make sure you posted username field. If you see some error message about MYSQL, it is mysql_query($query) that fails.
By the way, your code has a SQL Injection problem.
IT doesn't load below ?> because script fails. This is common behaviour when there is a bug.
Check tail -f /var/log/apache2/error.log on linux (terminal)
Check tail -f /var/log/apache2/error_log on max (terminal)
windows -> I have no idea... somewhere in C:\\
At this point:
die("cannot go empty");
you stop the script. The following PHP code will not be executed and the HTML will not be sent to the user.
It's possible that there is an error when executing your PHP code, that would prevent it from going through the rest of the file.
Using your browser's Developer Tools, check the contents of the HTML that was returned, it's possible that the last line could be an error message. If you have erorr_reporting off then it would write to your error log only.
/var/log/apache2/error.log is a common location for the error log file if you are using Apache on a Linux machine.
As a side note, that code you have is very dangerous, do not use data sent from the client directly in a SQL statement, you need to sanitize otherwise you make your web app vulnerable to SQL injection.
Consider using a prepared statement
http://php.net/manual/en/pdo.prepare.php
Try:
<img src="sexymotivation.jpg" style="margin-top:100px; margin-right:10px;" class="pull-right">
I think setting the top margin to -800px will cause it to disappear from the screen.
Also, make sure your image is of .jpg.

Categories