EDIT: I'm not sure what to really say. The comments was what helped my issue out right now. I didn't remember the fact to show an error, and that was what helped me. I had pretty much just tried something that obviously wasn't working due to wrongly placed variables and such,and displaying the error code let me know what variables was the faulty ones. Thank you for all your help, and this issue is now resolved!
So long story short, the title. I have no idea why this code refuses to input the inserted data into the database, and I've tried a bunch of things that haven't resulted any better.
Connection:
<?php
session_start();
$host = 'host';
$dbusername = 'username';
$dbpassword = 'password';
$anslutning = mysqli_connect($host, $dbusername, $dbpassword) or die("<b>Could not connect to database server</b>");
$anslutning->select_db('databasename') or die("<b>Could not connect to the specified database</b>");
?>
Form to grab data from :
echo '
<h2><center>Post a topic</center></h2>
<br /><br />
<div class="indexform">
<form action="index.php" method="POST">
Title: <input type="text" name="title"> <br /> <br />
Content: <textarea name="content" class="content"> </textarea>
<br /> <br />
<input type="submit" name="postTopicOnGeneral">
</form>
</div>
';
PHP code to insert it into database
if(isset($_POST['postTopicOnGeneral'])) {
$username = $_POST['username'];
$title = $_POST['title'];
$content = $_POST['content'];
$general = $_POST['general'];
$addPostOnGeneral = $anslutning->prepare('INSERT INTO tblPosts(title, content, author, category) VALUES(?, ?, ?, ?)');
$addPostOnGeneral->bind_param("ssss", $title, $content, $username, $general);
$addPostOnGeneral->execute();
echo "<center>Post created!</center>";
sleep(2);
echo "<script> window.location.href = 'index.php?general=1' </script>";
}
Undefined index:username and Undefined:general is what I get from that.
You are bound to get that error since you are not fetching $username and $general from anywhere in your form.
Change your form this:
echo '
<h2><center>Post a topic</center></h2>
<br /><br />
<div class="indexform">
<form action="index.php" method="POST">
Title: <input type="text" name="title"> <br /> <br />
Content: <textarea name="content" class="content"> </textarea>
<br /> <br />
<input type="submit" name="postTopicOnGeneral">
</form>
</div>';
to this:
echo '
<h2><center>Post a topic</center></h2>
<br /><br />
<div class="indexform">
<form action="index.php" method="POST">
Title: <input type="text" name="title"> <br /> <br />
Content: <textarea name="content" class="content"> </textarea>
<br /> <br />
Username:
<input type="text" name="username">
General:
<input type="text" name="general">
<input type="submit" name="postTopicOnGeneral">
</form>
</div>';
And then in your index.php:
if(isset($_POST['postTopicOnGeneral'])) {
echo $username = $_POST['username'];
echo $title = $_POST['title'];
echo $content = $_POST['content'];
echo $general = $_POST['general'];
// rest of your code
Try to change
$username = $_POST['username'];
$title = $_POST['title'];
$content = $_POST['content'];
$general = $_POST['general'];
With this:
$username = isset($_POST['username']) ? $_POST['username'] : '';
$title = isset($_POST['title']) ? $_POST['title'] : '';
$content = isset($_POST['content']) ? $_POST['content'] : '';
$general = isset($_POST['general']) ? $_POST['general'] : '';
Related
I have not found an answer anywhere else.
Still having a problem adding form textbox values to the session. The code as it stands won't even add to the session from this particular form. It had before until I closed the browser to restart the session. When it was sending the session correctly to the second page the values for fname, lname, address ect was fname:|N which I am assuming in a null value? Every page the sesson_start(); is called at the top.
Code for the form:
<form method='post' action='email.php'>
First name: <input type="text" name="fname"/><br />
Last name: <input type="text" name="lname"/><br />
Address: <input type="text" name="address"/><br />
City: <input type="text" name="city"/><br />
State: <input type="text" name="state" /><br />
Zip code: <input type="text" name="zip"/><br />
Email: <input type="text" name="email"/><br />
<button type="submit" name="submit">Continue to checkout</button>
</form>
<?php
if(isset($_POST['submit'])){
$_SESSION['fname'] = $_POST['fname'];
//$_SESSION['fname'] = $var_fname;
$_SESSION['lname'] = $_POST['lname'];
$_SESSION['address'] = $_POST['address'];
$_SESSION['city'] = $_POST['city'];
$_SESSION['state'] = $_POST['state'];
$_SESSION['zip'] = $_POST['zip'];
$_SESSION['email'] = $_POST['email'];
}
?>
Code on second page echo'ing the session:
<?php
session_start();
echo $var_session = json_encode($_SESSION["shopping_cart"]);
?>
<html>
<body>
<br /><br /><br />
<?php
echo session_encode();
//echo $var_email = json_encode($_SESSION["email"]);
//echo $var_fname = json_encode($_SESSION["fname"]);
//echo $var_email = $_SESSION["email"];
?>
</body>
</html>
I'm trying to make a simple message board MySQL database where you can write a review and submit it via an HTML form on one page and view all of the reviews on a separate page once you've submitted your review.
My problem is two of the fields from the HTML form are not being inserted into my MySQL database which results in my view all reviews page to be missing the Name and Title.
Link to what the "Read all Reviews" page looks like.
The code works without any issue when I tested it doing MySQL queries with just PHP but I need my HTML form to work.
HTML form:
<form action ="process.php" method = "post">
<fieldset>
<legend>Review Field</legend>
Reviewer Name: <br />
<input type="text" name "name" id = "name"><br />
Title of Review:<br />
<input type="text" name "title" id = "title"><br />
Enter your review below:
<!--Textbox start-->
<textarea name="body" id = "body" rows="10" cols="100">
</textarea>
<!--Textbox end-->
<br />
<input type="submit" name = "submit" id="submit">
<br />
</fieldset>
</form>
Code for process.php:
<?php // Create a database connection.
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "password";
$dbname = "ya_reviews";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
//Test if connection occurred.
if (mysqli_connect_errno()) {
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
}
//Perform database query
$name = $_POST['name'];
$title = $_POST['title'];
$body = $_POST['body'];
//This function will clean the data and add slashes.
// Since I'm using the newer MySQL v. 5.7.14 I have to addslashes
$name = mysqli_real_escape_string($connection, $name);
$title = mysqli_real_escape_string($connection, $title);
$body = mysqli_real_escape_string($connection, $body);
//This should retrive HTML form data and insert into database
$query = "INSERT INTO reviews (name, title, body)
VALUES ('".$_POST["name"]."','".$_POST["title"]."','".$_POST["body"]."')";
$result = mysqli_query($connection, $query);
//Test if there was a query error
if ($result) {
//SUCCESS
header('Location: activity.php');
} else {
//FAILURE
die("Database query failed. " . mysqli_error($connection));
//last bit is for me, delete when done
}
mysqli_close($connection);
?>
View all Reviews:
<?php
//This will fetch the data from the database
$query = "SELECT * FROM reviews";
$result = mysqli_query($connection, $query);
//Test if there was a query error
if (!$result) {
die("Database query failed.");
}
// This will let me display the data.
// The loop will be spilt so I can format with HTML
while ($row = mysqli_fetch_assoc($result)) {
//output data from each row
?>
Name: <?php echo $row["name"] . "<br />"; ?>
Title: <?php echo $row["title"] . "<br />"; ?>
Review: <?php echo $row["body"] . "<br />";
echo "<hr>"; ?>
<?php
} ?>
Note: I connected to the database with the same code seen in process.php before the above code, I excluded it to save space.
Your HTML attribute syntax is incorrect. Its missing = sign between attribute and value.
Change name "name" to name="name" and name "title" to name="title"
<input type="text" name="name" id = "name"><br />
Title of Review:<br />
<input type="text" name="title" id = "title"><br />
Also during insert you aren't using escaped values.
Use $name instead of $_POST["name"] in insert query. Same goes for title and body values.
The problem is that the name attribute is not correct in HTML.
<input type="text" name="name" id = "name"><br />
<input type="text" name="title" id = "title"><br />
I think you messed up with syntax of HTML
<form action ="process.php" method = "post">
<fieldset>
<legend>Review Field</legend>
Reviewer Name: <br />
<input type="text" name="name" id = "name"><br />
Title of Review:<br />
<input type="text" name="title" id = "title"><br />
Enter your review below:
<!--Textbox start-->
<textarea name="body" id = "body" rows="10" cols="100">
</textarea>
<!--Textbox end-->
<br />
<input type="submit" name = "submit" id="submit">
<br />
</fieldset>
</form>
It will work surely!
Yo, you're just missing some syntax, therefore creating errors when it comes to gathering the data from those elements,
<input type="text" name "title" id = "title">
You're missing the "=" sign from the name parameter
Here is the code of the username check I don't know how to make a code for the error message
<?php
if ($_POST['username']) {
include_once "connect_to_mysql.php";
$username = stripslashes($_POST['username']);
$username = strip_tags($username);
$username = mysql_real_escape_string($username);
$password = ereg_replace("[^A-Za-z0-9]", "", $_POST['password']);
$password = md5($password);
$sql = mysql_query("SELECT * FROM Users WHERE Us_Name='$username' AND Us_Password='$password'");
$login_check = mysql_num_rows($sql);
if($login_check > 0){
while($row = mysql_fetch_array($sql)){
$id = $row["Us_ID"];
$_SESSION['Us_ID'] = $id;
$username = $row["Us_Name"];
$_SESSION['Us_Name'] = $username;
header("location: Home2.php?id=$id");
}
} else {
$msg = '<br /><br /><font color="#FF0000">Invalid User Or Pass </font><br />';
exit();
}
}
?>
Add this is the code of the form.
I want the message to appear under the boxes of username and password
<form action="Home.php" method="post" enctype="multipart/form-data" name="loginform" id="loginform">
<input type="text" id="username" placeholder="Email or Username"/>
<input type="password" id="password" placeholder="Password"/>
<input type="submit" id="login_button" value="Login">
<p id="reset_password">Forget your password? Reset it here.</p>
</form>
I want the message to look like something like this
errorMsg
Instead of:
print '<br /><br /><font color="#FF0000">Invalid User Or Pass </font><br />';
Do:
$msg = '<br /><br /><font color="#FF0000">Invalid User Or Pass </font><br />';
And then in the HTML, do this:
<form action="Home.php" method="post" enctype="multipart/form-data" name="loginform" id="loginform">
<input type="text" id="username" placeholder="Email or Username"/>
<input type="password" id="password" placeholder="Password"/>
<?php echo $msg; ?> <!-- Here is where the message will appear -->
<input type="submit" id="login_button" value="Login">
<p id="reset_password">Forget your password? Reset it here.</p>
</form>
EDIT: Also, no need to exit();. Simply create the variable so you can echo it wherever you want it in your HTML by embedding your PHP in it.
Only printing will put it at the very top of the page, even before the <!DOCTYPE html>.
I am making a PHP Journal through a form, but no matter what I do, it always comes up as successfully posted. I've tried using empty() and null but I'm not sure what I'm doing wrong.
Here is the HTML for the form:
<form action="journal_post.php" method="post">
<p>Give your entry a title.</p>
<input class="input" type="text" name="title" />
<p>What is your mood today?</p>
<input class="input" type="text" name="mood" />
<p>Now please tell me about your day.</p>
<textarea class="input" name="entry" rows="12" cols="75" type="text"> </textarea>
<br>
<br>
<input class="submit" type="image" src="submit.png" name="submit" value="Submit" />
<form>
Here is the PHP:
<?php
$servername = "localhost";
$username = "root";
$password = "blahblah";
debug_to_console($password);
//Establishing Connection with Server
$connection = mysql_connect($servername, $username, $password);
//Selecting Database from Server
$journal_db = mysql_select_db("journal_db", $connection);
if(isset($_POST['submit'])){
//Fetching variables of the form which travels in URL
$title = $_POST['title'];
$mood = $_POST['mood'];
$entry = $_POST['entry'];
if($title !=''||$entry !=''){
//Insert Query of SQL
$query = mysql_query("insert into entrys(j_title, j_mood, j_entry) values ( '$title', '$mood', '$entry')");
echo "<br/><br/><span>Journal entry recorded..!!</span>";
}
else{
echo "<p>Insertion Failed <br/> Some Fields are Blank....!!</p>";
}
}
//Closing Connection with Server
mysql_close($connection);
?>
Change:
if($title !=''||$entry !=''){
to:
if($title !=''&&$entry !=''){
You want to check that both $title and $entry aren't empty, not either-or.
You should definitely use isset() to check the field before insertion into database
the line
<textarea class="input" name="entry" rows="12" cols="75" type="text"> </textarea>
actually adds a space in the entry, change it to
<textarea class="input" name="entry" rows="12" cols="75" type="text"></textarea>
I need to insert all form details into database and save the uploaded image in a location. I succeeded in uploading the file to specified location. But form details are not getting inserted into database.
This is the code in pages.php
<?php
session_start();
if(!empty($_SESSION['uname']) && !empty($_SESSION['pswd'])) {
include 'classes/insert.php';
$db_con->dbcon();
$db_con->insert_data();
$target_path = "uploads/";
$target_path = $target_path . basename( $_FILES['bg_img']['name']);
if(move_uploaded_file($_FILES['bg_img']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['bg_img']['name']).
" has been uploaded";
} else {
echo "There was an error uploading the file, please try again!";
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>New Page</title>
</head>
<body>
<p>Add pages</p>
logout
<br /><br />
Dashboard
<br /><br />
<form method="post" action="" enctype="multipart/form-data">
<label>Page name</label>
<input type="text" name="page_name" />
<br />
<br />
<label>Page title</label>
<input type="text" name="page_title" />
<br />
<br />
<label>Page bg img</label>
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
<input type="file" name="bg_img" />
<br />
<br />
<label>Page content</label>
<textarea name="page_content"></textarea>
<br />
<br />
<input type="submit" value="Submit" name="submit" />
</form>
</body>
</html>
<?php } else {
$home_loc = 'index.php';
header ('Location:' .$home_loc);}
?>
This is the code in insert.php
class db_con {
public function dbcon() {
$hostname = 'localhost';
$username = 'root';
$pswd = 'admin';
$dbname = 'web';
mysql_connect($hostname, $username, $pswd) or die('cudn\'t connect');
mysql_select_db($dbname) or die('cudn\'t select db');
}
function insert_data() {
$this->dbcon();
if (isset($_POST['page_name']) && isset($_POST['page_title']) && isset($_POST['bg_img']) && isset($_POST['page_content'])) {
$pg_name = mysql_real_escape_string($_POST['page_name']);
$pg_title = mysql_real_escape_string($_POST['page_title']);
$pg_img = mysql_real_escape_string($_POST['bg_img']);
$pg_content = mysql_real_escape_string($_POST['page_content']);
$insert_query = mysql_query("INSERT INTO pages (page_name, page_title, page_bg_img, page_content) VALUES ('" . $pg_name . "', '" . $pg_title . "', '" . $pg_img . "', '" . $pg_content . "')");
}
}
}
$db_con = new db_con();
well, there are many things to consider.
You are mixing Javascript with PHP.
change this
var $hostname = 'myhostname';
to
$hostname = 'myhostname';
same with others.
you shouldnt make many classes in your case.
use this:
class db_con{
public function dbcon(){
.........
}
function insert_data() {
...........
}
}
you are not calling the insert_data() function
call it like that:
$insert = new insert;
$insert->insert_data();
you should escape your variables, like that:
$pg_title = mysql_real_escape_string($_POST['page_title']);
you should switch to PDO or MYSQLI.
EDIT:
try this
session_start();
if(!empty($_SESSION['uname']) && !empty($_SESSION['pswd'])){
include 'classes/insert.php';
$db_con = new db_con();
$db_con->dbcon();
$db_con->insert_data();
EDIT2:
To get the uploaded file use $_FILES instead of $_POST:
$pg_img = $_FILES['bg_img'];
change this also
and $_FILES['bg_img']['name'] != ''
instead of
&& isset($_POST['bg_img'])
Try to check if you have successfully connected to the database, If not, change your initialization from $db_con = new db_con; to $db_con = new db_con();
EDITED:
I think you should also need to change your process flow. Separate the form, the insertion process and the database connection. I suggest you create 3 separate files:
1. The Form page (HTML)
2. The process page (PHP file where you will link your form. Or where the processes will be happening)
3. The Database connection file (PHP file. Put your db connection here and other db-related functionalities).
Here's my example:
Form Page:
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>New Page</title>
</head>
<body>
<p>Add pages</p>
logout
<br /><br />
Dashboard
<br /><br />
<form method="post" action="process.php" enctype="multipart/form-data">
<label>Page name</label>
<input type="text" name="page_name" />
<br />
<br />
<label>Page title</label>
<input type="text" name="page_title" />
<br />
<br />
<label>Page bg img</label>
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
<input type="file" name="bg_img" />
<br />
<br />
<label>Page content</label>
<textarea name="page_content"></textarea>
<br />
<br />
<input type="submit" value="Submit" name="submit" />
</form>
</body>
</html>
As you can seee, I pointed the action of the form to process.php.
Here's my sample process.php:
<?php
include 'classes/db.php';
if(isset($_POST['submit'])){
// get your post data here
$post_data = array('your post data');
// instantiate db
$db = new Db();
// create db connection
$db_connect = $db->connect();
// check if successfully connected to db
// then call the insertion process
$db->insert_data('table_name', $post_data);
}
Then in your db.php file:
<?php
class Db {
function connect(){
$hostname = 'localhost';
$username = 'root';
$pwd = 'admin';
$dbname = 'yourdbname';
mysql_connect($hostname, $username, $pswd) or die('couldn\'t connect');
mysql_select_db($dbname) or die('couldn\'t select db');
}
function insert_data($table_name, $data) {
mysql_query("INSERT INTO ".$table_name." (page_name, page_title, page_bg_img, page_content) VALUES ($data);
}
}
?>
Just don't follow my insertion process coz I just made it short. Its just the flow I wanted to show.
Hope this helps!