how to update mySQL database using a post method in php - php

i have created a leaderboard for a website which displays users high scores for a game. but whe the user goes to edit their high score, it doesnt change in the database or on the screen. does anybody know how to update the database using a post method. my code is below.
require_once('../sokodatabase.php');
//require_once('../sokodatabase.php');
//require_once('../sokodatabase.php');
if(isset($_POST['userId'])){
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$query = "
UPDATE leaderboardhighscores
SET highScores=".$_POST["highScores"].", rankNo=".$_POST["rankNo"]."
WHERE userId=".$_POST["userId"];
var_dump($_POST);
echo $query;
#mysqli_query($dbc, $query);
}
}
$manager = new DatabaseManager;
$manager->SelectHighScores();
?>
<form method="post" action="highScores.php">
high score <input type="text" name="highScores"/>
rankNo <input type="text" name="rankNo"/>
userId <input type="text" name="userId"/>
<input type="submit" value="Submit">
</form>

You have to provide attention to SQL injections!
Normally, you check for the submit button:
<input type="submit" name="submit" value="Submit">
Then
if(isset($_POST['userId'])){
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
goes to:
if(isset($_POST['submit'])){
If your query does not work, you can make die($query) to see it and perform it via phpMyAdmin. Or you can use mysqli_error to display any occured error after executing it.
Please note, that with your code only numeric values are possible. If your fields are not numeric, you should use this:
$query = "
UPDATE leaderboardhighscores
SET highScores='".mysqli_real_escape_string($dbc, $_POST["highScores"])."', rankNo='".mysqli_real_escape_string($dbc, $_POST["rankNo"])."'
WHERE userId=".intval($_POST["userId"]);

Need name for the submit input type in-order to submit the form...
Like
<input type="submit" name="userId" value="Submit">
if(isset($_POST['userId']))

Related

Not able to insert data using html form and php using wamp [duplicate]

This question already has answers here:
Why shouldn't I use mysql_* functions in PHP?
(14 answers)
Closed 1 year ago.
I am trying to insert data into a database from HTML form using php. I made two files html form and other is PHP script. When I click on submit in html form, it shows me the php code. I am using wamp server for database. I put my html files in C:/wamp64/www directory and html files at my local directory. The database table is :
id int(11)
fname varchar(30)
salary int(11) . Id is not auto-incremented and it is a primary key.
Html code:
<html>
<body>
<h2>Employee's Information</h2>
<form action="employee.php" method="POST">
<label for="id">Enter employee id:</label><br>
<input type="text" id="id" name="id" value=""><br>
<label for="fname">Enter First name:</label><br>
<input type="text" id="fname" name="fname" value=""><br><br>
<label for="salary">Enter Employee Salary:</label><br>
<input type="text" id="salary" name="salary" value=""><br><br>
<input type="submit" id="submit" name="submit" value="Submit">
</form>
</body>
</html>
Php code:
<?php
$mysql_hostname="localhost";
$mysql_username="root";
$mysql_password="";
$mysql_database="employee";
$con=mysql_connect($mysql_hostname,$mysql_username,$mysql_password);
if(!$con){
die('Connection Error: '.mysql_error());
}
mysql_select_db($mysql_database, $con);
if(isset($_POST['submit']))
{
$s_id = $_POST['id'];
$s_name = $_POST['fname'];
$salary = $_POST['salary'];
$employeeinsert = "INSERT INTO employee1
(id, fname, salary)
VALUES('".$s_id."','".$s_name."','".$salary."')";
if(!mysql_query($employeeinsert,$con)) {
echo "Error: " .mysql_error($con);
} else {
echo "1 record added";
}
}
?>
The code is neither giving any error on submitting data nor it is inserting the data into the database.
I am not getting what the error is.
If this is false then the code successfully produces no output:
if(isset($_POST['submit']))
Which is what's happening, since the condition is false. The form has a submit button, but that button has no name attribute to its value isn't sent to the server:
<input type="submit" value="Submit">
Give it a name:
<input type="submit" name="submit" value="Submit">
It's always a good idea to have some kind of indication of any given code branch, even if just logging something somewhere so you can see what's happening. Code will happily produce no output/result if that's what it's instructed to do, but as you've discovered it can leave you with no information about what's happened.
As an aside, and this is important, your code is wide open to SQL injection. You'll want to start addressing that.

Is there a way to differentiate between a page refresh and pushing a submit button?

I have a form that, when submitted with a button, adds an item to a SQL database. However, the problem is that if I refresh the page after submitting, it will add another identical item to this database. Is there any way to tell when a user is pushing a button and when they are just refreshing the page? I am aware that I could check each entry to see if it is identical to one already submitted, but I have had similar problems come up already in other programs and I would be grateful if I didn't have to create a new workaround each time.
Code for reference:
<input type="text" name="var1" required>
<input type="text" name="var2" required>
<input type="text" name="var3" required>
<input type="submit" name="Submit" value="Submit">
</form>
<?php
if($_POST && isset($_POST['Submit'])) {
$conn = mysqli_connect("localhost", "root","");
mysqli_select_db ($conn,'database');
$var1 =$_POST['var1'];
$var2 = $_POST['var2'];
$var3 = $_POST['var3'];
$sql = "INSERT into database (var1,var2,var3) VALUES ('$var1','$var2','$var3')";
if ($result = mysqli_query($conn, $sql)) {
echo("Item Added Sucessfully");
}
}
?>
Trying to determine of a page is being refreshed or not is not the way to resolve this issue. What you need to do is prevent the browser from ever resubmitting that same form submission.
The Post/Redirect/Get pattern resolves this issue. Basically, after the form has been processed you want to redirect the user to the page you wish them to see by using a HTTP 303 redirect. This tells the browser to replace the form page in the browser history making it impossible to resubmit the form.
Here's what it may look like in your code:
<input type="text" name="var2" required>
<input type="text" name="var3" required>
<input type="submit" name="Submit" value="Submit">
</form>
<?php
if($_POST && isset($_POST['Submit'])) {
$conn = mysqli_connect("localhost", "root","");
mysqli_select_db ($conn,'database');
$var1 =$_POST['var1'];
$var2 = $_POST['var2'];
$var3 = $_POST['var3'];
$sql = "INSERT into database (var1,var2,var3) VALUES ('$var1','$var2','$var3')";
if ($result = mysqli_query($conn, $sql)) {
header('Location: thankyou.php', true, 303);
exit;
}
}
FYI, please read about SQL injection. Instead of building queries with string concatenation, use prepared statements with bound parameters. See this page and this post for some good examples.

getting data from a textarea into a database

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.";}
}
}
?>

