Updating user table in database - php

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>

Related

Can A Form Method Be Post And Get?

I am learning PHP and have a situation where I want the method to be POST to pass variables to my php and
1) Connect to Server2) store results in a variable3) Display an HTML Table
However, I later on in my syntax want to use GET to "recall" that variable and output the results to a CSV file. This is what I have, but when I click the button Generate nothing happens. Is this possible? If not, how should I re-write the syntax to make ithappen?
<body>
<form method="POST">
End Date:<input type="date" name="end" value="<?= $_POST['end'] ?>">
<input type="submit" name="submit" value="Go">
</form>
</body>
<?php
if (isset($_POST['submit']))
{
//Connect To Server
//Store Result Set in Variable
//Display HTML Table
}
?>
<form method="get">
<button type="submit" name="csv" value="1">Generate CSV</button>
</form>

PHP - Get value of input field and pass it through the link

I get the id trough the link, this is no problem because there is a table "id" in the database, but i also want to pass the value from input field "quantity" trough the link.. Thank you in advance!
<?php
require_once 'database.php';
$id = $_GET['id'];
$query = sprintf("SELECT * FROM products WHERE id = '%s'", $id);
$result = mysql_query($query);
while( $row = mysql_fetch_assoc($result)) {
echo '<table>';
?>
<form action="add.php?id=<?php echo $row['id'];?>" method="POST">
<fieldset>
<legend> ADD quantity </legend>
Quantity: <br>
<input type="text" name="quantity" size="15"> </input> </br>
<input type="submit" value="Add" />
</fieldset>
</form>
?>
You are submitting a post request, so you should be able to get it like this :
$quantity = $_POST['quantity'];
If you want to send multiple GET values you can separate them via & (&).
You can do this:
link
Note: is better (standard) to use & instead of &. like this:
link
Use the $_POST var, as it follows:
$quantity=$_POST['quantity'];
But please, don't put the $id var and the $quantity directly on the sql query it will lead to mysql-injection attacks. Use PHP's PDO class or sanitized your input with proper function (like mysqli::real_escape_string()). And please not that mysql_* functions are deprecated since php 5.5 and removed since php 7.0.
you will have to use this:
<form action="add.php?id=<?php echo $row['id'];?>" method="GET">
<fieldset>
<legend> ADD quantity </legend>
Quantity: <br>
<input type="text" name="quantity" size="15"> </input> </br>
<input type="submit" value="Add" />
</fieldset>
</form>
And Get data from:
$_GET['quantity']

Form Action Process.php file not echoing results from mySQL DB

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">

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

How to write a javascript button which contains data?

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.

Categories