How to write a javascript button which contains data? - php

How do you create a javascript button to take the information from the form to the php sql:
<form>
<input type="text" placeholder="Name" name="name" class="name" /></br>
<input type="text" placeholder="Phone Number" name="number" class="number"/></br>
<input type="text" placeholder="Location " name="location" class="location"/></br>
<input type="submit" value="Add Booking" />
</form>
?php
$name = $_GET['name'];
$number = $_GET['number'];
$location = $_GET['location'];
$con = mysql_connect(".....",".....",".....");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
("chanh", $con);
$sql ="INSERT INTO book (name, number, location,timestamp)
VALUES ('$name', '$number','$location',NOW())";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added"
mysql_close($con);
?>
Any help would be appreciated as I am just a rookie! Thanks

You just need to specify where you form will be submitted
<form action="submit.php" method="get">
<input type="text" placeholder="Name" name="name" class="name" /></br>
<input type="text" placeholder="Phone Number" name="number" class="number"/></br>
<input type="text" placeholder="Location " name="location" class="location"/></br>
<input type="submit" value="Add Booking" />
</form>
Javascript is only needed here if you want to perform some sort of validation
NOTE
Avoid adding variables directly to your query, you will be vulnerable to SQL injection.
Here is what you can do:
$con = mysql_connect(".....",".....",".....");
$name = mysql_real_escape_string($_GET['name']);
$number = mysql_real_escape_string($_GET['number']);
$location = mysql_real_escape_string($_GET['location']);

create an , then set that when the button is clicked, the form is submitted. ie
but = document.getElementById('clickButton');
formToSubmit = document.getElementById('myForm');
but.onclick = function(){
formToSubmit.submit();
};

You don't need JavaScript to submit a form. It looks like you're just missing the < from <?php for now.
You could explicitly specify the action and method on the form HTML element, but if you don't it's a GET request and it will submit to the current URL (Web address).
Really, if you're doing something other than fetching data (like a search), your form should be using a HTTP POST, not a GET. For more understanding of why this kind of thing matters, see What should every programmer know about web development. However, that is a very big topic!

You just need to postback the form, in other words, set an action on the form as in:
<form id="mainForm" action="process.php" method="post">..
And add an onclick handler on the button as follows:
<input type="submit" value="Add Booking" onclick="javascript:document.getElementById('mainForm').submit();" />
However, not that I set the method to post; this will require your PHP code to change to:
$name = $_POST['name'];
$number = $_POST['number'];
$location = $_POST['location'];
Using POST in this case may not be necessary but you need to be aware that using GET will encode the form parameters in the URL as in process.php?name=value&numner=value... and some of this information may be sensitive and therefore, desirable to be submitted to the server in the body of the HTTP request as opposed to transmitted encoded in the URL.

Related

Problem: Part of the PHP exercise does not run correctly

I created a section for editing. When I edit the information and click the save button, the information is not saved and the header section does not display completely.
<?php
if (isset($_POST['submit_btn']))
{
$id = $_POST['id'];
$fn = trim($_POST['name']);
$ln = trim($_POST['lastname']);
$age = trim($_POST['age']);
$q = "UPDATE `users` SET `fn` = '$fn',
`ln` = '$ln',
`age` = '$age'
WHERE id = '$id'";
mysqli_query($dbconnect,$q);
if (mysqli_affected_rows($dbconnect) > 0)
redirect("?msg=ok&id=**$id**");
else
redirect("?msg=error&id=**$id**");
}
else
echo ("Not In If(isset)");
?>
<form action="" method="post">
<label for="name">FirstName:</label>
<input type="text" name="name" id="name" value="<?php echo $row['fn']?>">
<br>
<label for="lastname">LastName:</label>
<input type="text" name="lastname" id="lastname" value="<?php echo $row['ln']?>">
<br>
<label for="age">Age:</label>
<input type="text" name="age" id="age" value="<?php echo $row['age']?>">
<br>
<input type="submit" name="submit_btn" value="Save">
<a href="index2.php">
Back
</a>
</form>
</body>
Bold sections do not work here.
Below is a picture of the result:
In the link that I specified, after clicking on save the ID will not be displayed and all the information filled in the forms will be lost.
Sorry if the result is styleless and boring and I just created this page to practice php😁
Thank you for being responsive🙏🙏🙏
You are mistaking a POST request with a GET request.
Part, which appears in the URL is sent to the webserver in GET request.
Your form is submitting POST request to the webserver, logic in the code does the same, but you are trying to display information from url (GET).
Please check the examples in php.net:
POST variables: https://www.php.net/manual/en/reserved.variables.post.php
GET variables: https://www.php.net/manual/en/reserved.variables.get.php
You can take an example with GET request variable below, however, be careful with trusting the "end client" and always prepare your statements, which you send to your database to execute queries.
if (isset($_GET['submit']))
{
$number = $_GET['number'];
echo $number
? "Number which was submitted: $number <br>"
: 'Number is not set';
} else {
echo 'Form has not been yet submitted';
}
?>
<form action="" method="get">
<input type="number" name="number" placeholder="Number">
<input type="submit" name="submit" value="Save">
</form>

