Unexpected column 'message' in 'field list' - php

I'm trying to create a PHP forum page uses sessions. Every time I try to post a comment I keep getting the same error, not sure where I'm going wrong with this
Here's my code for the form:
session_start();
if(!isset($_SESSION['user_id'])){
require('login_tools.php');
load();
}
$page_title = 'Post Message';
include('includes/header.html');
echo "<h1>Home</h1>
<p>You are now logged in, {$_SESSION['first_name']}
{$_SESSION['last_name']}
</p>";
echo '<form action = "post_action.php" method = "POST" accept-charset = "utf-8">
<p>Subject:<br/>
<input name = "subject" type = "text" size = "64"</p>`
<p>Message:<br/>
<textarea name = "message" rows = "5" cols = "50">
</textarea></p>
<p><input type = "submit" value = "Submit"></p>
</form>';
Here's the code for the post action:
session_start();
require('login_tools.php');
if(!isset($_SESSION['user_id'])){
load();
}
$page_title = 'Post Error';
include('includes/header.html');
echo '<div id = "content">';
if($_SERVER['REQUEST_METHOD']=='POST'){
if(empty($_POST["subject"])){
echo '<p class = "main">Please enter a subject for this post</p>';
}
if(empty($_POST["message"])){
echo '<p class = "main">Please enter a message for this
post';
}
if(!empty($_POST['subject']) && !empty($_POST['message'])){
require('../connect_db.php');
$q = "INSERT INTO forum
(first_name,last_name,subject,messsage,post_date)
VALUES(
'{$_SESSION[first_name]}',
'{$_SESSION[last_name]}',
'{$_POST[subject]}',
'{$_POST[message]}',
NOW())";
$r = mysqli_query($dbc,$q);
if(mysqli_affected_rows($dbc)!=1){
echo '<p>Error</p>'.mysqli_error($dbc);
}
else{
load('forum.php');
}
mysqli_close($dbc);
}
}

There is a spelling mistake
$q = "INSERT INTO forum
(first_name,last_name,subject,messsage,post_date)
It should be message

The PHP statement which generates the SQL is missing quote marks around the member names of $_SESSION.
I would write
$q = "INSERT INTO forum
(first_name,last_name,subject,messsage,post_date)
VALUES('" .
$_SESSION['first_name'] . "','" .
$_SESSION['last_name'] . "','" .
$_POST['subject'] . "','" .
$_POST['message'] . "'," .
"NOW())";

Related

Unable to save text to mysql database and also how to comment quote reply

I have this code where i write comment in a textarea field and select a picture and sumbit to mysqli database through php, but the problem im having is when i only select a picture to upload or when i write a comment/texts in the textarea and select a picture to upload it works but then when i only write comment/texts in the textarea field and submit it doesn't work.
And also i want to create a comment reply "quote" , like to click reply on a comment then quote and reply the comment.
// My compose form
<form method="post" action="process.php" enctype='multipart/form-data'>
<textarea class="text-area" cols="75" name="comment" type="text" rows="5" placeholder="write message"></textarea><br>
<input type='file' style="width:257px" name='fileToUpload' ><br>
<input class="submitButton" type='submit' value='Send'>
</form>
// My process.php code
<?php
// start username session
session_start();
//connect to database
require_once ("dtb.php");
$commentSenderName = $_SESSION['username'];
$date = date('Y-m-d H:i:s');
$comment = isset($_POST['comment']) ? htmlspecialchars($_POST['comment']) : "";
//Directory where to upload file
$name = $_FILES['fileToUpload']['name'];
$target_dir = "upload/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
//Select file type
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
//Valid file extensions
$extensions_arr = array("jpg","jpeg","png","gif","NULL");
//Check extension
if( in_array($imageFileType,$extensions_arr) ){
//Upload file
move_uploaded_file($_FILES['fileToUpload']['tmp_name'],$target_dir.$name);
//Insert data into tables
$sql = "INSERT INTO tblcomment(comment,comment_sender_name,date,image) VALUES ('". $comment . "','" . $commentSenderName . "','" . $date . "','".$name."')";
$result = mysqli_query($conn, $sql);
if (! $result) {
$result = mysqli_error($conn);
}
echo "<p style='padding-left:22px;padding-top:10px;font-family:verdana;font-size:20px'> Post entered... </p>";
header("Refresh: 3; url=mysite.com");
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
// This is the code that fetches and display data from mysql database
$sql = "SELECT comment_sender_name,date,comment,image FROM tblcomment";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
//output data of each row
while($row = mysqli_fetch_assoc($result)) {
$name = $row['comment_sender_name'];
$time = $row['date'];
$msg = $row['comment'];
$img = $row['image'];
$now = array("<span><b style='font-size:25px'> $name </b></span>","<span style='font-size:14px;color:#474747;padding-left:40px;'><i>$time</i></span>");
$message = "<p style='color:#232323;font-size:20px;font-weight:bold'> $msg </p>";
$image_src = "<a href='#'><img src='upload/$img' style='width:550px;height:320px;border-radius:5px'></img></a>";
echo '<table border="0" style="padding-left:25px;box-sizing;height:450px;width:400px;">
<tr>
<td>' .$now[0] .$now[1] .$message .$image_src. "<br/><br/><br/><br/>". '</td>
</tr>';
}
} else {
echo "<p style='padding-left:22px'> 0 results </p>";
}
//Free result set
mysqli_free_result($result);
?>
Im not getting any kind of error.
Aside from my comment above with the many, many vulnerabilities in your code, the issue looks like you assume you always have a $_FILES. If you didn't upload a file, $_FILES['fileToUpload']['name']; is not going to exist. Check for it with if (isset($_FILES['fileToUpload'])) { and act on that information appropriately. You probably did get an error, or more specifically a warning, but it is in your web servers log file.

PHP produces blank screen with submit button click

Below I have code that is supposed to update an entry in the database. When I click the submit button the form goes away but it is not replaced with anything and more importantly it doesn't update the database. I cannot seem to find where the error is and any help would be greatly appreciated.
<?php
define('TITLE', 'Quotes Entry!');
// Include the header:
include('header.php');
include('mysqli_connect.php');
// Leave the PHP section to display lots of HTML:
?>
<?php //
mysqli_set_charset($dbc, 'utf8');
if (isset($_GET['id']) && is_numeric($_GET['id']) ) { // Display the entry in a form:
// Define the query:
$query = "SELECT title, entry FROM Salinger WHERE entry_id={$_GET['id']}";
if ($r = mysqli_query($dbc, $query)) { // Run the query.
$row = mysqli_fetch_array($r); // Retrieve the information.
//make the form
print '<form action = "edit_entry.php" method = "post">
<p> Entry Titles <input type= "text" name = "title" size = "40" maxsize = "100" value = "' . htmlentities($row['title']) . '" /></p>
<p>Entry Text <textarea name = "entry" cols = "40" rows = "5">'. htmlentities($row['entry']).'</textarea></p>
<input type = "hidden" name = "id" value = "'.$_GET['id'] .'" />
<input type = "submit" name = "submit" value = "Update This Entry!" />
</form>';
} else { // Couldn't get the information.
print '<p style="color: red;">Could not retrieve the blog entry because:<br />' . mysqli_error($dbc) . '.</p><p>The query being run was: ' . $query . '</p>';
}
} elseif (isset($_POST['id']) && is_numeric($_POST['id'])) { // Handle the form.
$problem = "false";
if(!empty($_POST['title']) && !empty($_POST['entry'])){
$title = mysqli_real_escape_string($dbc, trim(strip_tags($_POST['title'])));
$entry = mysqli_real_escape_string($dbc, trim(strip_tags($_POST['entry'])));
} else{
print '<p style="color: red;">Could not retrieve the blog entry because:<br />' . mysqli_error($dbc) . '.</p><p>The query being run was: ' . $query . '</p>';
$problem = true;
}
if(!problem){
$query = "UPDATE Salinger SET title = '$title', entry = '$entry' WHERE entry_id = {$_POST['id']}";
$r = mysqli_query($dbc, $query); //execute the query
if(mysqli_affected_rows($dbc) == 1){
print'<p> The blog entry has been updated.</p>';
// Report on the result:
} else {
print '<p style="color: red;">Could not retrieve the blog entry because:<br />' . mysqli_error($dbc) . '.</p><p>The query being run was: ' . $query . '</p>';
}
}
} else{
print '<p style="color: red;">Could not retrieve the blog entry because:<br />' . mysqli_error($dbc) . '.</p><p>The query being run was: ' . $query . '</p>';
}
mysqli_close($dbc); // Close the database connection.
include('footer.php'); // Need the footer.
?>
Because you set $problem = "false"; you need to set it to $problem= false;
"false" is not false
And !problem should be !$problem
You have a problem with GET[id].
It's getting blank cause of POST event on screen, due to which your SQL is not finding the record.
To test assign hard coded value in your select statement.
Example
$query = "SELECT title, entry FROM Salinger WHERE entry_id=10";

All-in-One Web form

I'm learning PHP and I am now on creating an all in one web form that adds a new subscriber record to the subscribers table in the newsletter database. This is my first time on this site, so excuse any n00biness.
The comments explain the portion of code which determines whether the form will be processed. I'm not sure if it needs to go inside the if..else statement that validates the submitted form data, or if it goes after the validation in its own if..else.
When I put it inside the validation, the html form shows, but when I hit submit, all the info refreshes and nothing happens.
When I put it after the validation, the html form does not show, I get an error saying undefined variable: FormErrorCount. It then tells gives me the id number I'm supposed to get, but I did not enter a name or email (due to the html form not showing) and that is left blank.
There is an include file, but that is just fine.
I'm sure once this gets figured out, I will have the feeling to want to slap myself, but I have been staring at the screen way too long. Thank you
<?php
$ShowForm = FALSE;
$SubscriberName = "";
$SubscriberEmail = "";
if (isset($_POST['submit'])) {
$FormErrorCount = 0;
if (isset($_POST['SubName'])) {
$SubscriberName = stripslashes($_POST['SubName']);
$SubscriberName = trim($SubscriberName);
if (strlen($SubscriberName) == 0) {
echo "<p>You must include your name</p>\n";
++$FormErrorCount;
}
}else{
echo "<p>Form submittal error (No 'SubName' field)!</p>\n";
++$FormErrorCount;
}
if (isset($_POST['SubEmail'])) {
$SubscriberEmail = stripslashes($_POST['SubEmail']);
$SubscriberEmail = trim($SubscriberEmail);
if (strlen($SubscriberEmail == 0)) {
echo "<p>You must include your email address!</p>\n";
++$FormErrorCount;
}
}else{
echo "<p>Form submittal error (No 'SubEmail' field)!</p>\n";
++$FormErrorCount;
}
//CODE BELOW IS THE SAME AS THE COMMENTED OUT CODE TOWARDS THE END. NOT SURE WHERE IT GOES.
if ($FormErrorCount == 0) {
$ShowForm = FALSE;
include("inc_db_newsletter.php");
if ($DBConnect !== FALSE) {
$TableName = "subscribers";
$SubscriberDate = date("Y-m-d");
$SQLstring = "INSERT INTO $TableName " .
" (name, email, subscribe_date) " .
" VALUES('$SubscriberName', '$SubscriberEmail', '$SubscriberDate')";
$QueryResult = #mysql_query($SQLstring, $DBConnect);
if ($QueryResult === FALSE) {
echo "<p>Unable to insert the values into the subscriber table.</p>" .
"<p>Error code " . mysql_errno($DBConnect) . ": " .
mysql_error($DBConnect) . "</p>";
}else{
$SubscriberID = mysql_insert_id($DBConnect);
echo "<p>" . htmlentities($SubscriberName) . ", you are now subscribed to our
newsletter.<br />";
echo "Your subscriber ID is $SubscriberID.<br />";
echo "Your email address is " . htmlentities($SubscriberEmail) . ".</p>";
}
mysql_close($DBConnect);
}
}else{
$ShowForm = TRUE;
}
//CODE ABOVE IS THE SAME AS THE COMMENTED OUT CODE TOWARDS THE END. NOT SURE WHERE IT GOES.
}else{
$ShowForm = TRUE;
}
/* CODE BELOW IS SAME AS THE CODE BETWEEN THE COMMENTS ABOVE, BUT NOT SURE WHERE IT BELONGS
if ($FormErrorCount == 0) {
$ShowForm = FALSE;
include("inc_db_newsletter.php");
if ($DBConnect !== FALSE) {
$TableName = "subscribers";
$SubscriberDate = date("Y-m-d");
$SQLstring = "INSERT INTO $TableName (name, email, subscribe_date) " .
"VALUES ('$SubscriberName', '$SubscriberEmail', '$SubscriberDate')";
$QueryResult = #mysql_query($SQLstring, $DBConnect);
if ($QueryResult === FALSE) {
echo "<p>Unable to insert the values into the subscriber table.</p>" .
"<p>Error code " . mysql_errno($DBConnect) . ": " .
mysql_error($DBConnect) . "</p>";
}else{
$SubscriberID = mysql_insert_id($DBConnect);
echo "<p>" . htmlentities($SubscriberName) . ", you are now subscribed to our
newsletter.<br />";
echo "Your subscriber ID is $SubscriberID.<br />";
echo "Your email address is " . htmlentities($SubscriberEmail) . ".</p>";
}
mysql_close($DBConnect);
}
}else{
$ShowForm = TRUE;
}
*/CODE ABOVE IS SAME AS THE CODE BETWEEN THE COMMENTS ABOVE SECTION, BUT NOT SURE WHERE IT BELONGS
//HTML PORTION
if ($ShowForm) {
?>
<form action = "NewsletterSubscribe.php" method = "POST">
<p><strong>Your Name: </strong>
<input type = "text" name = "SubName" value = "<?php echo $SubscriberName; ?>" /></p>
<p><strong>Your Email Address: </strong>
<input type = "text" name = "SubEmail" value = "<?php echo $SubscriberEmail; ?>" /></p>
<p><input type = "Submit" name = "Submit" value = "Submit" /></p>
</form>
<?php
}
?>
Your code, ignoring for now the ShowForm part at the end, is structured like this:
if this is a submit {
validate the form data
if there are no errors {
save the form data
}
}
This looks reasonable. Maybe your form isn't being submitted as a POST? Check your <form action> and also use Firebug to make sure the form data is being submitted.
If you were to move the error check, you would have:
if this is a submit {
validate the form data
}
if there are no errors {
save the form data
}
And that's wrong because if the form were not being submitted, then you'd have no errors (hence the "undefined variable" error) and then it would attempt to save the nonexistent form data.

mySQL php update

How can I update a row in my mySql database from a HTML form. I have tried every technique and nothing seems to work. I would like that users could update their own profile page information.
I have a form on my page but the data doesn't get sent through.
What am i missing?
Here is my code:
------------INDEX.php
<?php
require_once("inc/database.php");
require_once("inc/query.php");
?>
<div class="wrapper">
<div class="content">
<h1>User Profiles</h1>
<?php
while ($row = $results->fetch()) {
$id = ($row["id"]);
$name = ($row["name"]);
$age = ($row["age"]);
$password = ($row["password"]);
print '<div ' . 'class= id-' . ($id) . '">';
print "<p>" . ($name) . "</p>";
print "<p>" . ($password) . "</p>";
print "<p>" . ($age) . "</p>";
print "</div>";
}
?>
</div>
</div>
<form action="inc/addnew.php" method="post">
<p>Name: <input type="text" name="name" required></p>
<p>ID: <input type="text" name="id" value="<?php echo $id; ?>"></p>
<p><input type="submit" value="Lisää"></p>
</form>
------------QUERY.php
<?php
try{
$results = $db->query("SELECT name, password, age, id FROM users");
$results->execute();
// echo "Our query ran successfully.";
} catch (Exception $e){
echo "Data could not be retrived from the database.";
exit;
}
------------DATABASE.php
<?php
try{
$db = new PDO('mysql:host=localhost;dbname=user_profile;port=8889', 'User_profile','bFeLcZjMmVw4PBaF');
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$db->exec("SET NAMES 'utf8'");
} catch (Exception $e){
echo "Could not connect to the database.";
exit;
}
------------UPDATE.php
<?php
require_once("database.php");
if( isset( $_POST['name'] ) && strlen( $_POST['id'] )){
$id = $_POST['id'];
$name = $_POST['name'];
$results=("UPDATE users SET name='$name' WHERE id=$id");
}
header("Location: ../index.php");
}
else
{
//error either $_POST['login'] is not set or $_POST['login'] is empty form field
echo 'Name or ID field was empty. Please fill out those fields. Back to site <br>';
}
How you expect this query to execute?
$results=("UPDATE users SET name='$name' WHERE id=$id");
you are just generating a query here on UPDATE.php without actually doing anything with it.
Replace this line with:
$results = $db->query("UPDATE users SET name='$name' WHERE id=$id");
You need to prepare and execute your query, not just define it as a string:
$sth = $db->prepare("UPDATE users SET name=:name WHERE id=:id")
$sth->execute(array("name" => $_POST["name"], "id" => $_POST["id"]));
You should be using placeholders to insert your data. Your query uses string interpolation which is extremely dangerous due to SQL injection bugs. Do not put $_POST data directly into a query, it's never safe.

How to prevent rows with default values being submitted to MySQL database

I have a form with 2 sections, each of which starts out with one row and to which further rows can be added using a script. You can see the form on the bottom of this page.
The form uses default values and I am looking for a way of not submitting rows that contain default values (to both MySQL database and via email). Because people may only complete one row (i.e. at Waged or Unwaged rate), often I will only want one row of information to be submitted. The current code for the form is below.
Thanks for any help in advance,
Nick
HTML:
<form method="post" name="booking" action="bookingengine.php">
<fieldset>
<h2>Waged/Organisation Rate</h2>
<p>
<input type="text" name="name[]">
<input type="text" name="email[]">
<input type="text" name="organisation[]">
<input type="text" name="position[]">
</p>
<p><span class="add">Add person</span></p>
</fieldset>
<fieldset>
<h2>Unwaged Rate</h2>
<p>
<input type="text" name="name2[]">
<input type="text" name="email2[]">
</p>
<p><span class="add">Add person</span></p>
</fieldset>
<p><input type="submit" name="submit" id="submit" value="Submit and proceed to payment page" class="submit-button" /></p>
</form>
Script:
<script>
$(function() {
var defaults = {
'name[]': 'Name',
'name2[]': 'Name',
'email[]': 'Email',
'email2[]': 'Email',
'organisation[]': 'Organisation',
'position[]': 'Position'
};
// separating set and remove
// note that you could add "defaults" as an arg if you had different
// defaults for different fieldsets
var setDefaults = function(inputElements) {
$(inputElements).each(function() {
var d = defaults[this.name];
if (d) {
// set with jQuery
// we don't need the data - just check on the class
$(this).val(d)
.addClass('default_value');
}
});
};
var removeDefaults = function(inputElements) {
$(inputElements).each(function() {
if ($(this).hasClass('default_value')) {
$(this).val('')
.removeClass('default_value');
}
});
};
setDefaults(jQuery('form[name=booking] input'));
$("span.add").click(function() {
// get the correct fieldset based on the current element
var $fieldset = $(this).closest('fieldset');
var $inputset = $('p', $fieldset)
.first()
.clone()
.insertBefore($('p', $fieldset).last());
// add a remove button
$inputset.append('<span class="remove">Remove</span>');
setDefaults($('input', $inputset));
// return false; (only needed if this is a link)
});
// use delegate here to avoid adding new
// handlers for new elements
$('fieldset').delegate("span.remove", {
'click': function() {
$(this).parent().remove();
}
});
// Toggles
$('form[name=booking]').delegate('input', {
'focus': function() {
removeDefaults($(this));
},
'blur': function() {
// switch to using .val() for consistency
if (!$(this).val()) setDefaults(this);
}
});
});
</script>
PHP:
<?php
$emailFrom = "****";
$emailTo = "****";
$subject = "****";
$body = "****" . "\n\n";
$row_count = count($_POST['name']);
$row_count2 = count($_POST['name2']);
$values = array();
for($i = 0; $i < $row_count; $i++) {
// variable sanitation...
$name = trim(stripslashes($_POST['name'][$i]));
$email = trim(stripslashes($_POST['email'][$i]));
$organisation = trim(stripslashes($_POST['organisation'][$i]));
$position = trim(stripslashes($_POST['position'][$i]));
// this assumes name, email, and telephone are required & present in each element
// otherwise you will have spurious line breaks.
$body .= "Name: " . $name . " Email: " . $email . " Organisation: " . $organisation . " Position: " . $position . "\n\n";
//prepare the values for MySQL
$values[] = '(\'' . $name . '\',\'' . $email . '\',\'' . $organisation . '\',\'' . $position . '\')';
}
mysql_select_db($database, $connection);
$query1 = "INSERT INTO conference (Name, Email, Organisation, Position) VALUES " . implode(',', $values);
$result1 = mysql_query($query1);
if (!$result1) {
die('Invalid query: ' . mysql_error());
}
$body .= "****" . "\n\n";
$values = array();
for($i = 0; $i < $row_count; $i++) {
// variable sanitation...
$name = trim(stripslashes($_POST['name2'][$i]));
$email = trim(stripslashes($_POST['email2'][$i]));
// this assumes name, email, and telephone are required & present in each element
// otherwise you will have spurious line breaks.
$body .= "Name: " . $name . " Email: " . $email . "\n\n";
//prepare the values for MySQL
$values2[] = '(\'' . $name . '\',\'' . $email . '\')';
}
$query2 = "INSERT INTO conference (Name, Email) VALUES " . implode(',', $values2);
$result2 = mysql_query($query2);
if (!$result2) {
die('Invalid query: ' . mysql_error());
}
// send email
$success = mail($emailTo, $subject, $body, "From: <$emailFrom>");
// redirect to success page
if ($success){
print "<meta http-equiv=\"refresh\" content=\"0;URL=/conference/payment.html\">";
}
else{
print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
}
?>
I would use an IF statement in PHP assuming any validation you have has returned no errors.
For example
// SET VARIABLES
$name2 = $_POST['name2'];
// SET CORRECT VALUES
if($name2 == "Surname") { $name2 = ""; }
// RUN DB FUNCTIONS
I would do this for each default value allowing me to insert just what I need or want from the default values and remove or change the rest. It also means user data remains in tact.
I hope this helps you get on the right track :)

Categories