SQL Comment table insert statement - php

I want to develop a system where a user should be able to post the comments on the author published news.
I am very much confused about the Insert Statement that i should be using to store the user commenting system, i have two mysql table one is news and another is comments below is the screenshot of two tables.
news
comments
in the comments table i have defined a foreign key (new_id) , in which i want to store the value that is related to the particular news for example a news with id no. 7, how do i achieve this dynamic feat? how do i automatically relate it to the news when a user post the comment (nevertheless to say that the user will be giving the input from the form )?
EDIT : I want to use One news article on one page.
thank you

Well first off you need to know how you are going to view a news item? Is this going to have all news articles on one page and below each news article is a to post new comments? If so then each of these forms generated per news article should have the news ID in the form potentially as .
Example:
<p>News article 1.</p>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="hidden" name="new_id" value="1"/>
<textarea name="comments"></textarea>
<input type="submit" name="submit" value="Post COmment"/>
</form>
<p>news article 2</p>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="hidden" name="new_id" value="2"/>
<textarea name="comments"></textarea>
<input type="submit" name="submit" value="Post COmment"/>
</form>
Then on this page at the top you can check for whether or not user pressed submit button:
<?php
if(isset($_POST['submit'])){
//$_POST['new_id'] is news article id
//$_POST['comments'] is comments for this
//sql to store new_id = $_POST['new_id'] and comments = $_POST['comments']
{
Alternatively:
Lets say on your home page you have links to each news article and you retrieve them on subsequent page using $_GET. So index.php displays news and getNews.php is where news is displayed. You could want to on index.php generate a link to getNews.php?id=
THis way on getNews.php you know which news article to get using $_GET['id'] and you can easily post comments to this using a similar technique to above, take $_GET['id'] and toss it into your form on getNews.php as hidden field.
Caution: be careful and sanitize your $_GET variable before using it.
?>

first your structure looks good.
i assume "new_id" is id of the newspost!
i would switch from datetime to timestamp. its range is smaller but i dont think you are gonna have posts in the past? and it has additional features like automatical timezone conversion.
anyways! the usual approach is to include the "news_id" as a hidden form field in the form that is used to submit the comment!
then you can fetch it with $_POST["whatever-you-named-it"];
and then you construct your insert statement... dont' forget to mysql_real_escape_string() every user supplied data to avoid mysql injection.

Generally that id (the id of the entity you're attaching something to) is either in the URI the form is POSTed to, or is simply a hidden element in the form.
For example:
<?php
//somehow you need to set this value, if the comment form is on the same
//page as the news then you should already have this id. If not, then you
//have to provide the 'stand-alone' comment page with the id you expect it
//to be using
$new_id = 7
<form method='post' action='/news/<?php echo $new_id ?>/comment/'>
<input type='hidden' name='new_id' value='<?php echo $new_id ?>'>
<input tyle='text' name='Name'>
...
</form>
With that form you can either parse the URI to determine what the foreign key should be, or use the hidden field.
Update: Showing how to use both $_GET and $_POST (so you don't have to parse the URI):
<form method='post' action='/comments/?new_id=<?php echo $new_id ?>'>
As always, check all user input, regardless of where it comes from (the URI, a POST a GET).

you could add an hidden input field to your comments form like this:
<input type="hidden" name="new_id" value="7"/>
Then in your php code you get the value via $_POST['new_id'] or $_GET['new_id'] depending on what method you're using.
The you can use the following code to generate the SQL:
$new_id = mysql_real_escape_string($_POST['new_id']);
$comment = mysql_real_escape_string($_POST['comment']);
$sql = "INSERT INTO comments (comment,new_id) VALUES ('$comment','$new_id')"
If shortened it, you still have to add the other values. But I hope now it's clear how you can do this.
If you don't want to use the hidden field you can add a get parameter to the action url like this:
<form action="your_script.php?new_id=<?= $new_id ?>">
Then you get it as $_GET['new_id'].
Update:
If you're concerned for security and want to make sure nobody ist trying to forge a request, you should take a look at http://www.codewalkers.com/c/a/Miscellaneous/Stopping-CSRF-Attacks-in-Your-PHP-Applications/1/

You asked about the SQL INSERT statement, so I assume you are concerned simply with the SQL...
Using AUTO_INCREMENT, LAST_INSERT_ID(), and TRANSACTION...
Set [news].[id] to be an AUTO_INCREMENT value type. Then using a transaction, you should be able to do something like this:
START TRANSACTION;
INSERT INTO news VALUES('2010-08-21','','','','','')
INSERT INTO comments VALUES(,'2010-08-21','','','','','',1,LAST_INSERT_ID())
COMMIT;

Related

update_options not updating wp_options table

I am making a form for the admin area of WordPress. Here is the code so far;
<form method="post" action=options.php">
<?php update_option('gpspl_options', $gpspl_options);?>
<input type="text" name="gpspl_options" value="$gpspl_options"/>
<input type="submit" value="Save Changes"/>
</form>
On the page in the admin area the text box is auto filled with "$gpspl_options". However when I add the text and hit submit it does not update the wp_options table in the database.
What am I missing?
You always call update_option() on whatever is stored in $gpspl_options. You never do anything with the posted value ($_POST['gpspl_options']). So the posted value never gets saved. If you want to save the posted value, you need something like this:
if (isset($_POST['gpspl_options'])) {
update_option('gpspl_options', $_POST['gpspl_options']);
}
As for the text field, you always initialize the text field to the literal string "$gpspl_options" (not the value of the variable $gpspl_options). To use the value, you need something like this:
<?php
$gpspl_options = isset($_POST['gpspl_options']) ? $_POST['gpspl_options'] : '';
?>
<input type="text" name="gpspl_options" value="<?php echo $gpspl_options; ?>"/>
You might want to read an introductory PHP tutorial covering variables, variable names, output, and so on.
That said, all this mixing of logic and output is not good practice. It's what Wordpress does and therefore kind of encourages, but that doesn't mean you should do it, too.

How to get the right forms value from a button click

Overview of what my question is:
I have an array that is populated via XML inputs, and from this I am the using it to populate a web form with form controls. From here I want to be able to select the exact form that is clicked, but to do that I need to give the controls some form of unique identifier, which is an issue...
As the site is of a betting nature and I am currently working with horse racing, each horse is given a unique identifier by default, I have tried to add this identifier to the forms.
e.g:
<?php
//Values from feed examples: 123, 234, 345
$valuesFromFeed = array(123, 234, 345); //These are not in my code, they are values from the XML feed
while ($uniqueIdentifier = $valueFromFeed) {
<form name="horse_<?php echo $uniqueIdentifier; ?>_frm" action="#">
<input type="hidden" name="horse_<?php echo $uniqueIdentifier; ?>" />
<input type="button" value="Place bet" />
</form>
}
?>
But then the problem comes when I try to reference this name of "horse_123", I need to know exactly what the value of that name is, which is impossible as there are millions of horses, tracks and races.
Example of trying to get post:
<?php
if (isset($_POST['horse_' . $uniqueIdetifier])) {
echo "You got the right thing here.";
} else {
echo "Still no joy.";
}
?>
The issue with the code above, is that once the $uniqueIdentifier has been used in the while above, it is removed and is no longer usable in this scope.
So to conclude, my point and question:
How do I get the correct name from the form in a submit for the specific horse that I wish to reference and get information on?
How do I use this information as I need to?
Better Description:
I have been given an XML feed and site as part of a handover, this feed contains many hundreds of races and horses.
When this information is loaded into the page, it is also stored in a database on the server, as well as sending it through some different loops (which are messy, but someone else's code I'm trying to clean up!) which split it down and then make up a dynamic menu containing all the races, horses, odds and information. (All information on a single horse within a race is kept in one form)
Next to the information stated in the prior paragraph, is 2 buttons, one that allows the user to take odds and another that allows users to take starting price.
On either of these button clicks, I need the information attached to said horse, and then populate a betting slip. In the form (mentioned above) the name is "horse_<?php echo $uniqueIdentifier; ?>_frm".
The problem that occurs to me is, yes data is stored on the server when it is loaded, that I cannot seem to get the right form via the unique identifier that is put into the form name
Edits
Added form surrounding my input as this is there, I just missed it in original question
Added the button that transmits data to where I need it
Added a better description of my problem
You can use multiple forms, one for each horse. Each form has a different action, where the URL includes the id of the horse. For example:
<form action="/horses/my_unique_horse_name">
...
</form>
<form action="/horses/another_horse_name">
...
</form>
Or you could have multiple forms all with the same action, with a hidden field for the name of the horse:
<form action="/horses/">
<input type="hidden" value="my_unique_horse_name">
</form>
<form action="/horses/">
<input type="hidden" value="another_horse_name">
</form>
Alternatively, you could have a button for each horse:
<form method="/horses/">
<button type="submit" value="my_unique_horse_name">My Horse</button>
<button type="submit" value="another_horse_name">Another Horse</button>
</form>
Beyond that, I don't entirely understand the problem. What kind of data are you submitting and retrieving?

Sending value from a form to a html tag counter

I am looking for a bit of code to do the following:
A form containing a single text field and a submit button, must send the value of the text field to a landing page that automatically counts how many html tags that this page contains.
E.g. if the text field states stackoverflow.com, the landing page should say (H1 tags = 20) with many more parameters to come.
How is this done? I know how to make a form, but I do not know how to make it send its value to the landing page.
<form action="landingpage.php/" method="post">
The URL
<input type="text" name="cf_name">
<input type="submit" value="Submit">
</form>
This piece of code is a perfect answer to your question.
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="GET">
Type In Something: <input name="random-info" type="text" size="25">
<input type="submit" value="Submit">
</form> <br>
<?php
echo "You Typed: " . $_GET['random-info'];
?>
you get the method into the url, then you can use them on another page.
To access data from a form it depends on the method. Since your code shows a post message you simply access it in the php on the landing page by user $POST_['cf_name'].
To learn more you can check out:
http://w3schools.com/php/php_post.asp about the post method and http://w3schools.com/php/php_get.asp about the get method.
Also an invaluable source is php manual itself.
As far as counting the tags, not really sure what you are trying to achieve.
If you are counting the tags in the page you create, just make a variable and add to it each time you put that specific tag on the page.
Then you can put those values in a hidden field of the form to be passed into your landing page.

Can I include a forms value into the action redirect in php?

Is it possible in php to include a forms value into the action redirection?
For example:
<form method='POST' name='Select' action='customer.php?CID=xxxxx'>
<input type=text width='5' name='searchVal' />
where xxxxx is the value entered into the form.
I've tried a number of different ways and I'm just not figuring it out! (Still sort of new to php) Any help would be appreciated.
It was looking like I would have to use $_POST and $_GET. A little more information might be in order... customer.php displays a list of customers in order by ID, name, etc. The user currently clicks on the customer ID that they want to display the details for. I'm trying to add a box where they can just enter the customer number to get to the details quickly, but I still want to have the listing displayed. From what it is sounding like, I will have to do this as two separate programs...is that true?
How about this:
<form method='POST' name='Select' action='customer.php'>
<input type='hidden' value='xxxxx' name='CID' />
<input type=text width='5' name='searchVal' />
...
</form>
You are free to add as much hidden values as needed.
Note, that you can even use PHP-like array notation_
<input type='hidden' value='xxxxx' name='CID[1]' />
<input type='hidden' value='yyyyy' name='CID[2]' />
At the PHP-side, access those values using this syntax:
$_POST[ 'CID' ][ 1 ]
$_POST[ 'CID' ][ 2 ]
UPDATE-1
Ah, you want to use a user-entered values to the Action URL just before the form gets submitted?
In this case you need to use JavaScript. Access the DOM to change the Action URL.
But let me ask, why you need to post a form value additionally as a parameter of the Action URL?
UPDATE-2
You wrote: 'From what it is sounding like, I will have to do this as two separate programs...is that true?'
No, actually not. You can still use one customer.php which checks at its beginning, if it was called using a linked customer in the table element or a searched customer in the search field.
In other words: You don't need to prepare two scripts, but two forms for two purposes which call the same script customer.php.
You can include the required value in a hidden field in your form:
<input type="hidden" name="CID" value="xxxxx" />
The reason this is required is that you are submitting the form to your server via POST, but appending parameters to the URL requires submission via the GET method.
Not without a post to the server. The value in the form is filled in client-side, so it has to return to the server before you can add it to the action. (at least, if you want to use php).
You can either
add it after posting (might not be usefull)
use javascript
just not use the GET CID, but get it out of the POST in your customer.php script.
I got it finally! It's actually very simple!
In the body of the code I put this:
<form action='#_SELF' method='GET' name='Projected'>
<input type=text size=5 name='CID' value='' title='Enter Customer number to display' />
<a href='#' onclick='document.Projected.submit();' title='Enter Customer number to display'>Go</a>
And at the top of the code I just do a:
if (!isset($_GET['CID'])) { ...
It works exactly the way I wanted it to!
Thanks everyone for the help! I appreciate it! (And I'm learning more and more about PHP everyday!)
Im pretty sure you cant do that unfortunately

php secure comment logic?

Ok, this might be obvious but its not clicking quite yet. I am creating a forum/blog esque app.
I grab the posts from the database rather securely but commenting is beginning to be a little more difficult. (I could just be paranoid, right?).
How do I add a comment without exposing the id of the parent message? (like in a hidden form field or query string, or something).
I guess I am a bit paranoid that someone might go into the code with firebug or something and change the hidden form field value to something else before submitting. I guess I would have to make sure the user has permission to comment to that particular post/category?
Things to note :
The user is already logged in.
Its not a public post
I would recommend that you setup your database like so:
Comments
---------
id
encodedID
authorID
parentID
message
Then, for the form field have two hidden values, one will be the encodedID, and the second will be a hash that you make. I would recommend the hash to be:
<?php
$hash = sha1(md5($encodedID . $userID . $_SERVER['REMOTE_ADDR'] . "abc1234"));
?>
Then, when the user submits the form, validate that the hash is valid for the specific encodedID and user. Here is a brief code write up:
<?php
if(isset($_POST['submit']))
{
//Get the variables and all and sanitize the input of 'message'
if(sha1(md5($_POST['value1']. $userID . $_SERVER['REMOTE_ADDR'] . "abc1234")) == $_POST['value2'])
{
//User is valid.
}
else
{
//Invalid user.
//Document this.
}
}
$value1 = $encodedID; //Grab this from your database
$value2 = sha1(md5($value1 . $userID . $_SERVER['REMOTE_ADDR'] . "abc1234"));
?>
<form method="post" action="comment.php">
<input type="text" name="message" />
<input type="hidden" name="value1" value="<?php echo $value1; ?>" />
<input type="hidden" name="value2" value="<?php echo $value2; ?>" />
<input type="submit" name="submit" value="Comment" />
</form>
Edit: Just a small tip, but I would recommend that you change value1 and value2 to something abstract, don't call it encodedID or anything like that, just so that it confuses any users that will attempt to try and break it.
And yes md5 and sha1 are not completely secure, but for this case it will work since you want to be able to process the comments fast and efficiently.
That might be an overkill but if you really want to hide the post_id of the current message then you should consider using session. So instead of using something like this on your form:
<form action="/postcomment.php" method="post" >
<input name="post_id" type="hidden" value="123" />
<textarea name="message"></textarea>
</form>
Reduce it to something like this:
<?php $_SESSION['post_id'] = '123'; ?>
<form action="/postcomment.php" method="post" >
<textarea name="message"></textarea>
</form>
Of course this is "yucky" coding but at least you get the idea.
Oh, don't forget to validate EVERYTHING on postcomment.php. Also escape ALL string input values and make sure all numeric inouts are numbers indeed (multiply them by one?).
[EDIT: Due to insistent public demand, may I, if you please, amend the aforementioned:]
Instead of:
<?php $_SESSION['post_id'] = '123'; ?>
Generate a form id:
<?php $_SESSION['form_id'] = $_SESSION['user_id'].'_'.md5(time()); ?>
Then generate the unique post_id:
<?php $_SESSION[$_SESSION['form_id'].'_post_id'] = '123'; ?>
After submitting get the post_id:
<?php $post_id = $_SESSION[$_SESSION['form_id'].'_post_id']; ?>
you could assign the form an "id" as a hidden field and create a database table to track form ids and their associated post ids, that way when the form gets submitted you could check the post id in the db without ever sending it to the client based on the form id that is returned with the post
You're asking the wrong question here: instead of being concerned about the user getting some internal ID that means nothing outside your application, your primary concern should be about keeping them from doing anything unpleasant with it.
Imagine I just started sending POST requests to add a comment for every ID between 1 and 10,000. I'm sure to hit a real post sooner or later.
Rule #1 about writing secure web applications: Don't trust the user.
In other words, yes, you should check to make sure that they have permission to comment when you receive the results back from the from.

Categories