Using PHP to insert form values - php

So I have a website on which users can share content. I would like to add a like button to user posts. What would be the smartest/cleanest way to do it?
Right now, I know I could use a submit button with two hidden form fields with values containing the post id and the user id of the poster. Then I would just use my $_SESSION['id'] to insert that into a new row in the LIKES table. Now, that's not very effective. I mean it work and all, but I want to do it so that It is instantly updated both on the page and in the database. What is the logical process to it? Could someone lead me in the right direction as to what I need to learn? Is it javascript? Ajax?

By users I assume you mean registered users with an active session.
To be honest, I know that the best way to do this is ajax as #DarkXphenomenon sugested, but I don't know how so I will put my approach in plain php.
<?php
if (is_int($_POST['postnumber'])) {
mysqli_query($connected,"INSERT INTO likes (userid, postid)
VALUES ('".mysqli_real_escape_string($connected,$_SESSION['userid'])."',".$_POST['postnumber'].")");
echo "Liked";
} else {
?>
<form>
<input type="hidden" name="postnumber" value="3456">
<input type="submit" value="Like">
</form>
<?php
}
?>
NOTE: $connected should be a link as seen in mysqli_real_escape_string() and mysqli_query()
PS, I don't know what else you want to achieve. This code will show 'like' instead of the submit button when you click on it for a single post (only the first time you submit it). Work with it, you can try to think how to adapt the code for several posts, how to count the total number of likes for each post, if you want to display when mouseover which users liked it, add the ability to remove the like, anything you want. That's up to you.

Related

How do i make a form with an image and text

I want to make a form where the user uploads an image, the title with a textbox and a description with a textarea, when the user clicks on the submit boton i want this post to get posted in another page, and if another users makes another post send him to the same page and put his post on top of the older one and so on.
I already a form for the file upload that uploads it to a folder and the form for the text that displays the input in a php page.
I don't know how to continue or if i'm doing it wrong.
How do i make the posts go on top of each other?
How do i put this image they just uploaded next to their post, i don't think uploading it to a folder is the right way to do it.
Can someone point in the right direction because i'm not a programmer and i cant seem to find a guide on how to do this.
I will try to anwser your question, however you seem to have provided too little information (no code!!)
There are different ways to work with images, if you say you did it with a folder I am guessing you used a Javascript or PHP of somesort.
If you used PHP then its no problem. You just place the image AND the text in one variable and echo this variable out. For easy structuring i would use a blind table, although that is NOT the most potimal way and definetly not barrier free, it gets the job done. PHP is very flexible and you can place almost anything into a variable and have it echo out. It would look something like this:
$output = "
<table>
<tr> <td> *image link here* </td> <td> *text link here* </td> </tr>
</table>
";
echo $output;
Like i said, without any code its a little hard to tell you exactly what you are looking for, but this is a start i hope =)
Well, the other anwser kinda anwsered it, you would have to save all the data coming in, in a database, preferably mysql since the mysql functions are built into PHP. (i believe however that you are saving the info somewhere since you mentioned a folder with the images)
Your form would look something like this :
<form method=post action=display.php>
<textarea name=comment>
<input type=submit>
</form>
Now when someone clicks the button, they are taken to the "display.php" page (or whatever you want to PROCESS the data) Now, included in that page is a statement like:
$sql_update = "INSERT INTO post (comment) VALUES ('$_POST['comment']'";
This statement would insert the information provided in the previous textarea (with the name "comment" into a table named "post" (this table has to be premade though) in the column named "comment"
Then you save the information into a variable by doing:
$sql = "SELECT * FROM post";
$res = mysql_query($res);
This just selects EVERYTHING ( * ) from the table "post" and querys it (mysql_query) meaning it is ready for work
Then we stick the whole thing in a while loop like so:
while($row=mysql_fetch_assoc($res))
{
$output = "
<table>
<tr> <td> *image link here* </td> <td> $row['comment'] </td> </tr>
</table>
";
echo $output;
}
This loop will constantly echo every row as long as there is something to echo. $row['comment'] is the link meaning we are grabbing whatever is in the column "comment" in our row and echoing it. (which also would stack one onto the other since it takes on information set, echos it, then takes another information set, echos it ....)
Now you would do the same for your image, or something similar at least. It gets a little more complicated when we add users and "post-times" to the equation. I dont know exactly how much knowledge you have of PHP/MYSQL but if you wish to process anything with a form, you will need some. I hope my small tutorial did not bore you and i hope it helped you a little bit more =)
Happy coding =)
posting your data to a html page passes the (post-)variables from form fields to this page, but it doesn't save the data.
without saving the data you are only able to display the text from the form on the next page for the same user. and whenever s/he leaves the page, it's gone.
i guess that's not what you wanna do, so
you need to save the data in some way, most commonly using a MySQL database.

