updating wrong record in database after pressing button - php

I am busy making a new website, but I ran into a little problem today.
I will try to explain it as good as possible.
My website displays a random message every time you refresh the page, you can then click a button that says you like that message.
Now the problem is that when you click the button to like the message the page reloads (because of the form tag) and the like will go to the next message that is displayed.
I have no idea how to solve this so I hope you guys out there can help me with this.
I will post the code below here:
The bit that updates the database after you pressed the like button:
if(!empty($_POST["submit"]))
{
$id = $random['id'];
$query = "UPDATE `quotes` SET `likes` = likes + 1 WHERE `id` = $id";
$result = mysql_query($query);
if ((mysql_error()!=""))
{
$ANTW = mysql_error();
echo ("Cause of the error: " . $ANTW);
}
else
{
echo "It worked!";
}
}
The like button:
<form name='' method='post' action=''>
<input class='like' type='submit' name='submit' />
</form>
I hope that this if enough for you to solve the problem, if not let me know and I will post more code.
Dennis
UPDATE:
Hi guys, Thanks for all of the quick and good advice it worked the way you told me. Thanks

Save your id in a hidden input:
<form name='' method='post' action=''>
<input type="hidden" value="<?php echo $random[$id]; ?>" name="like" />
<input class='like' type='submit' name='submit' />
</form>
And in your PHP code assign:
$id = $_POST['like']; // your like id you passed by the form (input type hidden)

Send the id in submit form using a hidden field like
<input type="hidden" name="myid" value="YOURID">
and in the next page fetch the previous id using
$_POST['myid']

Related

PHP Autofill or something?

I have seen many questions related to auto fill, but none of them worked for me. I'm not even sure if a solution to my problem lies in HTML or PHP. I am new in both of them and I'm still not used to them. I'm working on a simple chat app. What I have now is chat window, text field, and nick name field. Both of them pass the values to the text file (which is how I want this to work, no change here). Problem is that both these fields work as a form, and each time I submit, nick name field refreshes. What I would want is auto completing nickname field so it stays the same (it'd be the best if it stayed even after browser refreshes, but it will be okay if it only goes through the form submit)
code if needed:
PHP:
<?php
$action = $_GET["action"];
$myText = $_POST["mytext"];
$nick = $_POST["nick"];
if($action = "save") {
$targetFolder = "/var/www/html/xami/";
file_put_contents($targetFolder."htmlinput.txt", $nick.">".$myText);
}?>
HTML:
<form action="?action=save" name="myform" method="post">
<label for="nick">Nick:</label>
<input type=text id="nick" name="nick" placeholder="Nick" value="Name" required><br>
<input type=text name="mytext" placeholder="Text" required>
<input type="submit" value="Send.">
</form>
I was fooling around with autocomplete but no positive results.
I'm leaving post for tomorrow, I'll reply then.
Assuming your HTML is on a .php page you could have...
if(0<strlen($nick)){
echo "<input type=hidden id='nick' name='nick' value='$nick'>";
}else{
echo "<input type=text id='nick' name='nick' placeholder='Nick' value='Name' required><br>";
}
Or, use AJAX as #Rishi says.

Browser go back button Confirm Form Resubmission

I have a search form on my page.
<form action='' method='post'>
<input type='text' name='search' />
<input type='sumit' name='submit' value='submit'/>
</form>
When the user clicks the submit button on the form, it should run a mysql_query and create a link to the user page.
if(isset($_POST['search'])){
$add = "city = {'$_POST['search']'}";
}
$res = mysql_query("SELECT * FROM user WHERE {$add}");
while($rw=mysql_fetch_object($res)){
echo "<a href=user.php?id={$rw->user_id}?>{$rw->name}</a>";
}
When I click on the link user.php?id=3, it goes to the user page and everything is OK. But I have problem when I click the browser's back-button, on user.php page. Then i have problem back to previous page.
Confirm Form Resubmission.
Correct the following:
<input type='sumit' name='submit' value='submit'/>
You are writing type='sumit' instead of type='submit'
To not display the "Confirm Form Resubmission" alert, do you have to change your submission (method) to GET.
<form action='' method='GET'>
<input type='text' name='search' />
<input type='sumit' name='submit' value='submit'/>
</form>
...
if(isset($_GET['search'])){
$res = mysql_query(sprintf("SELECT * FROM user WHERE city='%s'", mysql_real_escape_string($_GET['search']) ));
while($rw=mysql_fetch_object($res)){
echo "<a href=user.php?id={$rw->user_id}?>{$rw->name}</a>";
}
}
You should use get method instead of post. Post resubmissions must be confirmed by most browsers.
P.s.: you shouldn't pass the user input into your sql query directly to prevent the risk of sql injections.

