Pre Complete HTML Form with PHP and MYSQL - php

I am creating a simple page which updates a single record tempKey=1, single field reqdTemp MySQL dBase. I have the form working fine; it updates the record, then returns to the initial form ready for the user to change the temperature again.
Q: I would like the form to be pre-populated with the existing information from the database so the user sees the current required temperature about to be changed. I'm not sure where to start!!
The form, updateTemperature.php, is this:
<html>
<body>
<h1>RPi BBQ - Set Temperature</h1>
<form action="insert.php" method="post">
<p>Set Temperature: <input type="text" name="setTemp" /></p><br><br>
<input type="submit" value="Set Temperature" />
</form>
</body>
</html>
The post script, insert.php is this:
<?php
require_once 'login.php';
$con=mysqli_connect($hh,$un,$pw,$db);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
echo 'Connected successfully';
$sql = "UPDATE PiBQ_Temp SET reqdTemp = '$_POST[setTemp]' WHERE tempKey = 1";
mysqli_query($con,$sql);
echo "1 record added";
header ('location: PiBQ_Temp2.php');
mysql_close($con)
?>

To pre-populate the form, query the database for the current value and set that in the returned HTML. So your updateTemperature.php could become something like this:
<?php
require_once 'login.php';
$con=mysqli_connect($hh,$un,$pw,$db);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
echo 'Connected successfully';
$currentTemp = 100; // some default
$sql = "SELECT reqdTemp FROM PiBQ_Temp WHERE tempKey = 1";
$result = mysqli_query($con,$sql);
if(mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_assoc($result);
$currentTemp = $row['reqdTemp'];
}
mysql_close($con);
?>
<html>
<body>
<h1>RPi BBQ - Set Temperature</h1>
<form action="insert.php" method="post">
<p>Set Temperature: <input type="text" name="setTemp" value="<?= $currentTemp ?>" /></p><br><br>
<input type="submit" value="Set Temperature" />
</form>
</body>
</html>

Related

When adding a value from an input field to the database to an existing number, the number added is double

