I am having trouble with my form adding to my database.
I have made the form and the script but am having trouble implementing them. Any ideas?
Table:
Here is the HTML form:
<form method="post" id="form2" action="home.php?id=<?php echo "$user_id";?>"> </br>
<h2>What would you like to ask? Rant away!</h2>
<input type="text" name="title" placeholder="Write a title" size="92px"/>
<textarea cols= "70px" rows="6px" name="content";>Description...</textarea><br/>
<select name="topic">
<option> Select Topic</option>
<?php getTopics() ;?>
</select>
<input type="submit" name ="submitbtn" value="Post to Timeline"/>
</form>
<?php
insert_post();?>
Here is the function - the file the function is in, is included in the HTML file using the include command at the top of the file.
function insert_post(){
if(isset($_POST['submitbtn'])){
global $con;
$title=$_POST['title'];
$content=$_POST['content'];
$topic=$_POST['topic'];
$insert="INSERT INTO `posts` ( `user_id`, `topic_id`, `post_title`, `post_content`, `post_date`)
VALUES ('$user_id','$topic','$title','$content',NOW()) ";
$run=mysqli_query($con, $insert);
if($run){
echo"<h3>Discussion posted</h3>";
}
}
}
EDIT:
For reference, the error I get when clicking the submit is a 404 which says "object not found".
EDIT 2:
Image of table shows the row is called pos_title whereas my own code says post_title. When code was edited to say pos_title, the same error still arose.
EDIT 3:
New errors after implementing some suggested changes:
Remove if(isset($_POST['submitbtn'])){ from the functions and add this above the form:
if(isset($_POST['submitbtn'])){
insert_post();
}
Change action to action="home.php".
Add this code to form:
<input value="<?php echo $user_id?>" type="hidden" name="user_id">
Add this code to insert_post function:
$user_id = (int)$_POST['user_id'];
Replace post_title to pos_title or alter your table.
You don't need the quotes in '$user_id', '$topic', but MySQL will still accept it.
$insert="INSERT INTO `posts` ( `user_id`, `topic_id`, `post_title`, `post_content`, `post_date`)
VALUES ('" . $user_id . "','" . $topic . "','" . $title . "','" . $content . "',NOW()) ";
Try this code. You should concatenate using the . instead of inserting variables in the string:
$run=mysqli_query($con, $insert);
if($run) {
echo"<h3>Discussion posted</h3>";
} else {
echo mysqli_error($con);
}
NOTE:
also for debugging purposes you should check mysqli_error($con); if there's an error.
<form method="post" id="form2" action="home.php?id=<?php echo $user_id;?>"> </br>
When you echo a variable there is no need for double quotes. It is a variable not a string.
<textarea cols= "70px" rows="6px" name="content">Description...</textarea><br/>
And you have a semicolon after name="content" that should not be there as well.
I want to thank you all for your time and effort and help. It turned out there had been a syntax error about 400 lines higher than this form at the previous form, where I'd typo'd when closing it. So the question I had asked was unsolvable for you as it turns out the code shared was more or less fine. So very big apologies for my mistake guys and thanks so much for all your help. This has certainly taught me to clean up my html files and not let them get so big!
Related
i am trying to get text from a text box into my database, but it wont go through. i have tried so many things please help!! the else statement always executes, because I get the message "no submission received on my webpage", which means the first if statement definitely executes.
As FirstOne said you need to name the input "submit".
<input class="input" type="submit" name="submit" value="شارك"/>
Hello There are two problem's with your code ..
First one add name attr in your submit button because you are checking isset($_POST['submit'])
<input class="input" type="submit" name="submit" value="شارك"/>
Second Update Your $query with this
$query= "INSERT INTO hamsasubmissions (secret,popularity) VALUES ('".$_POST["newSecret"]."',0)";
first of all you didn't give the submit button a name so you must name it 'submit' to match what you wrote in your code and also your SQL query seems to be incorrect, here's a snippet with the desired changes:
<form method="post" action="post.php">
<textarea name="newSecret" id="help" class="textarea" rows="20" cols="100">
</textarea>
<input class="input" name="submit" type="submit" value="شارك"/>
</form>
<?php
if(isset($_POST['submit'])) {
// trim possible begining/ending whitespaces from the the textarea value. But you still need to escape it againt SQL injection !
$newSecret = trim($_POST['newSecret']);
if(isset($newSecret)[0]) {
include "db_connect.php";
$query= "INSERT INTO hamsasubmissions (secret,popularity) VALUES ('" . $newSecret . "', 0)";
if(!mysqli_query($mysqli,$query)){
echo "no submission received";}
else{echo "Secret submitted.";}
}
}
?>
I am currently working on a form that uses PHP and SQL to update information in a database. It is functioning properly and updating the information but the issue is... is that it updates everything, including fields that I didn't even put any input in which means it will only update a particular row in the database and leave the others blanks... I need it to just change information from a field with an actual input and leave it if there is no input.
Here is the PHP and SQL code:
try {
$deleteRecId = $_GET['id'];
$update_event_name = $_POST['updateName'];
$update_event_location = $_POST['updateLocation'];
$update_event_date = $_POST['updateDate'];
include 'connect.php';
if(isset($_POST["submit"])) {
// new data
$sql = "UPDATE events SET event_name='$update_event_name',
event_location='$update_event_location', event_date='$update_event_date'
WHERE event_id=$deleteRecId";
// Prepare statement
$stmt = $conn->prepare($sql);
// execute the query
$stmt->execute();
// echo a message to say the UPDATE succeeded
echo $stmt->rowCount() . " records UPDATED successfully";
}
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
and here if the form:
<form class="update-form" action="<?php echo $_PHP_SELF ?>" method="post">
<p id="input-headers">Event Name</p>
<p id="update-input-field-wrapper">
<input type="text" name="updateName" value="">
</p>
<p id="input-headers">Event Location</p>
<p id="update-input-field-wrapper">
<input type="text" name="updateLocation" value="">
</p>
<p id="input-headers">Event Date</p>
<p id="update-input-field-wrapper">
<input type="text" name="updateDate" value="" placeholder="01/01/2000">
</p>
<input type="submit" name="submit" value="Submit" id="updateBtn">
</form>
So to sum up I need this application to only update information of a field with an actual input and if the form field has no input I need that database info to remain the same. I appreciate any help with this as I am pretty new to these concepts... thanks!
I found a really handy solution to this! Here is how I implemented it into my code.
$sql = "UPDATE events SET event_name=IF(LENGTH('$update_event_name')=0, event_name, '$update_event_name'), event_location=IF(LENGTH('$update_event_location')=0, event_location, '$update_event_location'), event_date=IF(LENGTH('$update_event_date')=0, event_date, '$update_event_date') WHERE event_id=$deleteRecId";
It basically just checks whether the string is empty or not. If it's empty it won't be updated. If it isn't empty it'll go through with the update! Very simple way to achieve this effect when creating an update form.
Using your current code structure, you can do this.
Use SQL to select * from event ID. Populate your update_event_xxx with the parameters.
If $_POST[xx] is blank, ignore. Else, update_event_xx = $_POST[xx]
I'm making a storage log for work, and I've been fighting with this code for the last two hours with no success. For some reason, no matter how many times I check and recheck the code for my INSERT INTO query, it will not work.
Keep in mind that I copied this code, almost verbatim (changed the form names and fields, obviously) from another page that has basically the same functionality and works 100%. Code below:
This is the page containing the form where the transaction is being submitted:
<?php
$script = '<script>
$(document).ready(function(){
$(".datepicker").datepicker();
}); </script>' ;
$title = "View/Edit Storage - " ;
include('inc/header.php');
?>
<table>
<tr>
<form action="transadded.php" name='addnewtransaction' method="POST">
<td><input type="text" name="moveID" size="20" value="<?php echo $results[moveid]; ?>" readonly> </td>
<td><select id="inoutselect" name="inorout">
<option value="Select">Select</option>
<option value="Storage In">Storage In</option>
<option value="Storage Out">Storage Out</option>
</select> </td>
<td><input type="text" name="numberofunits" size="20"></td>
<td><input type="text" name="dateoftransaction" size="20" class="datepicker"></td>
<td><input type="text" name="rrdt" size="20"> </td>
<td><input type="submit" value="Add" id="logsubmit"></td>
</form>
</table>
<br /><br />
<?php };?>
Here's the query itself, aka "transadded.php":
<?php
$title = "Project Added - ";
include('inc/header.php');
$query = "INSERT INTO newtransaction (moveid, inout, units, transdate, refno) VALUES('$_POST[moveID]','$_POST[inorout]','$_POST[numberofunits]','$_POST[dateoftransaction]','$_POST[rrdt]')";
if(!mysqli_query($con,$query))
{
die ('Error: ' . mysqli_error($con));
}
echo '<div class="transstatus">' . '1 record added' . '</div>';
mysqli_close($con);
?>
The header, obviously, contains the function for connecting to the database, and as I said, another query works just fine with it, so I know that that isn't the problem. Upon clicking the submit button, the error I get on the page is as follows:
Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'inout, units, transdate, refno) VALUES ('1234567','Storage In','81','09/11/2013'' at line 1
Here, "1234567", "Storage In", etc are the values I enter into the form.
I hope you can help me out. I'm so stuck!
Also, I know that I'm not protected against injection right now. I plan to work on that later, but I'm trying to get the functionality straightened out first.
INOUT is a MySQL reserved word.
See here: http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html
Change the name or put it in quotes.
Use the following:
$query = "INSERT INTO newtransaction (
`moveid`, `inout`, `units`, `transdate`, `refno`
)
VALUES(
'{$_POST[moveID]}', '{$_POST[inorout]}',
'{$_POST[numberofunits]}', '{$_POST[dateoftransaction]}',
'{$_POST[rrdt]}'
)
";
$query = "INSERT INTO newtransaction (moveid, inout, units, transdate, refno)
VALUES
( '".$_POST['moveID']."','".$_POST['inorout']."','".$_POST['numberofunits']."',
'".$_POST['dateoftransaction']."','".$_POST['rrdt']."')";
you post your like ='$_POST[dateoftransaction]'
right procedure is if you using wamp= '".$_POST['dateoftransaction']."'
i hope you got your mistake
Ferrakkem
I have a small (42 hours) problem with my code trying to edit article
- just the basic editNews.php
When I choose article to edit the data appears in the forms from the DB and when
I hit "update" it returns no error but the data wasn´t updated
<?PHP
connection to database blah blah
?>
<?php
if(isset($_POST['update']))
{
$newsid = $_POST['newsid'];
$date=$_POST['date'];
$time=$_POST['time'];
$location=$_POST['location'];
$result=mysql_query("UPDATE news SET date='$date',time='$time',location='$location', WHERE newsid=$newsid");
header("Location: listNews.php");
}
}
?>
<?php
$newsid = $_GET['newsid'];
$result=mysql_query("select * from news where newsid=$newsid");
while($res=mysql_fetch_array($result))
{
$date = $res['date'];
$time = $res['time'];
$location = $res['location'];
}
?>
This is the form - just the normal one....
<form method="post" action="editNews.php" name="form1">
each item is like
<input type="text" name="headline" value="<?php echo $location;?>" id="UserName">
and
<input type="hidden" name="newsid" value=<?php echo $_GET['newsid'];?>
<input name="update" type="submit" value="update" />
Most likely there is something that I don´t see but "seeing" has taken almost 2 days now
... Is there a possibility I don´t have "edit" privileges in the mySql?
How do you know there was no error? Your code lacks:
print mysql_error();
Add it right after the UPDATE query.
Also your code is most likely to fail whenever the submitted content itself contains single quotes. To send correct SQL to the database it's advisable to apply mysql_real_escape_string() on all input variables.
Try
$result= mysql_query('UPDATE news SET
date = "'. $date .'",
time = "'. $time. '",
location = "' .$location. '"
WHERE newsid = '.$newsid.';') OR die(mysql_error());
I have a simple Form along side a PHP update query that simply isn't working! I know the PHP is working on the page as there are several validation checks that need to be passed before hand which are working perfectly. The form its self is inside the Colorbox Popup tool.
My HTML Form Code is:
<div id="stylized" class="myform">
<form action="#" method="post">
<input type="hidden" name="user_id" value="<?php echo $user_id; ?>" />
<label>First Name:<span class="small">Enter your forename</span></label>
<input id="first_name" type="text" name="first_name" maxlength="50" placeholder="e.g. Joe" required autofocus/>
<div class="spacer"></div>
<input type="submit" id="update" name="update" value="Continue to Step 2!">
</form>
</div>
With the PHP Code as follows (this is above the HTML code on the page):
<?php
if($_POST['update']){
$user_i = $_POST['user_id'];
$f_name = $_POST['first_name'];
$first_name = ucfirst($f_name);
mysql_query("UPDATE user SET first_name = '$first_name' WHERE user_id = '$user_i'") or die(mysql_error());
} ?>
The actual submit appears to be working, with the Popup refreshing afterwards, but the database does not update! I have triple checked the syntax and the database fields. 'user' and 'first_name' and 'user_id' is correct.
Update: Because the popup box refreshes, I cannot view the error's from the 'or die(mysql_error()) unfortunately, other wise i might have been one step closer.
Any help would be hugely appreciated.
Many thanks in advance.
When you say pop-up box, I assume you are using ajax to communicate from the form to the server, which as you stated is difficult to view submitted data. If this is the case try:
error_log(serialize($_POST));
This will force an entry in your error log with the $_POST data in serialized format, so you can check the values you are submitting are populated correctly.
You will also want to sanitize the variables you are adding to the SQL:
$sql = "UPDATE user SET first_name = " . mysql_real_escape_string($first_name) . " WHERE user_id = " . mysql_real_escape_string($user_i) . " LIMIT 1";
mysql_query($sql);
I would:
print_r($_POST); to view the POST data.
Generate the SQL from a string so it can be printed for debugging purposes, like so:
$sql = "UPDATE user SET first_name = '$first_name' WHERE user_id = '$user_i'";
echo $sql;
mysql_query($sql) or die(mysql_error());
One of these techniques will likely tell you why the PHP-generated SQL doesn't update your database record.
you set your user_id field by echo $user_id; but your variable name is set to $user_i = $_POST['user_id'];
therefore your user id field is not set and your Mysql command will fail.