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
Related
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>
I created php form for inserting data to mysql. Data is inserted successfully but when i refresh my page it send empty fields to mysql db. code is as follows..
<?php
$con=mysqli_connect("localhost","root","") or die ("connection fail");
mysqli_select_db($con, 'college') or die ("database error");
$n=$_POST["name"];
$c=$_POST["class"];
$sql="insert into studentsinfo(name,class) values('$n','$c')";
mysqli_query($con,$sql);
echo "1 record inserted";
?>
<html>
<head>
</head>
<body>
<form action="" method="post">
Name: <input type="text" name="name" required="required" title="Enter Name">
Class: <input type="text" name="class" required="required">
<input type="submit" value="insert" name="sub">
</form>
</body>
</html>
any suggestion please.
Since you have your php and html code on same page. first php code get executed. this is why you get empty row inserted in data base on every time you refresh.
Solution is use different page for logic or check condition when submit button is pressed by using isset() and empty() function in php.
Also add condition in data base that they can not be blank.
Also Use Prepared Statements to prevent SQL injections
if (isset($_POST['sub'])) {
$n=$_POST["name"];
$c=$_POST["class"];
$sql="insert into studentsinfo(name,class) values('$n','$c')";
mysqli_query($con,$sql);
echo "1 record inserted";
}
Just need to check form request is empty or not
<?php
$con=mysqli_connect("localhost","root","") or die ("connection fail");
mysqli_select_db($con, 'college') or die ("database error");
if(isset($_REQUEST['sub']))
{
$n=$_POST["name"];
$c=$_POST["class"];
$sql="insert into studentsinfo(name,class) values('$n','$c')";
mysqli_query($con,$sql);
echo "1 record inserted";
}
?>
<html>
<head>
</head>
<body>
<form action="" method="post">
Name: <input type="text" name="name" required="required" title="Enter Name">
Class: <input type="text" name="class" required="required">
<input type="submit" value="insert" name="sub">
</form>
</body>
</html>
Currently, I have an index.php file with a form and a text input from the user as well as a submit button. When the submit button is pressed, the process.php file is supposed to get the data and echo it out. However, it just sends me to a blank page and does not echo anything out. I am well aware that I would need to style it the page, etc... But it just isn't echoing out at all. I am already connected to the mySQL DB with another php script and have tested that and it works fine so I know I am connected. What am i doing wrong?
index.php
<form action="process.php" form method="post" id="myForm">
<div class="col-xs-12 col-md-6">
<div class="input-group">
<span class="input-group-addon">
<input aria-label="..." type="checkbox" id="checkbox1">
</span>
<input aria-label="..." class="form-control" type="text" id="food1">
</div>
</div>
<input type="submit" value="Submit">
</form>
process.php
<?php
//Check whether the form has been submitted
if($_POST['submit'] == "Submit")
{
$varFood1 = $_POST['food1'];
$sql = "SELECT menu.dish FROM menu WHERE menu.description LIKE '%varFood1%'"; // sql query
$result = mysql_query($sql);
// Loop the recordset $result
// Each row will be made into an array ($row) using mysql_fetch_array
while($row = mysql_fetch_array($result)) {
echo "Items : {$row['dish']}\n";
}
}
?>
Use name attribute not id. <input aria-label="..." class="form-control" type="text" id="food1"> Try printting out the POST in the future.
<input aria-label="..." class="form-control" type="text" id="food1" name="food1">
Additional changes...
$varFood1 = mysql_real_escape_string($_POST['food1']);
$sql = "SELECT menu.dish FROM menu WHERE menu.description LIKE '%$varFood1%'";
without escaping you open yourself to injections. You should consider switching driver to mysqli or PDO as well.
The problem is that you are checking for $_POST['submit'], which the process.php file does not see, because it does not exist in the POST array. Solution: give your submit button a name, instead of this:
<input type="submit" value="Submit">,
which is what you have, do this:
<input type="submit" name="submit" value="Submit">
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>
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.