how to trigger an href and php code with single onclick event of submit button

I've seen many forums, but couldn't figure this out. Please help and guide.
When I click the submit button, I am taken to a href file location ... no problem with this. Simultaneously I want to add details of the event to a table named 'docdownloads'. My code looks like this. Currently my table is getting updated without clicking the submit button. I want both the events to occur together and be triggered by the single click.
<?php
echo "<input type='submit' value='Click Here To Download' ". $downloaddisabled." onclick='window.location.href=\"$docpath\"'>";
echo '<br>';
if ($downloaddisabled!="disabled" ) {
$sql4="INSERT INTO docdownloads (accno, username, userid, downloadtime, filename) VALUES('$accno', '$uname', '$uid', '$downloadtime', '$docpath')";
if (!mysqli_query($con1, $sql4)) {
die('Error: ' . mysqli_error($con1));
}
echo "one record added";
}
?>
The Way I do things.
Create a seprate page for recording things in MySQL and when your things are done redirect it to downloadable item.
Original Page:
<?
echo "<input type='submit' value='Click Here To Download' ".
$downloaddisabled."
onclick='window.location.href=\"$docpath_special_Page\"'>";
echo '<br>';
?>
docpath_special_Page:
<?php
$sql4="INSERT INTO docdownloads (accno, username, userid, downloadtime,
filename) VALUES('$accno', '$uname', '$uid', '$downloadtime',
'$docpath')";
if (!mysqli_query($con1, $sql4)) {
die('Error: ' . mysqli_error($con1));
}
header("Location:/".$docpath);
exit(0);
?>
One solution is to have three pages
Page one: contains the submit button (with link to page 2). Also, make the $downloaddisabled a session variable so that it can be accessed on other pages
Page two: Checkes the session variable for being equal to disabled, if yes.. executes SQL.
This page also redirects to the third page automatically
Page three: Your final destination
I had similar issue am not sure how exactly is to mine but I had to submit form details to PayPal , save the same detail to database and send email of the details...
This is what you have to do:
Create form that will send details to database and you can put values hidden if you wish for normal user to see the details.
<form name="insert_to_table_docdownloads" method="post" id="msend" action="insert.php" target="_main">
<input type="hidden" name="accno" value="">
<input type="hidden" name="username" value="">
</form>
were insert.php contain sql insert command
Create another form which will view details you want to see
<form name="download" id="download" >
<input type="text" value="">
</form>
Then create JavaScript button to submit both form by id
<input type="image" src="button_img.png" onclick="document.getElementById ('msend').submit();document.getElementById('download').submit();" />
Tell me if it works for you.

PHP Mysql - Delete button keeps on deleting latest row