Way to re-populate checkboxes on page?

I have a bit of an odd/unique situation, where I am currently looking for a way to 're-populate' checkboxes on my page.
First some background on how the page/app works.
1.) state1: You get simple search form. Enter in first or last or state, etc., hit submit.
It queries a DB and posts back to the SAME Page (?mode=results).
Inside of a MAIN container DIV, I loop through the returned records, and create (echo) a TABLE with a certain tabular layout to parse the values from each record/row (name, date, ID#, etc).
If I have 5 records returned from DB, I loop through and create 5 tables right after each other, populating each with the unique data from the record/row.
In each one of these tables I create, along with the data from the DB record/row. I also create/add in several check boxes.
Using some jQuery and on $(document).ready, I listend for the onClick event for all these checkboxes. So when clicked, I grab some data from the checkbox, as well as some parent info, and do the following:
a.) I create/add another element to the stage
b.) Make an Ajax call to an external .php script, so that I can update the SESSION with my array I have build (collecting all the user checks/input)
I build the array in JS/jQuery and use the Ajax call to get this data into my PHP session (anyone knows a way to NOT use this external .php script to update the SESSION var, let me know please!)
So to re-cap so far: There is no "FORM" (tags), just check boxes in multiple tables. There really is no 1-button (submit) event that POSTS all the checkbox data anywhere at one time. Each time a checkbox is clicked (or un-clicked), I update my SESSION array. That if/when a user IS ready to 'check out' (for lack of better term) (leave the page and go to another page), the SESSION data/array is 'current' and the data is ready to be used on any following pages.
so far everything posted above works just fine.
The question I have is: If the user wants to go BACK to this MAIN PAGE with all the checkboxes, what nice, simple/elegant solutions do I have to re-populate all these checkboxes?
I'm thinking the only approach I have is the check and see if this SESSION array exists when main page loads (meaning it's a re-visit, not the first time), and try to loop through this array and somehow target elements on my stage to find the correct table, then the checkbox ID?
Usually use jQuery to walk the DOM - not PHP?
And what about toggling the checkbox with PHP?
Is there a nice way to do this?
I don't really see your problem. I recapitulate:
You have a page with several <table> coming from your database (1 row = 1 <table>)
In these tables you have checkboxes
When you click on a checkbox, you do an ajax call to save the clicked checkbox in session
Your question is: how can I repopulate checkboxes when the use come again on the page
I think you already have the answer: just use what you stored in your session. When you build your <table>, and your checkboxes, test if they are in session:
<input type="checkbox" <?php if (!empty($_SESSION['blabla'][$myCurrentCheckboxID])) echo 'checked'; ?> />
If you want something more elegant, just create a nice PHP class or list of functions to generate your checkbox.
thanks for the suggestions.. this is what worked for me in the end (so far)
function sessionCheck($recordID, $checkBoxID){
for($r = 0; $r< count($_SESSION['userPicks']); $r++){
if($_SESSION['userPicks'][$r]['recordid'] == $recordID){
for($z=0; $z < count($_SESSION['userPicks'][$r]['itemsordered']); $z++){
if($_SESSION['userPicks'][$r]['itemsordered'][$z]['name'] == $checkBoxID){
return 'checked="checked"';
}else{
return "";
}
}
}else{
return "";
}
}
}
usage for MY project is like this:
<?=sessionCheck($row["id"] ."-A","Testimonial History") ?>

PHP Cycle Through MySQL Table With Submit Button

Okay, I've looked for a solution to this question, but to no avail. It could be the way I worded it, but I've tried almost everything I could think of. And I know this is probably something so simple, I just can't wrap my head around it.
The problem I'm having is this:
I have a form that is prepopulated with data from a MySQL database. This part of the form is strictly for viewing the records (that were previously entered by the user). I can get it to work; I have the database linked, and it shows the data for the row of the particular table that I want. But this is what I'm having trouble with.
I want there to be a button that the user can press that cycles through each row of data in the database, and outputs it in the form accordingly.
It's a little complicated, so I'll use a simple example.
Let's say I have a basic table in a MySQL database with three columns: ID, Name,
and EmailAddress.
Here's the query that grabs the data:
$sql = "SELECT * from tbl_Users ORDER BY ID ASC";
$query = mysql_query($sql);
$result = mysql_fetch_array($query);
Now I know this is deprecated, but I am working in an older version of php, and I'm trying to stay consistent other pages/apps in this particular domain.
Now let's say I have a simple form with two inputs and a submit button.
HTML
<form name="button" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" name="Name" value="<?php echo $row[Name]; ?>" />
<input type="text" name="emailAddress" value="<?php echo $row[EmailAddress]; ?>" />
<input type="submit" name="submit" value="Next Record" />
</form>
Now I can get it to echo what I need in the form. It can prepopulate the form with a row, as I want it to. The trouble lies with the submit button.
When the submit button is clicked, I want the next row to populate in the form, and so on until the end of the records.
I've tried the if(isset($_POST['submit']{...}, yet I don't know exactly to get this to work. I've tried loops, etc. I know there is a way, I just cannot comprehend one right now. Thanks in advanced.
Okay, so I DID manage to get it to work with PHP. I found a simple PHP Pagination script and changed the limit of the query to 1. Instead of echoing out the results of the query in the WHILE loop, I just called the variables for the form
Unfortunately in your case, PHP is server side, and it will run any queries before the client side has a chance to catch up and output it. I believe you will need to use javascript for this.
You can do one of two things, 1. Pull all table information on load (slower way) and use javascript to show/hide certain elements of that query. Or 2. You can use AJAX to pull the data on command.
I would suggest learning javascript (e.g. use a framework like jQuery) to perform an AJAX call for this.