How do I update a table in the database securely using an input from a html form?

I have a html table where I need to take the users input safely and securely to update a table item. Any guidance? (I know what I've wrote below is incorrect)
For example if they wanted to update their own details for example surname:
<div class="grid-2">
<p><b>UPDATE MY DETAILS</b></p>
<form action ="includes/update.inc.php" method ="post">
<label>S.Name</label>
<input name="update-surname" type="text" placeholder="Enter new surname...">
<label>Address</label>
<input name="update-houseno" type="text" placeholder="Enter house no' or name...">
<input name="update-ln1" type="text" placeholder="1st Line of Address...">
<input name="update-town" type="text" placeholder="Town...">
<input name="update-county" type="text" placeholder="County...">
<input name="update-postcode" type="text" placeholder="Postcode...">
<label>Contact Number</label>
<input name="update-number" type="text" placeholder="Contact Number...">
<label>Email</label>
<input name="update-email" type="text" placeholder="Email...">
<input type="submit" name="update-details" value="Update">
</form>
</div>
Update name snapshot.....
UPDATE I have added code to the above page and an action on the form as requested. The code below is the start of what I've made to the page the action leads to:
<?php
// Here we check whether the user got to this page by clicking the proper button.
if (isset($_POST['update-details'])) {
require 'dbh.inc.php';
// We grab all the data which we passed from the update form so we can use it later.
$surname = $_POST['update-surname'];
$houseno = $_POST['update-houseno'];
$ln1 = $_POST['update-ln1'];
$town = $_POST['update-town'];
$county = $_POST['update-county'];
$postcode = $_POST['update-postcode'];
$number = $_POST['update-number'];
$email = $_POST['update-email'];
// We validate email is correct if email has been updated.
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: ../after-login.php?error=invalidmail&uid=");
exit();
}
}
?>
So you need an action on your form - i.e a script to point it to to process the form (can be the same script). You also ideally want to set the method to post so that data isn't visible in the url then you need to clean your data, connect to the db and do your query.
This should help you get the right idea
Form in PDO to update data

Calling php file from form

I have an HTML form that I need to call a php script upon pressing submit but can't work out why the script isn't being executed.
<form action="update.php" method="POST">
<input name="id" type="hidden" value="id"/>
<input name="subArea" type="text" placeholder="Sub Area (optional)"/>
<label><textarea name="description" rows="2" cols="80" placeholder="Description" ></textarea></label>
<label><input type="radio" name="markNA[]" value ="markNA"/> N/A? </label>
<input class = "btn-testname" type="submit" value="Change" name="update"/>
</form >
I don't need the page to reload when pressing the button (so want to avoid Ajax) It was my understanding that the method above will execute the script?
update.php
<?php
include ("databaseLogin.php");
// Create connection to Database
$con = mysqli_connect('localhost',$dbuser,$dbpass,$dbname);
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
// Sql Query
$sql = "INSERT INTO `table_tests` (`active`, `description`)
VALUES (1, 'newstuff')";
mysqli_query($con, $sql);
?>
EDIT 1: I excluded the bringing in of the POST vars just to simplify the php code (and hard coded them into the sql query)
If I'm just missing a stupid syntax error I apologise.
**Try this**
<form action="update.php" method="POST">
<input name="id" type="hidden" value="id"/>
<input name="subArea" type="text" placeholder="Sub Area (optional)"/>
<label><textarea name="description" rows="2" cols="80" placeholder="Description" ></textarea></label>
<label><input type="radio" name="markNA" value ="markNA"/> N/A? </label>
<input class = "btn-testname" type="submit" value="Change" name="update"/>
</form >
<?php
include ("databaseLogin.php");
// Create connection to Database
$con = mysqli_connect('localhost',$dbuser,$dbpass,$dbname);
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
$description = $_POST['description'];
$active= $_POST['markNA'];
$id= $_POST['id'];
// Sql Query
$sql = "INSERT INTO `table_tests` (`active`, `description`,`id`)
VALUES ('$active', '$description','$id')";
mysqli_query($con, $sql);
?>
You have to reload the page or atleast go to another page, PHP is a server sided language so it cant make realtime changes. if you want to do that you have to use javascript.
but the way you are using now you can get the variables from this page in update.php:
$description = $_POST["description"];
If you have that code on update.php the text filled in the description textbox will be saved as the variable $description so you can validate forms for example
======================
EDIT
To get the values of for example the textbox 'description' you can use:
document.getElementById("searchTxt").value;
So if you want to get it on a button click you do :
<script type="text/javascript">
function check () {
document.getElementById("description").value;
}
</script>
<button onclick="check()"></button>
Here you get the value of the field where ID="description"
There are ways you can get it by name but I always rather use ID
document.getElementsByName('description')[0].value
the code above gives you the first element with the name description