When i run into a glitch, I always find find the answer on StackOverflow, but this time, although I'm sure the fix is easy, I just can't seem to get it right !
Basically, i'm trying to add a "delete" button next to each row fetched from my mysql database. The users should be able to delete a specific post, if needed.
When i hit the delete button, it's always the latest row that gets deleted. So i guess there's something wrong with the value passed in each row : seems like they're overridden by the latest one.
Below's my code:
<?php
$table = query("SELECT post, postid FROM post_list WHERE id = ? ORDER BY
time DESC LIMIT 15", $_SESSION["id"]);
foreach ($table as $row)
{
$post = $row["post"];
$postid = $row["postid"];
echo ("<table>");
echo ("<tr>");
echo("<td>" . $post . "</td>");
echo("</td>")?>
<div id="posteraser">
<form action='' method='post'>
<input type='hidden' name='postid' value='<?php echo $postid?>'>
<input type='submit' name='posteraser'>Delete</input>
</form>
</div>
<?php
echo ("</td>");
echo ("</tr>");
echo ("</table>");
echo '<hr>';
}
?>
And below on the same page, there's the delete button code:
<?php
if(isset($_POST['posteraser']))
{
$sql = query("DELETE FROM post_list WHERE postid = '$postid' ");
redirect ('home.php');
}
?>
Any help/tips will be much appreciated !
Thanks a lot !
You have to pass here the $_POST['postid']
if(isset($_POST['posteraser'])){
$postid = $_POST['postid'];
$sql = query("DELETE FROM post_list WHERE postid = '$postid' ");
redirect ('home.php');
}
OR as procedure way
$sql = query("DELETE FROM post_list WHERE postid = ? ",$postid);
A developer should always be aware of the HTML code they create with their PHP code.
It's essential thing.
As a matter of fact, HTML code is the very result of our efforts. NOT nice picture on can see in the browser windows - it's browser's job - but the very HTML code.
So, if you bother to see into generated code, you would discover something that can be boiled down to
<input type='hidden' name='postid' value='1'>
<input type='hidden' name='postid' value='3'>
<input type='hidden' name='postid' value='4'>
<input type='hidden' name='postid' value='5'>
<input type='hidden' name='postid' value='9'>
Do you have any questions why you have only last value?
Speaking of solutions, you have two choices
create a separate form for the every row
mark the very Delete button with id.
<input type='submit' name='posteraser[<?php echo $postid?>]'>Delete</input>
for example
let's check the logic from select statement.
you are selecting postid and assigning it to a hidden element and when you press delete button
that hidden id is sent to server.
so form creating under for loop is
<div id="posteraser">
<form action='' method='post'>
<input type='hidden' name='postid' value='<?php echo $postid?>'>
<input type='submit' name='posteraser'>Delete</input>
</form>
</div>
but hidden element is creating with same name for each row.
so when you press delete button . first hidden id is sent to server.
and this hidden id is already newest as from your select statement.
so what's the solution for it..
either you should sent postid through get attaching it in your url so that you can identify
which delete button is pressed.
or create a logic to send only that id on which delete is pressed.
This looks wrong:
echo ("<tr>");
echo("<td>" . $post . "</td>");
echo("</td>")?>
The trailing </td> shouldn't be there. Something else perhaps?
Also, you don't show how postid gets into $_SESSION['id']

request in while loop

I work with this code:
<form method="get" name="MobileDetails">
<input name="brand" id="brand" value="<?php echo $brand;?>" type="hidden">
<input name="brid" id="brid" value="<?php echo $brandid;?>" type="hidden">
<button type="button" name="submitButton" value="get Details" onclick="getDetails()">
</form>
java script
<script type="text/javascript">
function getDetails(){
var brand = document.getElementById('brand').value;
var brandid = document.getElementById('brid').value;
document.MobileDetails.action = 'details.php?brand='+brand+'&id='+brandid;
document.MobileDetails.submit();
}
</script>
But it does not work in while loop. Whats the problem? My code is given below.
When i click on the button it do not do anything. But the code work great with out while loop given on the top.
<?php
require_once('connection.php');
$SQL= "SELECT*FROM mobile ORDER BY price ASC LIMIT 10";
$result= mysql_query($SQL);
while ($db_field = mysql_fetch_assoc($result)){
$brand=$db_field['brand'];
$id=$db_field['id'];
$model=$db_field['model'];
echo "<form method='get' name='MobileDetails'>";
echo " <input name='brand' id='brand' value='". $brand ."' type='hidden'>";
echo" <input name='brid' id='brid' value='". $id ."' type='hidden'>";
echo" <input name='mod' id='mod' value='". $model ."' type='hidden'>";
echo" <button type='button' name='submitButton' value='get Details' onclick='getDetails()'/>
</form> ";
echo "CLICK HERE";
}
?>
You're using several times the same id. Ids have to be unique.
Uou are dealing with multiple id's. The job of an ID is to be unique identifier for the element. I suggest just using
<form action="details.php" type="get">
this will do exactly what you are trying to achieve without using the function.
The thing with element ID's is that they need to be unique for the page; however, as you may see, not required for HTML to be displayed. When calling your JS function getDetails(), it grabs the element by ID but when you have multiple ID's in the page, this will fail.
So what can you do? Well, in your loop, you create a new form for each 'brand'. You can pass a reference of the form to the grabdetails and then, by NAME, grab the values from that form.
Rather than using Javascript to generate a link based on given details put in a hidden field, you should just generate the action at the PHP level.
echo "<form method='get' name='MobileDetails' action='details.php?brand=$brand&id=$brandid'>";
But since you do have hidden fields, using just action='details.php' the form will take the user to
details.php?brand={brand}&brid={id}&mod={model}
You should look into POST or making your button into a plain link rather than having a form.

Categories