I am writing code that produces a <textarea> for a user to input something but it isn't giving me any output besides "please include some content" which is what it means to do if there is nothing in the box. This appears even if there is content in the <textarea> and won't even say "post fail" which is what it is meant to do if it can't insert into the database.
I am asking if anybody can see if there is something I have neglected to include, or if there is something that is wrong with my code.
<?php
session_start();
require('connect.php');
if(#$_SESSION["name"]){
//echo "welcome ".$_SESSION['name'];
?>
<html>
<link rel="stylesheet" type="text/css" href="styles.css" />
<head>
<title> Welcome to faecesbook</title>
</head>
<?php include('header.php'); ?>
<form action="post.php" method="POST">
<br / >
<br / >
<br / >
<br / >
<center>
<br/>
<br/>
Type your post here:<br/>(160CharLimit)<br/>
<textarea style="resize: none; width: 800px; height: 100px;" name="con" maxlength="160">
</textarea>
<br />
<input type="submit" name="submit" value="Post" style="width: 800px;" >
</center>
</form>
<body>
</body>
</html>
<?php
$content = #$_POST['con'];
$post_date = date("d-m-y");
if(isset($_POST['submit'])){
if($content){
if($query = mysqli_query($conn, "INSERT INTO post(`postID`, `userID` , `post_date` , `in_reply_to`, `postContent` )
VALUES ('','".$_SESSION["userID"]."','".$post_date."','','".$content."')") )
echo "post successful";
}else{
echo "post fail";
}
}else{
echo "Please include some content";
}
}
?>
Try this code. It should work.
<?php
session_start();
require('connect.php');
if(#$_SESSION["name"]){
//echo "welcome ".$_SESSION['name'];
?>
<html>
<link rel="stylesheet" type="text/css" href="styles.css" />
<head>
<title> Welcome to faecesbook</title>
</head>
<?php include('header.php'); ?>
<form action="post.php" method="POST">
<br / >
<br / >
<br / >
<br / >
<center>
<br/>
<br/>
Type your post here:<br/>(160CharLimit)<br/>
<textarea style="resize: none; width: 800px; height: 100px;" name="con" maxlength="160">
</textarea>
<br />
<input type="submit" name="submit" value="Post" style="width: 800px;" >
</center>
</form>
<body>
</body>
</html>
<?php
$post_date = date("d-m-y");
if(isset($_POST['submit'])){
if(isset($_POST['con']) && $_POST['con'] != ''){
$content = #$_POST['con'];
if($query = mysqli_query($conn, "INSERT INTO post(`postID`, `userID` , `post_date` , `in_reply_to`, `postContent` )
VALUES ('','".$_SESSION["userID"]."','".$post_date."','','".$content."')") )
echo "post successful";
}else{
echo "post fail";
}
}else{
echo "Please include some content";
}
}
?>
You have a missing braces in your code
if(#$_SESSION["name"]){
//echo "welcome ".$_SESSION['name'];
Should read
if(#$_SESSION["name"]){
//echo "welcome ".$_SESSION['name'];
}
And
if($query = mysqli_query($conn, "INSERT INTO post(`postID`, `userID` , `post_date` , `in_reply_to`, `postContent` )
VALUES ('','".$_SESSION["userID"]."','".$post_date."','','".$content."')") ) // <--- here
echo "post successful";
}else{
echo "post fail";
}
Making it readable also helps reduce errors
$query = mysqli_query($conn, "INSERT INTO post(`postID`, `userID` , `post_date` , `in_reply_to`, `postContent` )
VALUES ('','".$_SESSION["userID"]."','".$post_date."','','".$content."')");
if ($query){
echo "post successful";
}else{
echo "post fail";
}
I see your code sends submited data to another page, i checked it through print_r($_POST)
I changed <form action="post.php" method="POST"> to <form action="" method="POST"> and tried and it was working, in case if the code you submited here is not "post.php" do this.
So it means someting is wrong with your insert query. So try this PDO way of inserting data.I thought of suggesting you the following easy pdo insert
$dbhost = "localhost";
$dbname = "mydatabase";
$dbusername = "root";
$dbpassword = "mypppasss";
//connection string
$link = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbusername,$dbpassword);
Inside the if($content) put the following code and try
$statement = $link->prepare("INSERT INTO post(userID,post_date,postContent)
VALUES(:inp1,:inp2,:inp3,:inp4)");
$statement->execute(array(
inp1=>$_SESSION["userID"],
inp2=>$post_date,
inp4=>$content
));
EDITED
Add this code to the form submitted page to see the posted data for debugging.
if($_POST){
echo '<pre>';
print_r($_POST);
echo '</pre>';
}
EDITED
Note:# is used to hide errors, prevent it from displaying error
messages. that doesn't mean there is no error. Remove # for debugging
EDITED
Change your whole insert query part to this and try
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO post(userID,post_date,in_reply_to,postContent)
VALUES (".$_SESSION['userID'].",".$post_date.",'',".$content.")";
if (mysqli_query($conn, $sql)) {
echo "inserted";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
This is what was wrong.
i had two set of <?php ?>, the first one in the code included require('connect.php'); within it, and the second one required it also.
<?php
require('connect.php'); <<<<<------ NEEDED TO ADD THIS
$content = #$_POST['con'];
$post_date = date("d-m-y");
$userID = mysqli_query($conn,"SELECT userID FROM users WHERE name = '".$_SESSION['name']."'");
if(isset($_POST['submit'])){
if($content){
if($query = mysqli_query($conn, "INSERT INTO post(`postID`, `userID` , `post_date` , `in_reply_to`, `postContent` )
VALUES ('','".$userID."','".$post_date."','','".$content."')") )
echo "post successful";
}else{
echo "post fail";
}
}else{
echo "Please include some content";
}
}
?>
So thats what i think the offending piece of code was. And it now will give me error saying the SQLI query was unnsuccessful, which means it is at least attempting that part, whereas before it was not.
Related
I am trying to make a CRUD application. on the Create page I have to have three fields (title, text, category). the problem is that I have to make a method / function in PHP or JS that chooses a random picture from the "images" file and automatically loads it in the database along with the other 3 fields. then it has to appear on the admin.php page together with the other 3 fields.
Images have almost the same name except the last digit which differs (1-2-3)
I have no idea how to make this method/function.
my create.php page
// Include config file
require_once "config.php";
// Define variables and initialize with empty values
$title = $text = $category = "";
$title_err = $text_err = $category_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate title
$input_title = trim($_POST["title"]);
if(empty($input_title)){
$title_err = "Please enter a title.";
} else{
$title = $input_title;
}
// Validate text
$input_text = trim($_POST["text"]);
if(empty($input_text)){
$text_err = "Please enter an text.";
} else{
$text = $input_text;
}
// Validate category
$input_category = trim($_POST["category"]);
if(empty($input_category)){
$category_err = "Please enter the category.";
} else{
$category = $input_category;
}
// Check input errors before inserting in database
if(empty($title_err) && empty($text_err) && empty($category_err)){
// Prepare an insert statement
$sql = "INSERT INTO informatii (title, text, category) VALUES (?, ?, ?)";
if($stmt = $mysqli->prepare($sql)){
// Bind variables to the prepared statement as parameters
$stmt->bind_param("sss", $param_title, $param_text, $param_category, );
// Set parameters
$param_title = $title;
$param_text = $text;
$param_category = $category;
// Attempt to execute the prepared statement
if($stmt->execute()){
// Records created successfully. Redirect to landing page
header("location: admin.php");
exit();
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
$stmt->close();
}
}
?>
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Create Record</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<style>
.wrapper {
width: 600px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<h2 class="mt-5">Create Record</h2>
<p>Please fill this form and submit to add employee record to the database.</p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group">
<label>title</label>
<input type="text" name="title"
class="form-control <?php echo (!empty($title_err)) ? 'is-invalid' : ''; ?>"
value="<?php echo $title; ?>">
<span class="invalid-feedback"><?php echo $title_err;?></span>
</div>
<div class="form-group">
<label>Text</label>
<textarea name="text"
class="form-control <?php echo (!empty($text_err)) ? 'is-invalid' : ''; ?>"><?php echo $text; ?></textarea>
<span class="invalid-feedback"><?php echo $text_err;?></span>
</div>
<div class="form-group">
<label>Category</label>
<textarea name="category"
class="form-control <?php echo (!empty($category_err)) ? 'is-invalid' : ''; ?>"><?php echo $category; ?></textarea>
<span class="invalid-feedback"><?php echo $category_err;?></span>
</div>
<input type="submit" class="btn btn-primary" value="Submit">
Cancel
</form>
</div>
</div>
</div>
</div>
</body>
</html>
this should get you in the right direction (saving the image src is enough), you of course will have to adapt the path to your image folder, and image name
$nr_images = 3;
$random_nr_index = random_int(1,$nr_images);
$random_image_src = '/images/image-'.$random_nr_index.'.jpg';
To do it you need more than one step creating:
A simple html page to post 3 fields value and the image
A php file that receive the post fields and the image and save into mysql
A simple admin.PHP page that shows 3 fields and image
if you already have the images on the server please specify it in a comment
STEP 1:
<html>
<body>
<form method="POST" action="post.php">
f1:<input type="text" name="field1"><br>
f2:<input type="text" name="field2"><br>
f3:<input type="text" name="field3"><br>
im:<input type="file" name="image"><br>
<input type="submit" value="Save">
</form>
</body>
</html>
STEP 2: post.php
<?php
$f1=$_POST["field1"];
$f2=$_POST["field2"];
$f3=$_POST["field3"];
$im=$_POST["image"];
if ($f1 == "" || $f2 == "" || $f3 == "" ){
die("Errors: fields can't be empty! Go back check the fields and try Again");
}
//Saving image on Server's file system if any image
if(isset($_POST["image"])) {
//Saving image with no checking nothing: filetype, mime , extention (it may be very dangerous in a real server exposed to the public)
$where_save = "images/";
$im_name = basename($_FILES["image"]["name"]);
$tmp_name = $_FILES["image"]["tmp_name"];
move_uploaded_file ( $tmp_name , $where_save.$im_name );
}
$h = "localhost";
$u = "username";
$p = "password";
$db = "yourDB";
// Creating connection to mysql server
$conn = mysqli_connect($h, $u, $p, $db);
// Checking connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// WARNINGS ------------------------------------------------
// I do not care about security , please pay attention to it .
// use some mysql_escape_string , or real_mysql_escape_string
// could mitigate the violence of some sqlinjection attack
$sql = "INSERT INTO yourtable (field1, field2, field3,im_name)
VALUES ('$f1', '$f2', '$f3',$im_name)";
//executing mysql query to save data into it
if (!mysqli_query($conn, $sql)) {
die("Error: " . $sql . "<br>" . mysqli_error($conn));
}
//closing connection
mysqli_close($conn);
//Now we can redirect the user to admin.php where we show data
header("Location: admin.php");
?>
STEP 3:
<?php
$where_are_images="images/";
$h = "localhost";
$u = "username";
$p = "password";
$db = "yourDB";
// Again creating connection to mysql server
$conn = mysqli_connect($h, $u, $p, $db);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
//now we want to read the data from mysql
$sql = "SELECT * FROM yourtable LIMIT 1"; //just limit to the first record
$result = mysqli_query($conn, $sql);
?>
<html>
<body>
<h2>Admin page</h2>
<em> hey every one can see top secret data here , Needs soma care about security!</em>
<?php while($d = mysqli_fetch_assoc($result)){ // LOOPING ?>
<br>
f1:<?= $d["field1"] ?><br>
f2:<?= $d["field2"] ?><br>
f3:<?= $d["field3"] ?><br>
<img src="<?=$where_are_images.$d['im_name']?>">
<br>
<br>
<?php } ?>
</body>
</html>
<php? // CLOSING AND FREE RESOURCES
mysqli_free_result($result);
mysqli_close($conn); ?>
Now you have all you need . Have fun editing it with random images part ...
I hope there are no error (i have not tested it)
Iam trying to create a private messaging system in which user sends message to another user and that content is inserted into database..Iam using a random number called hash to identify a conversation between two people..table for that is "message_group" and table for saving messages is "messages"..here comes the problem..
When I type something in text area and click on sendmessage button it inserts the data into the messages database..But if type something again and try to send it , the data wont enter into database..coz of this the other person is getting only first message..Please help me solving this problem..here's the code
<html>
<head>
<title>new convo</title>
</head>
<body>
<?php include 'connect.php';?>
<?php include 'message_title_bar.php';?>
<?php include 'functions.php';?>
<div>
<?php
if(isset($_GET['user']) && !empty($_GET['user'])){
?>
<form method='post'>
<?php
if(isset($_POST['message']) && !empty($_POST['message'])){
$my_id=$_SESSION['user_id'];
$user=$_GET['user'];
$random_number=rand();
$message=$_POST['message'];
$connect = mysqli_connect('localhost','root','','php_mysql_login_system');
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query_string = "SELECT `hash` FROM `message_group` WHERE (`user_one`='$my_id' AND `user_two`='$user') OR (`user_one`='$user' AND `user_two`='$my_id')";
$check_con=mysqli_query($connect,$query_string) or die(mysqli_error($connect));
if(mysqli_num_rows($check_con)==1){
echo "<p>Conversation already Started</p>";
}else{
$connect = mysqli_connect('localhost','root','','php_mysql_login_system');
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($connect,"INSERT INTO message_group VALUES('$my_id' , '$user' , '$random_number')");
mysqli_query($connect,"INSERT INTO messages VALUES ('','$random_number','$my_id','$message')");
echo "<p>Conversation started</p>";
}
}
?>
Enter message:<br />
<textarea name='message' rows='7' cols='60'></textarea>
<br />
<br />
<input type='submit' name="submit" value="sendmessage" />
</form>
<?php
}
else{
echo "<b>Select User</b>";
$connect = mysqli_connect('localhost','root','','php_mysql_login_system');
$user_list=mysqli_query($connect,"SELECT `id`,`username` FROM `users`");
while($run_user=mysqli_fetch_array($user_list)){
$user = $run_user['id'];
$username = $run_user['username'];
echo "<p><a href='send.php?user=$user'>$username</a></p>";
}
}
?>
</div>
</body>
</html>
Any help is appreciated.
<html><head><title>new convo</title></head><body>
<?php include 'connect.php'; ?>
<?php include 'message_title_bar.php'; ?>
<?php include 'functions.php'; ?>
<?php $connect = mysqli_connect('localhost', 'root', '', 'php_mysql_login_system'); if (mysqli_connect_errno()) echo "Failed to connect to MySQL: " . mysqli_connect_error(); ?>
<div>
<?php
if (isset($_GET['user']) && !empty($_GET['user'])) {
?>
<form method='post'>
<?php
if (isset($_POST['message']) && !empty($_POST['message'])) {
$my_id = $_SESSION['user_id'];
$user = $_GET['user'];
$message = $_POST['message'];
$query_string = "SELECT `hash` FROM `message_group` WHERE (`user_one`='$my_id' AND `user_two`='$user') OR (`user_one`='$user' AND `user_two`='$my_id')";
$check_con = mysqli_query($connect, $query_string);
if (mysqli_num_rows($check_con)) {
$f_array = mysqli_fetch_array($check_con);
$hash = $f_array['hash'];
echo "<p>Conversation already Started</p>";
} else {
$hash = rand();
mysqli_query($connect, "INSERT INTO message_group VALUES('$my_id' , '$user' , '$hash')");
echo "<p>Conversation started</p>";
}
mysqli_query($connect, "INSERT INTO messages VALUES ('', '$hash', '$my_id', '$message')");
}
?>
<label for="message">Enter message:</label>
<textarea name='message' id="message" rows='7' cols='60'></textarea>
<br/>
<br/>
<input type='submit' name="submit" value="sendmessage"/>
</form>
<?php
} else {
echo "<b>Select User</b>";
$user_list = mysqli_query($connect, "SELECT `id`,`username` FROM `users`");
while ($run_user = mysqli_fetch_array($user_list)) {
$user = $run_user['id'];
$username = $run_user['username'];
echo "<p><a href='send.php?user=$user'>$username</a></p>";
}
}
?>
</div>
</body>
</html>
There are many mistakes in code brother read basic first... and you are not using echo function to print old chat.
Just echo old chat. before post function.
steps:
1. Check if users already chatting.
2. If they are chatting echo chat which they already chatted.
3. If not chatting then start new chat.
4. if they are not chatting you dont need to echo anything just echo new message.
Your present code will just show you last message i think. because your page getting reload. and after it loads its just printing your last message in my view.. you need to print old chat as well.
I have used an isset() function on 'submit' to store and retrieve my html form inputs. However all my SQL data in my table only gets displayed after I clicked the submit function on the browser as I programmed it that way.
I would like to make it now so that even when I refresh the browser the html form input remains permanently and I do not have to click submit to fetch the entire table and display (it rather displays itself straight away).
Please show me how I can go about this?
below is my code:
<?php
require_once "connection.php";
if(isset($_POST['submit'])) {
$question = $_POST['question'];
$description = $_POST['description'];
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME );
if($conn->connect_error) {
die("connection error: " . $conn->connect_error);
} else {
echo "Submit button connected to database!";
}
}
if(isset($_POST['question']) && $_POST['description']) {
$sql = " INSERT INTO `ask` (question_id, question, description) VALUES
(NULL, '{$question}', '{$description}' ) ";
if($conn->query($sql)) {
echo "it worked";
} else {
echo "error: " . $conn->error;
exit();
}
$query = "SELECT * FROM `ask` ";
$result = $conn->query($query);
while($row = $result->fetch_assoc()) {
echo "<p> {$row['question']}</p>";
echo "<p> {$row['description']}</p>";
}
$conn->close();
}
?>
<!DOCTYPE html>
<html>
<head></head>
<body>
<div id="submitQuestion">
<form action="" method="post">
<input type="text" name="question"/>
<textarea name="description" rows="10" cols="20"></textarea>
<input type="submit" name="submit" value="ASK"/>
</form>
</div>
</body>
</html>
If I've correctly understood the question, you would like to always display all entries and add new data only when it's required. For this goal, you can connect and retrieve data independently from form submission, and insert new data only when required.
<?php
require_once "connection.php";
// Connect to database
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME );
if($conn->connect_error) {
die("connection error: " . $conn->connect_error);
}
// Insert new data if required
if(isset($_POST['submit']) && isset($_POST['question']) && isset($_POST['description']))
{
$question = $_POST['question'];
$description = $_POST['description'];
$sql = " INSERT INTO `ask` (question_id, question, description) VALUES
(NULL, '{$question}', '{$description}' ) ";
if(!$conn->query($sql)) {
echo "error during insert: " . $conn->error;
exit();
}
}
// Display data
$query = "SELECT * FROM `ask` ";
$result = $conn->query($query);
while($row = $result->fetch_assoc()) {
echo "<p> {$row['question']}</p>";
echo "<p> {$row['description']}</p>";
}
// Close database connection
$conn->close();
?>
<!DOCTYPE html>
<html>
<head></head>
<body>
<div id="submitQuestion">
<form action="" method="post">
<input type="text" name="question"/>
<textarea name="description" rows="10" cols="20"></textarea>
<input type="submit" name="submit" value="ASK"/>
</form>
</div>
</body>
</html>
<?php
require_once "connection.php";
if(isset($_POST['submit'])) {
$question = $_POST['question'];
$description = $_POST['description'];
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME );
if($conn->connect_error) {
die("connection error: " . $conn->connect_error);
} else {
echo "Submit button connected to database!";
}
}
if(isset($_POST['question']) && $_POST['description']) {
$sql = " INSERT INTO `ask` (question_id, question, description) VALUES
(NULL, '{$question}', '{$description}' ) ";
if($conn->query($sql)) {
echo "it worked";
} else {
echo "error: " . $conn->error;
exit();
}
}
$query = "SELECT * FROM `ask` ";
$result = $conn->query($query);
while($row = $result->fetch_assoc()) {
echo "<p> {$row['question']}</p>";
echo "<p> {$row['description']}</p>";
}
$conn->close();
?>
<!DOCTYPE html>
<html>
<head></head>
<body>
<div id="submitQuestion">
<form action="" method="post">
<input type="text" name="question"/>
<textarea name="description" rows="10" cols="20"></textarea>
<input type="submit" name="submit" value="ASK"/>
</form>
</div>
As I told you in the other question..
I'm creating a page with PHP for a class and when I echo things it shows up in the wrong place.
Here is my HTML page
<html>
<head>
<link rel="stylesheet" href="Site.css">
<?php include("Header.php"); ?>
</div>
</head>
<body>
<div id="main">
<h1>About</h1>
<form action="Insert.php" method="post">
<table>
<tr>
<td><span>First name:</span></td>
<td><input type="text" name="firstname"></td>
</tr>
<tr>
<td><span>Last name:</span></td>
<td><input type="text" name="lastname"></td>
</tr>
<tr>
<td><span>Age:</span></td>
<td><input type="number" name="age"></td>
</tr>
</table>
<input type="submit">
</form>
<?php include("Footer.php");?>
</div>
</body>
</html>
Here is my PHP page:
<?php
$con = mysql_connect("localhost","USERNAME","PASSWORD");
if(!$con) {
die("could not connect to localhost:" .mysql_error());
}
mysql_select_db("a7068104_world") or die("Cannot connect to database");
header("refresh:1.5; url=NamesAction.php");
$firstname = mysql_real_escape_string($_POST['firstname']);
$lastname = mysql_real_escape_string($_POST['lastname']);
$fullname = mysql_real_escape_string($_POST['firstname'] . " " . $_POST['lastname']);
$age = mysql_real_escape_string($_POST['age']);
$query = "SELECT * FROM names_1 WHERE fullname='$fullname'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0 ){
echo "Your name is already in the database and will not be added again!";
}
else {
$query = "INSERT INTO names_1 (firstname, lastname, fullname, age) VALUES('$firstname', '$lastname', '$fullname', '$age')";
$result = mysql_query($query);
if($result) {
echo "Your name was successfully added to the database!";
}
else{
echo "Your name couldn't be added to the database!";
}
}
mysql_close($con);
?>
<html>
<head>
<link rel="stylesheet" href="Site.css">
<?php include("Header.php"); ?>
</div>
</head>
<body>
<div id="main">
<h1>Names</h1>
<p>You will be redirected back to the <b>Names</b> page in a moment.</p>
<?php include("Footer.php");?>
</div>
</body>
</html>
When I echo stuff in my PHP page it shows up at the very top of the frame that it's in right above the
<div id="main">
I want the echoed text to go in the very bottom of the
<div id="main">
Is there any way that I can do that? I appreciate your help!
Thanks,
Leonardude
Your issue is that you are echo'ing the message before you supply your HTML.
Which is evident here:
if($result) {
echo "Your name was successfully added to the database!";
}
else{
echo "Your name couldn't be added to the database!";
}
Because PHP is a server-side language and HTML is client-side, the PHP will process well before the HTML, meaning it will echo before the page is displayed. Hence the issue where it is before your <div id="main"></div>.
A way around this is by setting a variable
if($result) {
$var = "Your name was successfully added to the database!";
}
else{
$var = "Your name couldn't be added to the database!";
}
And somewhere in your <div id="main"></div> you could do something like the following:
<div id="main">
<?php
if(isset($var) && !empty($var)) {
echo $var;
}
?>
</div>
My class is attempting to make our own game.. But, we can't get the submit page to send to the database in PhpMyAdmin. When you click submit, it sends blank entries to the database, like if you hadn't filled in any of the blanks. Can someone help with this problem. Thanks!!
My index.php page.
<html>
<head>
<meta charset="UTF-8">
<title> Register New Account </title>
<link rel="stylesheet" type="text/css" href="td.css">
</head>
<body>
<?php
/* $count=$count+1;
echo " count " . $count; */
if($_POST['submit_id'] == 1)
{
/* echo "testing"; */
if($_POST['Username'] == NULL)
{
$message = 'Please enter your Username.';
}
if($_POST['Email'] == NULL)
{
$message = 'Please enter your Email.';
}
if($_POST['Confirm'] == NULL)
{
$message = 'Please re-enter your Email.';
}
if($_POST['Password'] == NULL)
{
$message = 'Please enter your Password.';
}
if($_POST['Email'] != $_POST['Confirm'])
{
$message = 'Your emails did not match, Please enter your emails again.';
}
}
if( $message == NULL )
{
// if there is no error, test to see if there is already an account by the player_name
$MySQLlink = new mysqli("localhost", "root", "******", "Tower_Defense");
// check connection - take out later
if ( !$MySQLlink )
{
printf( "Could not connect to MySQL server : %s", mysqli_connect_error() );
exit();
}
else
{
printf( "Connected to the MySQL server" );
echo "<br>";
}
$result = mysqli_query( $MySQLlink, "SELECT * FROM Users WHERE ( email = 'email' ) " );
if($row = mysqli_fetch_array($result))
{
$message = "There is an account with that email address already. Please choose another email account";
}
mysqli_free_result($result);
$result = mysqli_query( $MySQLlink, "SELECT * FROM Users WHERE ( Username = '$Username' ) " );
if( $row = mysqli_fetch_array($result) && $message == NULL )
{
$message = "There is an account by that player name already. Please choose another Login name";
mysqli_free_result($result);
}
else
{
//echo "next date <br>";
// create account
$Username = ($_POST['Username']);
$Password = ($_POST['Password']);
$Email = ($_POST['Email']);
$email = ($_POST['email']);
//echo "Next one<br>";
$TableList = " `Username`, `Password`, `Email`, `Confirm` ";
$Values = " '$Username', '$Password', '$Email', '$Confirm' ";
if($message != NULL)
{
echo "$message";
}
?>
<div id="container" >
<div id="header">
<h1 id="h1">Besco's Biscuits</h1>
About
Instructions
The Creation Of The Game
Contact Us
</div>
<br /> <br /> <br />
<table align = "center">
<tr>
<td>
Welcome to <b> Besco's Biscuits </b>. Please fill out the following <br />
areas and we will begin your adventure soon. :)
</td>
</tr>
</table>
<br /> <br /> <br /> <br /> <br />
<table align = "center">
<tr>
<td>
<form action = "<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post"> <br />
Username: <input type="text" name="Username" id= "Username"> <br />
Email: <input type = "text" name = "Email" id= "Email"> <br />
Confirm: <input type = "text" name = "Confirm" id= "Confirm"> <br />
Password: <input type = "password" name = "Password" id = "Password"> <br />
<input type = "submit" value = "Register" id="submit_id" value = "1">
<input type = "reset" name="Reset" value="Check if Available!" class = "account">
</form>
</td>
</tr>
</table>
</body>
</html>
My insert.php page
<html>
<body>
<?php
$Username = $_POST['name'];
$con=mysqli_connect("localhost", "root", "******", "Tower_Defense");
//Check Connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO Users (Username, Email, Confirm, Password)
VALUES
('$_POST[Username]','$_POST[Email]',' $_POST[Confirm]',' $_POST[Password]')";
if (!mysqli_query($con,$sql))
{
die ('Error: ' . mysqli_error($con));
}
else
{
echo "1 record added";
echo $_POST[Username];
//echo "Where is Username?";
echo $_POST[Email];
//echo "Where is Email?";
echo $_POST[Confirm];
//echo "Where is Confirm";
echo $_POST[Password];
//echo "Where is Password";
}
mysqli_close($con);
?>
</body>
UPDATE:
I added in the changes that someone had suggested in moving the checks to insert.php and now the email and confirm email check does not work. Can anyone help?
index.php
<html>
<body>
<div id="container" >
<div id="header">
<h1 id="h1">Besco's Biscuits</h1>
About
Instructions
The Creation Of The Game
Contact Us
</div>
<br /> <br /> <br />
<table align = "center">
<tr>
<td>
Welcome to <b> Besco's Biscuits </b>. Please fill out the following <br />
areas and we will begin your adventure soon. :)
</td>
</tr>
</table>
<br /> <br /> <br /> <br /> <br />
<table align = "center">
<tr>
<td>
<form action = "insert.php" method = "post"> <br />
Username: <input type="text" name="Username" id= "Username" required = "1"> <br />
Email: <input type = "text" name = "Email" id= "Email" required = "1"> <br />
Confirm: <input type = "text" name = "Confirm" id= "Confirm" required = "1"> <br />
Password: <input type = "password" name = "Password" id = "Password" required = "1"> <br />
<input type = "submit" value = "Register" id="submit_id" value = "1">
<input type = "reset" name="Reset" value="Reset Page" class = "account">
</form>
</td>
</tr>
</table>
</body>
</html>
insert.php
<html>
<body>
<?php
if($_POST['submit_id'] == 1)
{
echo "testing";
if($_POST['Email'] != $_POST['Confirm'])
{
$message = 'Your emails did not match, Please enter your emails again.';
}
}
if( $message == NULL )
{
// if there is no error, test to see if there is already an account by the player_name
$MySQLlink = new mysqli("localhost", "root", "abc123", "tower_defense");
// check connection - take out later
if ( !$MySQLlink )
{
printf( "Could not connect to MySQL server : %s", mysqli_connect_error() );
exit();
}
else
{
printf( "Connected to the MySQL server" );
echo "<br>";
}
$result = mysqli_query( $MySQLlink, "SELECT * FROM Users WHERE ( email = 'email' ) " );
if($row = mysqli_fetch_array($result))
{
$message = "There is an account with that email address already. Please choose another email account";
}
mysqli_free_result($result);
$result = mysqli_query( $MySQLlink, "SELECT * FROM Users WHERE ( Username = '$Username' ) " );
if( $row = mysqli_fetch_array($result) && $message == NULL )
{
$message = "There is an account by that player name already. Please choose another Login name";
mysqli_free_result($result);
}
else
{
//echo "next date <br>";
// create account
$Username = ($_POST['Username']);
$Password = ($_POST['Password']);
$Email = ($_POST['Email']);
$email = ($_POST['email']);
//echo "Next one<br>";
}
}
if($message != NULL)
{
echo "$message";
}
$con=mysqli_connect("localhost", "root", "abc123", "tower_defense");
//Check Connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO Users (Username, Email, Confirm, Password)
VALUES
('$_POST[Username]','$_POST[Email]',' $_POST[Confirm]',' $_POST[Password]')";
if (!mysqli_query($con,$sql))
{
die ('Error: ' . mysqli_error($con));
}
else
{
echo "1 record added";
echo $_POST[Username];
//echo "Where is Username?";
echo $_POST[Email];
//echo "Where is Email?";
echo $_POST[Confirm];
//echo "Where is Confirm";
echo $_POST[Password];
//echo "Where is Password";
}
mysqli_close($con);
?>
</body>
</html>
I see two main problems here -
First, the action of your form points to itself. That means that the $_POST array submits to index.php, and your insert.php page has no access to that information. Index.php runs through the validation checks, and if everything checks out, it assigns the $_POST values to variables and quits. That's where the data dies. There is no method for getting the information over to the file insert.php. So if you manually open the file insert.php in a browser, the $_POST array will be empty, and it will simply insert blanks.
There are several ways to resolve this. The simplest, most expeditious way would be the single page solution - move the insert.php code into the index.php file inside that last else block.
else {
//echo "next date <br>";
// create account
$Username = $_POST['name'];
//etc.. code to insert data from insert.php
Another solution would be to move all the validation code to insert.php, display any form errors on that page, and make the user go back a page if validation fails. In that case, you would change the action of the form to insert.php:
<form action="insert.php" method="post">
This approach is less user-friendly, and not an ideal solution. Really a better practice is to use Javascript for form validation and PHP for form processing. That may be outside the scope of your class...
Second, this code is wide open to SQL injection. Instead of putting variables directly into your SQL statements, you need to use parameterized queries. Take a look at this SO question about how to parameterize queries with mysqli.
The mistakes that I found:
First things first your code submits the values received from the form to index.php itself so there is no question of values getting insert at the first place because the insert query is not run.
In index.php check the query to SELECT email and username. The variables do not have any value when the query is run because the values get transferred couple of lines AFTER the queries (at the lines where you have $email = $_POST['Email']). Moreover you have missed the $ sign in the query related to email.
Coming to insert.php you have missed quotes in the global variable $_POST[] in the insert query viz. $_POST['email'].
Check for these errors and let me know if it works.