Updating user table in database

I've created a members area where a user can update their bio. The problem is that the information the user submits isn't updating the rows in the database.
Member's Area
<body bgcolor="#E6E6FA">
<button>Log Out</button><br><br>
<input type="text" name="age"placeholder="Enter a your age."><br>
<input type="text" name="bio"placeholder="Enter your bio.">
<input type="submit" name="submit" value="Submit your details!">
PHP
<?php
if(isset($_POST['submit'])){
$con=mysql_connect("localhost","root","****","****");
// Check connection
if (mysql_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$age = mysql_real_escape_string($_POST['age']);
$bio = mysql_real_escape_string($_POST['bio']);
$name = mysql_real_escape_string($_SESSION['username']);
mysql_query($con,"UPDATE accs SET age='.$age.' WHERE name='.$name.'");
mysql_query($con,"UPDATE accs SET bio='.$bio.' WHERE name='.$name.'");
mysql_close($con);
};
?>
</body></html>
Any Ideas as to what is wrong here?
in your HTML page, the form should be inside the <form></form> tags
<form method="post" action="update.php">
<input type="text" name="age" placeholder="Enter a your age.">
<br>
<input type="text" name="bio" placeholder="Enter your bio.">
<input type="submit" name="submit" value="Submit your details!">
</form>
In your PHP page - to check the results, you can temporarily echo $age; echo $bio;
As you are using $_SESSION['username']; I think you are missing session_start(); to the top of your PHP code.
Also mysql_query only needs the SQL command, and not the connection ($con), that is mysqli, which is strongly advised to use instead of mysql_*.
As a side note, don't rely on user names in your database as the update criteria. If not already introduced, you can add an ID column to your table
a) create a proper submit form. use form tags around your form fields.
b) check, that the form is correctly submitted, by checking the $_POST array.
var_dump($_POST);
c) check, that you have values for the fields that you want to insert.
do a var_dump() before mysql_query(), to see what's going on.
var_dump($age, $bio, $name);
d) combine your two query calls into one:
mysql_query($con, "UPDATE accs SET age='.$age.', bio='.$bio.' WHERE name='.$name.'");
If you want to use the page it self to process your request, then empty the action property of your form. For example :
<form method="post" action="">
<input type="text" name="age"placeholder="Enter a your age."><br>
<input type="text" name="bio"placeholder="Enter your bio.">
<input type="submit" name="submit" value="Submit your details!">
</form>

unable to post data from php form into mysql