Update data WHERE

I have a table called client and I am trying to update the contact number, but for only the id that is typed in. I have a form that creates two textfields for the data to be changed. My problem is im unsure on how i can only update data for only the id that is entered.
Code:
<form method="post" name="update" >
Client ID:
<br>
<input type="text" name="clientid"><br>
Contact Number:
<br>
<input type="text" name="contactno"><br>
<input type="submit" name="submit" value="Update"><br><br>
</form>
<?php
if(isset($_POST['submit'])){
$client = $_POST['clientid'];
$contact = $_POST['contactno'];
$result= $pdo->prepare ("UPDATE client SET client_contact_number='$contact' WHERE client_id='$client'");
$result->execute;
}
?>
your syntax should be:
mysqli_query($connection, $sql_query)
you're missing the $connection object in your method.
PHP docs: http://php.net/manual/en/mysqli.query.php
*Original version of this question used procedural syntax - hence my answer.

DELETE FROM table WHERE ID='$id' — Variable refuses to stick

Trying to perform a very simple task here.
I have an <ol> that contains 4 rows of data in some handy <li>s. I want to add a delete button to remove the row from the table. The script in delete.php appears to have finished, but the row is never removed when I go back and check dashboard.php and PHPMyAdmin for the listing.
Here's the code for the delete button (inside PHP):
Print "<form action=delete.php method=POST><input name=".$info['ID']." type=hidden><input type=submit name=submit value=Remove></form>";
Moving on to delete.php:
<?
//initilize PHP
if($_POST['submit']) //If submit is hit
{
//then connect as user
//change user and password to your mySQL name and password
mysql_connect("mysql.***.com","***","***") or die(mysql_error());
//select which database you want to edit
mysql_select_db("shpdb") or die(mysql_error());
//convert all the posts to variables:
$id = $_POST['ID'];
$result=mysql_query("DELETE FROM savannah WHERE ID='$id'") or die(mysql_error());
//confirm
echo "Patient removed. <a href=dashboard.php>Return to Dashboard</a>";
}
?>
Database is: shpdb
Table is: savannah
Ideas?
It's refusing to stick because you're calling it one thing and getting it with another. Change:
"<input name=".$info['ID']." type=hidden>"
to
"<input name=ID value=".$info['ID']." type=hidden>"
because in delete.php you're trying to access it with:
$id = $_POST['ID'];
You should really quote attribute values as well ie:
print <<<END
form action="delete.php" method="post">
<input type="hidden" name="ID" value="$info[ID]">
<input type="submit" name="submit" value="Remove">
</form>
END;
or even:
?>
form action="delete.php" method="post">
<input type="hidden" name="ID" value="<?php echo $info['ID'] ?>">
<input type="submit" name="submit" value="Remove">
</form>
<?
Please, for the love of the web, don't built an SQL query yourself. Use PDO.
Just another point I'd like to make. I'm 95% sure that you can't give an input a numeric name/id attribute. It has to be like "id_1" not "1".
Also with php you can do arrays.
So you could do this
<input name="delete[2]">
then in your php
if(isset($_POST['delete']))
foreach($_POST['delete'] as $key=>$val)
if($_POST['delete'][$key]) delete from table where id = $val

Categories