I decided to open a new question for this topic, as I have been having issues with it. My blog has a mysql database with the table posts complete with a post_user field. Each user has a form and can submit a post to a public blog. Once they submit this form, complete with a title and a body, when it is posted on the blog it should say by Username. My idea is that I can save the username to the post_user in the database upon form submission using $_SESSION info, but I am not exactly sure how to do this. Any help would be greatly appreciated.
The form, with the old UNSECURE way of entering the session author, note I am only including session data in the form to display what I am trying to show on a blog post, I don't know how to do it any other way hence my question:
<form action="" method="post">
<p>
<input type="hidden" name="user" id="user" value="<?php echo $_SESSION['user']['username'] ?>" readonly />
</p>
<p>
<input type="hidden" name="userid" id="userid" value="<?php echo $_SESSION['user']['id'] ?>" readonly />
</p>
<p>
<label for="title">Title: </label>
<input type="text" name="title" id="title" />
</p>
<p>
<textarea name="body" rows="20" cols="60"></textarea>
</p>
<p>
<input type="submit" value="Add Post" />
</p>
</form>
Code that posts the entry:
$posts = get_posts();
foreach($posts as $post)
{
?>
<h2><?php echo $post['title']; ?></h2>
<h4>By <font color="#FF6347"><?php echo $post['user']; ?></a></font> on <?php echo $post['date']; ?></h4>
<h4><?php echo $post['total_comments']; ?> comments, last comment <?php echo $post['last_comment']; ?>
<hr />
<p><?php echo $post['preview']; ?></p>
<?php
}
?>
You shouldn't save the username on the posts table. You should have two separate tables: one for the posts and one for the users, which are linked via a user_id field, a.k.a foreign key.
This is the way relational databases, such as MySQL, operate. This serves a few purposes:
You avoid repetition in case of one to many relations, which is exactly your case: one user can post many posts.
You use a unique identifier.
The information is organised better instead of mixing data together.
The way to tie the tables together when retrieving data is by using a JOIN statement, which links the two tables via the common user_id field. It is highly recommended to make this field an index, which would significantly speed up data retrieval. (Think about the difference between finding a certain word or sentence in a book by scanning through each and every page, and finding a chapter using the, well, index)
To sum up, you should have an id key in your $_SESSION super-global array, which you then insert to the user_id field upon post submission.
As for your question, you don't need to send the session data with a hidden input field, because it will be available even after submission - after all this is what session is all about. So why convert it to $_POST and expose it publicly?
Related
Below is my form- which value i like to update into database.
<form action="#" class="form">
<div class="form__slider">
<div class="form__slider-rating" id="slider__rating"></div>
<div class="form__slider-value" id="form__slider-value"></div>
<!-- <input type="number" class="form__slider-value" id="form__slider-value" value=""> -->
</div>
<input type="hidden" name="movie_id" id="movie_id" value="<?php echo $post_id; ?>" />
<input type="hidden" name="name" id="name" value="<?php echo $userName; ?>" />
<textarea class="form__textarea" name="remark" id="remark" placeholder="Review"></textarea>
<button type="button" class="form__btn">Send</button>
</form>
and in site it was look like this
This blue mark value I need to update into database. How to do that?
Regarding PHP, you need to handle a form.
Firstly, write a code that would handle the form itself, you can do that, by putting some php on top of your page;
if(isset($_POST['form-slider-value'] && $_POST['form-slider-value'] !== null) {
$value = $_POST['form-slider-value'];
//Database handle
}
Of course don't forget to add name 'form-slider-value' to the input.
Ideally there would be classes or similar stuff for that, I'd advise you to use some kind of framework.
Basically. PHP and FORMS works with handling them, once you submit your form with a button submit, it goes to a place where you address it Form action=. Then everything that is written within names will be at $_POST data.
It is not recommended to keep standalone code in one file, with HTML,css,PHP all together.
Hope that answered your question.
As well. This thing is very common to do or use. I advise you to learn about PHP Forms.
https://www.w3schools.com/php/php_forms.asp
And read about constructing a class. Id say do it the proper way.
Learn about frameworks as well, they are modern day time saviors once you learn it.
I'm making a social network type site, where users can upload their items to be rated. However, I'm trying to improve the way the site is laid out, so want to automatically generate pages once the user inserts a new item. The add.php page has the following form:
<form action="add.php" method="post" autocomplete="on" enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" id="pic">
<p> <label for="jname" class="iconic user"> Name of Jam <span class="required">*</span></label> <input type="text" name="jname" id="jname" value="<?php if (isset($_POST['jname'])) echo $_POST['jname']; ?>" required="required" placeholder="Input your Name of Jam here" /> </p>
<p> <select name="jtype" id="jtype" value="<?php if (isset($_POST['jtype'])) echo $_POST['jtype']; ?>" required="required">
<option value="jam">Jam</option>
<option value="jelly">Jelly</option>
<option value="marmalade">Marmalade</option>
<option value="preserve">Preserve</option>
</select> </p>
<p> <label for="producer" class="iconic user"> Jam Producer <span class="required">*</span></label> <input type="text" name="producer" id="producer" value="<?php if (isset($_POST['producer'])) echo $_POST['producer']; ?>" required="required" placeholder="Input the producer of the Jam here" /> </p>
Upload a picture of your jam: </br> </br> <input name="userfile" type="file" /> </br>
<input type="submit" name="submit" value="Register" />
<input type="hidden" name="submitted" value="TRUE" />
</form>
When the form is submitted, I then want it to generate a new page for that new user created item. Is there a fairly simple way of doing this?
Cheers
You don't have to actually 'create' new html page for each item.
You could save this information to database (mysql for example).
Then you could create another php file, say 'item.php' and access different entries from mysql database like so:
item.php?id=1
This generally isn't the way such sites are created. (i.e.: You don't generate the physical pages themselves at the point of form submission.) Instead, you'd usually store the form data in a database and then retrieve/display it based on the URL - either by decoding the URL itself via a "controller" or by using a query string variable such as ?producerid=x. This data would then be used to populate a template.
To be honest, I'd really recommend getting hold of a recent PHP book (as far as database access is concerned, you should be using PDO or MySQLi) or following some online tutorials - whilst it might initially seem like this won't be a meaningful form of progress, its likely to pay substantial dividends in the long run.
The best and efficient way to do it is to store the data in a database and retrieve it whenever user clicks on specific item. One thing though, if part of your plan is to make your site accessible by google search engine, you have to generate the individual web pages... because, google is only a web crawler...it cant get into mysql or other databases.
Usually there's no new page generation for things like that. You should create a template and load dynamic informations from other sources (such an XML file or a database) to it so that it seems a completely new page.
Just:
See what each item page has in common
Define a template which contains the common code
Retrieve dynamic informations (item infos for example) from a database
Use PHP embedded in HTML to load dynamic HTML
An example:
Facebook does not create a new page per each user registration. There's an HTML template which defines the position of the profile photo, the position and style of the posts, the position and style of the friend list and stuff common to any profile page, and then just load different informations when you call such a page for Mark, Frank, Jeff and so on.
Having looked at various similar questions, both on SO and elsewhere, I have a horrible feeling what I want to do is impossible, but here goes.
I have a page that is a table of text input rows. The user enters information on each row, and submits the data to a separate file, which creates a PDF.
The problem is that I need the user to be able to add rows to the table at will, since the amount of data can vary.
[Before you go there, I need to point out that I cannot use Javascript for any of this - I know it is easy to do in JS but the page needs to be accessible.]
Here is a very simplified version I just cobbled together to (hopefully) illustrate the point:
<?php
if (filter_has_var(INPUT_POST, 'add_rows')) {
$howmanyrows = filter_input(INPUT_POST, 'howmanyrows', FILTER_SANITIZE_NUMBER_INT);
//get all the data from table and put it in an array,
//then add 5 (or however many) new rows to said array.
}
else if (filter_has_var(INPUT_POST, 'send_data')) {
//get table data, add to session and redirect to other page with a header()
}
?>
<html>
<form action="" method="POST">
<table>
<?php //table rows added using an array of data
foreach ($data as $d): ?>
<tr><td><input type="text" value="<?php echo $d; ?>"></td></tr>
<?php endforeach; ?>
</table>
<input type="text" name="howmanyrows" value="5">
<input type="submit" name="add_rows">
<input type="submit" name="send_data">
</form>
...
</html>
As you can see, at the moment I have a clunky setup where there is just one form that encompasses the entire page, and submits the page to itself. Depending on the button that was clicked, a new row is added or the data is submitted to the PDF-creation page.
This is not ideal, for so many reasons. What I really want to be able to do is have two separate forms, or nested forms. But the former won't allow the input values to be submitted to both, and the latter is apparently bad form (no pun intended) and doesn't work.
Is it at all possible to make this do what I want it to do? Any suggestions for a different way to go about it?
I think you have the best non-javascript solution - certainly hte way I'd run with it.
One thing to make it easier is that you can use multiple inputs with the same name:
<input name="tablerow[]" type="text" value="A" />
<input name="tablerow[]" type="text" value="B" />
<input name="tablerow[]" type="text" value="C" />
And these come through the $_POST['tablerow'] as an array. The length of the array is the number of fields. Then add additional fields to that.
For accessibility, you should add a link at the top that allows the user to hop directly to the first "new" field - otherwise they need to tab through the entire form to get to the new field. (See my comment above about if JS is really unavoidable as you and they can avoid this scenario!)
I have a search function that currently grabs data from one table, and I'd like to grab data from an additional table, as well.
$query = $this->db->get('tbl_customer');
$this->db->select('in_customer_id, st_company_name, in_customer_type, st_customer_account, st_customer_state_id, flg_customer_account_type, in_status, dt_added_date, st_tag');
if(trim($action['searchtxt'])!='')
$this->db->like('st_company_name', html_entity_decode($action['searchtxt']));
The view:
<div class="floatl" style="width:250px;">
<form name="frm" action="<?php echo $index_url; ?>customers/search/" method="post">
<div class="floatl">
<input name="Search" type="text" class="textboxsearch" id="Search" onfocus="if(this.value==this.defaultValue)this.value='';" onblur="if(this.value=='')this.value=this.defaultValue;" value="<?php if($searchtxt!=''){ echo $searchtxt; } else{ echo 'Search'; }?>" maxlength="50" />
</div>
<div class="floatl searchicon">
<input type="image" src="<?=$admin_base_url?>images/textbox_search.gif" alt="" width="22" height="22" />
</div>
<br />
<br />
<font class="txt9">(i.e. Company, Account name)</font>
</form>
</div>
The table I want to additionally search is called tbl_admin_user. Any ideas on how I can accomplish this?
You might want to brush up on your SQL a little, especially take a look at SQL Joins.
With that said, after re-reading your question it appears that you are attempting to search particular columns for fairly specific data within multiple tables. First you might want to look into using LIKE instead of WHERE.
Second, depending on how you're displaying the results you you'll probably either write two separate queries and then loop through each of the separate results and display them. A Union or Join might be possible but also might be difficult to display the results accurately if the table structures are really different.
It seems that you are using an ORM/framework to access data, which one are you using.
Anyway, you are probably looking for join or union.
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;