When the inputted number for $points is taken in the inputted field, it adds the number to the total already in the database, but for some reason the number added is double. For example if input 3, 6 will be added to the total. Can anyone help with an answer to this?
The idea is that someone should be able to add points to the total, and then on a separate page able to view it in a progress bar (which is working correctly) but the totals do not add up.
I am new to php so sorry in advance for any mistakes throughout the code.
Thank you
<?php
session_start();
if(!isset($_SESSION["sess_user"])){
header("location:login.php");
} else {
echo "Userid: ".$_SESSION["sess_id"];
?>
<!doctype html>
<html>
<head>
<h2><a id="button" href = "index.php">Main Menu</a></h2>
<h2><a id="button" href = "selftrack.php">Track your updated progress!</a></h2>
</head>
<body>
<?php
// Connect to the database
$username = "";
$password = "";
$host = "";
$db = $username;
$points = $_POST['self_p'];
// Connect to the MySQL server and select the required database
$connection = mysqli_connect($host, $username, $password, $db);
if (mysqli_connect_error()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else { // Database connected correctly
echo "<h1>Add daily points</h1>";
if (isset($_POST["addSubmit"])) {
if ((!empty($_POST["self_p"]))) {// Check all parts of the form have a value
$query="UPDATE targets
SET self_points = self_points + ".$points."
WHERE user_id='".$_SESSION['sess_id']."'";
$result = mysqli_query($connection, $query);
if ($result == false) {
// Show error message
echo "<p>The target points for " . $_POST["self_p"] . " was not added.</p>";
}
else {
echo "<p>The target points for \"" . $_POST["self_p"] . "\" has been added.</p>";
}
}
else {
echo "<p>Please fill out all the details</p>";
}
}
}
?>
<form role="form" id="addForm" name="addForm" action="?" method="post">
<div class="form-group">
<div class="col-xs-7">
<label for="addFormLast_Name">Please enter your daily points, up to 5:</label>
<input class="form-control" id="addFormLast_Name" name="self_p" type="text">
</div>
<div class="form-group">
<div class="col-xs-7">
<input class="form-control" id="addSubmit" name="addSubmit" value="Add Target" type="submit">
</div>
</div>
<?php
mysqli_close($connection);
}
?>
</body>
<?php
?>
</html>

database wont update after clicking submit button

After connecting to the database, here is the simplest code that should update my database after clicking the submit button :
<?php
if (isset($_POST['update'])){
$sql = "UPDATE accounts SET download='Yes' WHERE id=15 ";
}
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form method="post" >
<input type="submit" value="Update " name="update">
</form>
</body>
</html>
I dont know what am i doing wrong.
You first need to connect to a database.
$con = mysqli_connect("localhost","my_user","my_password","my_db");
Check connection if successful
if (mysqli_connect_errno()){
die( "Failed to connect to MySQL: " . mysqli_connect_error() );
}
If successful execute your query now.
$sql = "UPDATE accounts SET download='Yes' WHERE id=15 ";
$result = mysqli_query($con,$sql);
Check if query succeeded.
if( $result ) {
echo "Update successful!";
}
else {
echo "Updated Failed!";
}
Try to use error and exception handling codes, it will be helpful to fix the errors

When i check my database there are no new entries. What am i doing wrong?

<!DOCTYPE html>
<html>
<head>
<title>Sign up page</title>
</head>
<body>
<form method="post" action="signup_redirect.php">
username: <input type="text" name="username" placeholder="username"><br>
Password: <input type="password" name="password" placeholder="password"><br>
<input type="submit" value="Create Account">
</form>
// The user would enter the desired username and password.
<?php
if(isset($_POST['submit'])) {
$dbCon = mysqli_connect("localhost", "root", "", "test");
if (mysqli_connect_errno()) {
echo "Failed to connect" .mysqli_connect_error();
}
$sql = "INSERT INTO test (username, password)
VALUES ('".$_POST['username']."','".$_POST['password']."')";
}//Takes the values that the user has submitted and inserts them into my table called "test".
?>
</body>
</html>
I have a form which would take the users desired details then if the submit button is pressed it runs through the rest of the php code.I also have the sql statement which is meant to add data but when i check my database there are no new entries.
$sql = "INSERT INTO test (username, password)
VALUES ('".$_POST['username']."','".$_POST['password']."')";
After that run query
$sql_qry=mysqli_query($dbCon, $sql);
add
if (mysqli_query($dbCon, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($dbCon);
}
after, $sql query you have written

Save input into database

Hello guys i need some help.I connected to database from server and can insert some info like $sql = "INSERT INTO Posts (Text_Post) VALUES ('Sample Text')";. Now I want to save on click text from <input type="text" /> to database. Can you tell me what i am doing wrong.
<?php
$servername = "google.com";
$username = "google";
$password = "google";
$dbname = "google";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['Submit'])) {
$sql = "INSERT INTO Posts (Text_Post) VALUES ('".$_POST['text']."')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>anonim</title>
</head>
<body>
<form name="form" action="" method="post">
<input type="text" name="text" id="text" value="Salut" /=>
<input type="submit" id="Submit" />
</form>
</body>
</html>
You're missing the name tag on your submit. When data is POST'ed to the server, it uses the name tag.
<input type="submit" id="submit" name="Submit">
Remember to watch your Capitals also - (since you're checking if Submit is SET then you need to POST the submit).
You could just do:
if(isset($_POST['text'])) {
Also, going off the comments: I'd suggest taking a look at this link because you're prone to SQL Injections.
when we are going to post a form using POST or GET. we should always give name to all our fieds so we get get them just using $_POST['name'] or $_GET['name']. In Your case just give a name to your submit tag and check whether data is submitted or not.
replace
<input type="submit" id="Submit" />
with
<input type="submit" id="submit" name="submit">
and check it like
if(isset($_POST['submit'])) {// it will only check where form is posted or not
// your code...
}

Update database data with submit button

I want to update a database so that when you put your text in a text box and click the submit button, the data will be sent to the database with a specific id. It is clear what I want to do in the code below. When I write something like this and run it, I receive a 403 error: Access forbidden. How can I fix this?
<?php
function updater($value,$id){
// Create a connection
$conn = new mysqli( 'localhost' , 'user_name' , '' , 'data_base_name' );
// Check the connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE table_name SET name=$value WHERE id=$id";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
//$conn->close();
}
?>
<!DOCTYPE html>
<html>
<header>
</header>
<body>
<form action="<?php updater($_POST['name'],1); ?>" method="post" style="height:50px;width:50px;">
<input type="text" name="name" /><br><br>
<input type="submit" /><br/>
</form>
</body>
</html>
You need to put the URL inside the action attribute that does the form processing, not the function:
action="<?php updater($_POST['name'],1); ?>" // not this
action="" // empty for the same page
Also, usually the edited value fills the input and the record's id is added to the form in a hidden field. If processing is on the same page, best to leave the action empty. So a basic form could be like this:
<form action="" method="post">
<input type="text" name="name" value="<?=htmlspecialchars($row['name']) ?>"/><br>
<input type="hidden" name="id" value="<?=htmlspecialchars($row['id']) ?>"/>
<input type="submit" /><br/>
</form>
Above the form, the processing has to be added
if($_SERVER['REQUEST_METHOD'] === 'POST') {
$conn = new mysqli( 'localhost' , 'user_name' , '' , 'data_base_name' );
updater($conn, $_POST['name'], $_POST['id']);
}
Besides, you must use safer prepared queries:
function updater($mysqli, $value, $id) {
$sql = "UPDATE table_name SET name = ? WHERE id= ?";
$update = $mysqli->prepare($sql);
$update->bind_param('si', $value, $id);
$update->execute();
return $update->affected_rows;
}
like this:
<?php
function updater($value,$id){
// Create connection
$conn = new mysqli( 'localhost' , 'user_name' , 'pass' ,'data_base_name' );
$value =mysqli_real_escape_string($conn,$value);
$id =mysqli_real_escape_string($conn,$id);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE table_name SET name='{$value}' WHERE id='{$id}'";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
}
if(isset($_POST['name'])){
updater($_POST['name'],$_POST['id'])
}
?>
<!DOCTYPE html>
<html>
<header>
</header>
<body>
<form action="" method="post" style="height:50px;width:50px;">
<input type="hidden" name="id" value="1" />
<input type="text" name="name" /><br><br>
<input type="submit" /><br/>
</form>
</body>
</html>

Categories