No matter how many sites I go to to try and get this to work, it still doesn't. I am unable to have the data that has been entered end up in the database. The form submits, but doesn't come back with an error. When looking in phpMyAdmin, there are no records. I've tweaked it a million times with no luck. Can a second set of eyes show me what I'm doing wrong?
Thanks!!
Tim
<body>
<form action="insert.php" method="post"><br>
Date: <input type="text" name="date" id="date"><br>
Time: <input type="text" name="time" id="time"><br>
City: <input type="text" name="city" id="city"><br>
Fire Dept: <input type="text" name="fire" id="fire"><br>
Address: input type="text" name="addy" id="addy"><br>
Call Type/Level <input type="text" name="level" id="level"><br>
Description: <input type="text" name="desc" id="desc"><br>
Units: <input type="text" name="units" id="units"><br>
Submitted by: <input type="text" name"who" id="who"><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
<?php
if (isset($_POST['submit'])){
$db=mysql_connect("", "", "");
$mydb=mysql_select_db("rm911_incidents");
$date=$_Post['date'];
$time=$_Post['time'];
$city=$_Post['city'];
$fire=$_Post['fire'];
$addy=$_Post['addy'];
$level=$_Post['level'];
$desc=$_Post['desc'];
$units=$_Post['units'];
$who=$_Post['who'];
$sql = "INSERT INTO incidents(date,time,city,fire,addy,level,desc,units,who)
VALUES
('$date','$time','$city','$fire','$addy','$level','$desc','$units','$who')";
$result = mysql_query($sql);
if($result)
{
echo "<br>Input data is successful";
}
else
{
echo ("<br>Input data has failed");
}
}
?>
Okay, so I have fixed the error that Leo mentioned (Thank you!), however that was not the problem either. The errors that I am getting using the error reporting that you provided are: Undefined index: xxx... (xxx being every field name in the db). I have an 'id' field in the db, auto_increment-ing - did I forget to set that as the index?
The POST data is stored in the $_POST array, not the $_Post array. You should get a Notice on the undefined variable in your server log or in the browser (if PHP messages are sent to the browser).
The problem is in your post array name $_Post
$date=$_Post['date'];
$time=$_Post['time'];
$city=$_Post['city'];
$fire=$_Post['fire'];
$addy=$_Post['addy'];
$level=$_Post['level'];
$desc=$_Post['desc'];
$units=$_Post['units'];
$who=$_Post['who'];
Instead of $_Post you should use $_POST. Also, you can do
var_dump($_POST);
at the top of php file, so you will be able to see what the form sends to your script.
Regards
changed a few things, this should work.. if it doesnt is most likely an issue with your db
<html>
<body>
<form action="insert.php" method="POST"><br> <!-- method POST-->
Date: <input type="text" name="date" id="date"><br>
Time: <input type="text" name="time" id="time"><br>
City: <input type="text" name="city" id="city"><br>
Fire Dept: <input type="text" name="fire" id="fire"><br>
Address: <input type="text" name="addy" id="addy"><br>
Call Type/Level <input type="text" name="level" id="level"><br>
Description: <input type="text" name="desc" id="desc"><br>
Units: <input type="text" name="units" id="units"><br>
Submitted by: <input type="text" name="who" id="who"><br> <!-- name"who" changed -->
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
<?php
if (isset($_POST['submit'])) {
$db=mysql_connect("", "", "") or die ("Cant connect");
$mydb=mysql_select_db("rm911_incidents") or die ("Cant find db");
$date = $_POST['date']; //_POST not _Post
$time = $_POST['time'];
$city = $_POST['city'];
$fire = $_POST['fire'];
$addy = $_POST['addy'];
$level = $_POST['level'];
$desc = $_POST['desc'];
$units = $_POST['units'];
$who = $_POST['who'];
$sql = "INSERT INTO incidents ( date , time, city , fire , addy , level , desc , units , who )
VALUES ( '$date' , '$time' , '$city' , '$fire' , '$addy' , '$level' , '$desc' , '$units' , '$who' )";
$result = mysql_query($sql) or die ("Cant insert");
if($result)
{
echo "<br>Input data is successful";
}
else
{
echo "<br>Input data has failed";
}
}
?>
Also you're missing an opening square bracket:
Address: input type="text" name="addy" id="addy"><br>
Should be:
Address: <input type="text" name="addy" id="addy"><br>
Try doing this in your php file at the very top after the <?php:
//error reporting set to all
error_reporting(E_ALL);
ini_set('display_errors', 'On');
Also place your php code before your html.
You should see errors being outputted and be able to debug it.
Post the errors here if you need help.
can you check if Submitted by: <input type="text" name"who" id="who"><br> is causing error..
it should be Submitted by: <input type="text" name="who" id="who"><br>
If this doesnt help.. Try running a static insert query in your php file and check if its working...
Regards,
Leo

Categories