Change some user settings, but not all from a single form (PHP, MySQL)

I am creating a site in PHP while storing my date in a MySQL database. I have already created my sign-up, login, logout portions, but I would like to make things more user friendly and add an area where people can change their user settings. Some of the settings that I would like for the user to be able to modify are as follows:
full name
email
age
gender
etc.
That being said, I would like for them to be able to fill out only the portions of a form that they would like to update. They should be able to leave everything else unchanged and submit all of their changes with a single submit button.
Any suggestions as to the best way to approach this problem are greatly appreciated.
As a side, I would eventually like for this site to contain AJAX (where the user might be able to select individual settings and change them at will), so if your solutions take that into consideration, that would be great.
EDIT:
Sorry, but I should have mentioned that I want to keep the information from being shown to the user (i.e. displayed in the text field) unless they explicitly type in there. As far as I can tell, this would keep me from always posting all of the data every time.
I have a great way of achieving this. Just simply do some if/else coding in php. Like this--
Html Code:
<form action="settings.php" method="POST">
<input type="text" name="full name" />
<input type="text" name="email" />
........ (and more)
</form>
And PHP code ---
<?php
if($_POST)
{
if(isset($_POST['full name'])) { //Update full name of user and redirect to the settings page on success. }
else { //Redirect and show errors! }
if(isset($_POST['email'])) { //Update email of user and redirect to the settings page on success. }
else { //Redirect and show errors! }
}
?>
Or you can use array function of PHP to set the MySql queries in it like ---
<?php
mysql_query("
UPDATE table name SET
//Loading different values from the array using foreach() php function.
");
?>
Just try to do some modifications in it.
Hope this helps you.
Your choices are:
1) multi-stage edit process. 1. pick fields to change. 2. present fields for editing. 3. save updated data. Rather tedious
2) present all the fields in a form, but use some Javascript to keep track of which ones were changed and submit only those
3). present all the fields in a form, and update all the fields in the database. if one or more weren't changed, the update is a null-operation anyways.
3)'s easiest to implement. 2)'s dependent on javascript. 1)'s tedious for you and even more tedious for the user.
As long as you do proper validation on all the fields, I don't see how #3 is anything but the most logical choice.
Create a edit.php or something else. Create textfields which one you want to edit.
All information could be showed thats related with the unique id of a user.
input type='text' value='"Example: Select * from users WHERE id = '$userid'"' name'Example: Update_name'
Do this for all the field you want to edit. After creating this edit.php. Use a script to update the $_POST or $_GET user details. Based on this easy to use script you've got a edit function for a user.

fetching data from database in randomly generated button

i found it difficult,,,, fetching data from database while a buttons are randomly generated in for each how can i fetch
Without understanding what your question really is, you could go trough the mysql query result like this:
// button_text is a database column in this example
while ($row = mysql_fetch_row($result)){
echo "<button type="button">".$row['button_text']."</button>";
}
But to really help you, you need to rephrase your question!
I'll make some assumptions for what you are trying to do:
1. You have buttons that fetch more info from a db
2. The buttons are "randomly" generated, and each calls different info (pets, cars, etc).
You may or may not be using ajax, but I will describe it basically assuming straight php, and you are using a single page (for clarity in my explanation).
What you need to do is have each button either be a link or a submit for a form. This just depends on whether you want to use GET or POST. The buttons will have php generated links (if GET) or values (if POST). For example, using get the link could be "www.file.php?cat=cars". The button would just have the value of "Cars", and since bother are generated, that shouldn't be an issue keeping them the same.
When the page is now reloaded based on the click, the top of the page has a query in it to get the new info. For example, it would run a query looking for all items that have the car category. Then the new information would be displayed, and the new random buttons would show.
VERY IMPORTANT: Sanitize all GET and POST values before using them in a query

Categories