Inserting HTML Form data into MySQL with PHP - php

I'm trying to make a simple message board MySQL database where you can write a review and submit it via an HTML form on one page and view all of the reviews on a separate page once you've submitted your review.
My problem is two of the fields from the HTML form are not being inserted into my MySQL database which results in my view all reviews page to be missing the Name and Title.
Link to what the "Read all Reviews" page looks like.
The code works without any issue when I tested it doing MySQL queries with just PHP but I need my HTML form to work.
HTML form:
<form action ="process.php" method = "post">
<fieldset>
<legend>Review Field</legend>
Reviewer Name: <br />
<input type="text" name "name" id = "name"><br />
Title of Review:<br />
<input type="text" name "title" id = "title"><br />
Enter your review below:
<!--Textbox start-->
<textarea name="body" id = "body" rows="10" cols="100">
</textarea>
<!--Textbox end-->
<br />
<input type="submit" name = "submit" id="submit">
<br />
</fieldset>
</form>
Code for process.php:
<?php // Create a database connection.
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "password";
$dbname = "ya_reviews";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
//Test if connection occurred.
if (mysqli_connect_errno()) {
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
}
//Perform database query
$name = $_POST['name'];
$title = $_POST['title'];
$body = $_POST['body'];
//This function will clean the data and add slashes.
// Since I'm using the newer MySQL v. 5.7.14 I have to addslashes
$name = mysqli_real_escape_string($connection, $name);
$title = mysqli_real_escape_string($connection, $title);
$body = mysqli_real_escape_string($connection, $body);
//This should retrive HTML form data and insert into database
$query = "INSERT INTO reviews (name, title, body)
VALUES ('".$_POST["name"]."','".$_POST["title"]."','".$_POST["body"]."')";
$result = mysqli_query($connection, $query);
//Test if there was a query error
if ($result) {
//SUCCESS
header('Location: activity.php');
} else {
//FAILURE
die("Database query failed. " . mysqli_error($connection));
//last bit is for me, delete when done
}
mysqli_close($connection);
?>
View all Reviews:
<?php
//This will fetch the data from the database
$query = "SELECT * FROM reviews";
$result = mysqli_query($connection, $query);
//Test if there was a query error
if (!$result) {
die("Database query failed.");
}
// This will let me display the data.
// The loop will be spilt so I can format with HTML
while ($row = mysqli_fetch_assoc($result)) {
//output data from each row
?>
Name: <?php echo $row["name"] . "<br />"; ?>
Title: <?php echo $row["title"] . "<br />"; ?>
Review: <?php echo $row["body"] . "<br />";
echo "<hr>"; ?>
<?php
} ?>
Note: I connected to the database with the same code seen in process.php before the above code, I excluded it to save space.

Your HTML attribute syntax is incorrect. Its missing = sign between attribute and value.
Change name "name" to name="name" and name "title" to name="title"
<input type="text" name="name" id = "name"><br />
Title of Review:<br />
<input type="text" name="title" id = "title"><br />
Also during insert you aren't using escaped values.
Use $name instead of $_POST["name"] in insert query. Same goes for title and body values.

The problem is that the name attribute is not correct in HTML.
<input type="text" name="name" id = "name"><br />
<input type="text" name="title" id = "title"><br />

I think you messed up with syntax of HTML
<form action ="process.php" method = "post">
<fieldset>
<legend>Review Field</legend>
Reviewer Name: <br />
<input type="text" name="name" id = "name"><br />
Title of Review:<br />
<input type="text" name="title" id = "title"><br />
Enter your review below:
<!--Textbox start-->
<textarea name="body" id = "body" rows="10" cols="100">
</textarea>
<!--Textbox end-->
<br />
<input type="submit" name = "submit" id="submit">
<br />
</fieldset>
</form>
It will work surely!

Yo, you're just missing some syntax, therefore creating errors when it comes to gathering the data from those elements,
<input type="text" name "title" id = "title">
You're missing the "=" sign from the name parameter

Related

why is not saving to SQL data base from html form? it does not show any error messages

I tried many ways if I insert data to my data base without the
from method it works but with the form and it's method is not working and it doesn't show any error. I don't see any message seems like the code doesn't exist. the connection is good and the name of the table is fine. I am trying to save some data before to implement more code like validation password check and more but if it doesn't save the data how I am going to implement validations. I used the numbers of my serve because it could not be connect with localhost name.
<?php
session_start();
$_SESSION['message'] = "";
$host = "localhost:3308";
$user = "root";
$password = "";
$database = "accounts";
$connect = mysqli_connect($host, $user,
$password,$database); //open the connection.
if(!$connect){
die("cannot connect to database
field:".mysqli_connect_error());
}
else
{
`enter code here`echo "Database is connected". "
<br/>";
if(isset($_POST['create'])){
session_start();
$userName = $_POST['username'];
`enter code here`$email = $_POST['email'];
$pasword = $_POST['pasword'];
$avatar= $_POST['avatar'];
$sql = "INSERT INTO new_table (
username,email,password,avatar)
VALUES (
'$userName','$email','$pasword','$avatar')";
if(mysqli_query($connect, $sql)) {
$_SESSION['message']= "creted";
}
else{
$_SESSION['message']= "not created";
}
}
else {
$_SESSION['message']= "Enter valid data";
}
//my html form
<form action="conectingDB.php" method = "post">
<form action="conectingDB.php" method = "post">
<header>
<h3></h3>
</header>
<br /><br />
<div><?php $_SESSION['message'] ?></div>
<input type="text" name="username" placeholder=
"username" required /><br /><br />
<input type="email" name="email" placeholder = "email"
required /> <br /><br />
<input type="password" name="password"
placeholder="pasword" required /> <br /><br />
<div class = "avatar"><label>Select your avatar:
<input type= "text" name="avatar" ></label></div>
<input type="button" value="create account"
name="create" />
I suggest one more files in your directory with the name "conectingDB.php" and in this file insert the insert command with the connection to the database.
replace the
<input type = "button" value = "create account" name = "create" />
for this
<button type = "submit" value = "create account" name = "create"></button>

Showing submitted values into database into next php page

I'm trying to make a verify page for my reservation website but I can't show only specific data from picking the specific id.
For example, I submitted a new customer and it generated an ID = 1. Then the form will take me to another PHP page and I want it to show the name of the customer I just submitted by choosing it's specific ID (which is 1 or whatever id was generated from before).
Here's my first submit form:
<form action="menuactions/temporestoaction.php" method="post" enctype="multipart/form-data">
<label class="control-label">First Name:</label>
<input class="form-control" placeholder="John" type="text" name="first_name" required autofocus/>
<br />
<label>Last Name:</label>
<input class="form-control" placeholder="Doe" type="text" name="last_name" required/>
<button type="submit" name="submit" class="btn btn-success btn-md">Submit</button>
</form>
and this is the temporestoaction.php which will submit all the values into mysql database:
<?php
if(isset($_POST['submit'])) {
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "records";
//Form Inputs to Db
$foodid = $_POST['foodid'];
$firstname = $_POST['first_name'];
$lastname = $_POST['last_name'];
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO `temporesto` ( first_name, last_name)
VALUES ( '$firstname', '$lastname')";
if (mysqli_query($conn, $sql)) {
header('Location: ../temporesto.php?id='.$row['food_id'].'');
exit();
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
}
?>
Which will then redirect to a new PHP page, the temporesto.php:
<?php
include 'menuactions/temporestopick.php';
while($row = mysqli_fetch_array($data, MYSQLI_ASSOC)){
?>
<input type='hidden' value=" <?php echo $_GET['food_id'];?>" name="iduse">
<label class="control-label">First Name: <h2><?php echo $row['first_name'];?></h2></label>
<input class="form-control" type="text" name="first_name" />
<br />
<label class="control-label">Last Name: <h2><?php echo $row['last_name'];?></h2></label>
<?php
}
?>
The problem I have with this is that it shows all of the values submitted instead of a specific one, see this image for reference.
P.S
temporestopick.php is using "SELECT * FROM temporesto";
If you are trying to display a verify page before you process form, then I don't see the need to save first into the database. You can simply post all form values from your form and they would be contained in your $_POST which is an array. You then sanitize all inputs, loop through to get all their values then display them for verification. If all is okay, you sanitize again then insert into your database.
In case you are a little lost, you can do the following.
Submit your form with the values filled to your action page.
In your action page, sanitize all received values from the form.
You can use extract($_POST); to get the values of your form fields into strings.
Display for viewing and confirmation then submit values to database after sanitizing.
Sample:
process.php
<?php
if(isset($_POST['submit']))
{
//sanitize your $_POST values
foreach($_POST as $key => $value)
{
$_POST[$key] = sanitize($value);
//You can out errors from empty fields here if you want
}
//extract $_POST values into strings
extract($_POST);
/*
If your form has something like input name="fname" when you extract you will get the value for name as $name
You can then echo Name: $fname
*/
$values = <<<EOD
Name: {$name}
Email: {$email}
EOD;
}
I hope you are able to get on with this. After this stage of verification then you can save to database to avoid you saving unwanted data into your database.
I removed the whole code inside temporestoaction.php and added this:
<html>
<body>
<?php
if(isset($_POST['submit']))
{
//Form Inputs to Db
$firstname = $_POST['first_name'];
$lastname = $_POST['last_name'];
$contact = $_POST['contact'];
$eventdate = $_POST['eventdate'];
$eventtime = $_POST['eventtime1'];
$eventhours = $_POST['eventhours1'];
$packages = $_POST['packages'];
$food = $_POST['food'];
$prices = $_POST['price-total'];
$treats = $_POST['treats'];
$chkfood = "";
$chktreats = "";
foreach($food as $chkfood1)
{
$chkfood.= $chkfood1.",";
}
foreach($treats as $chktreats1)
{
$chktreats.= $chktreats1.", ";
}
?>
<label><h2>NAME: <?php echo $firstname . " " . $lastname; ?></h2> </label>
<br/>
<label><h2>Contact: <?php echo $contact; ?></h2></label>
<br/>
<label><h2>Food: <?php echo $chkfood; ?></h2></label>
<br/>
<label><h2>Event Date: <?php echo $eventdate; ?></h2></label>
<br/>
<label><h2>Event Time: <?php echo $eventtime; ?></h2></label>
<br/>
<label><h2>Event Hours: <?php echo $eventhours; ?></h2></label>
<br/>
<label><h2>Packages: <?php echo $packages; ?></h2></label>
<br/>
<label><h2>Food: <?php echo $chkfood; ?></h2></label>
<br/>
<label><h2>Prices: <?php echo $prices; ?></h2></label>
<br/>
<label><h2>Treats: <?php echo $chktreats; ?></h2></label>
</body>
<?php
}
?>
</html>
With this code, it takes all the inputs from my submit form and transfers it into the next page for verifying.

Insert data mysqli and php in form 1 and return to new form 2

Hi all I am new to mysqli and php (currently studying and trying to work on a test database- I have not used security measures at this wont be available public) and trying to get the information I have just submitted in the form to display in a new form which will then receive further user input then submitted to database. Here is an example of what I have done so far:
Form 1 (customer table - cust id =primary key)
Customer Details ie name address telephone etc
dynamic drop down box - consists of 4 options.( would like whatever option is selected here to return a particular form)
The form is currently submitting correctly in the database, but I would like once it has submitted to the database to return the customer info (including the customer id as that is the relationship in the new table) and on the form2(service table - service id is primary key) so the user can input further data to the form and submit.
Hope this makes sense, any help would be appreciated.
Thanks
Response 1
Thank you for my response I probably havent made myself very clear.
Form 1 where dynamic dropdown list is - when user submits forms I would like it to return form 2 with the customer info we inserted in form 1
Form 1
<!doctype html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>test</title>
</head>
<body>
<form action="newbookingcode.php" method="post">
<p>First Name: <input type="text" name="firstname"/>
Last Name: <input type="text" name="lastname"/></p>
<p>Business Name: <input type="text" name="businessname"/></p>
<p>Contact Number: <input type="text" name="number"/>
Alt Number: <input type="text" name="altno"></p>
<p>Email Address:<input type="text" name="email"></p>
<p>Street No:<input tyep="text" name="streetno">
Street Name:<input type="text" name="street"></p>
<p>Suburb:<input type="text" name="suburb">
Postal Code:<input type="text" name="postalcode">
State: <input type="text" name="state"></p>
**<p>Type of Service Required: <select id="category" name="category" >
<option value="nill">---Select Service---</option**
<?php
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM serviceType";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<option value= "'.$row['jobType'].'" >' . $row['jobType'] . '</option>';
}
} else {
echo "0 results";
}
$conn->close();
?>
</p>
</select>
<p>
<input type="submit"/>
</p>
</form>
</body>
</html>
Query in separate file
$fname=$_POST['firstname'];
$lname=$_POST['lastname'];
$bname=$_POST['businessname'];
$phone=$_POST['number'];
$altphone=$_POST['altno'];
$email=$_POST['email'];
$streetno=$_POST['streetno'];
$street=$_POST['street'];
$suburb=$_POST['suburb'];
$postcode=$_POST['postalcode'];
$state=$_POST['state'];
$service=$_POST['category'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO customer (contactFirstName,contactLastName,businessName,contactNumber,altNumber,email,streetNo,streetName,suburb,postalCode,state,serviceType)
VALUES ('$fname','$lname','$bname','$phone','$altphone','$email','$streetno','$street','$suburb','$postcode','$state','$service')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Check this code and let me know if you have any questions:
<?php
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM serviceType";
$result = $conn->query($sql);
/************** IMPORTANT *************/
$whichForm = 1;//to know which form to show
$last_customer_id = 0;//to store last customer id
//to store your customer information
$fname=$lname=$bname=$phone=$altphone=$email=$streetno=$street=$suburb=$postcode=$state=$service='';
//To handle post operations after clicking on post.
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$whichForm = 2; // to show second form
//if it is first form
if($_POST['action'] == 'firstForm')
{
$fname=$_POST['firstname'];
$lname=$_POST['lastname'];
$bname=$_POST['businessname'];
$phone=$_POST['number'];
$altphone=$_POST['altno'];
$email=$_POST['email'];
$streetno=$_POST['streetno'];
$street=$_POST['street'];
$suburb=$_POST['suburb'];
$postcode=$_POST['postalcode'];
$state=$_POST['state'];
$service=$_POST['category'];
//Preparing your insert query
$sql = "INSERT INTO customer (contactFirstName,contactLastName,businessName,contactNumber,altNumber,email,streetNo,streetName,suburb,postalCode,state,serviceType) VALUES ('$fname','$lname','$bname','$phone','$altphone','$email','$streetno','$street','$suburb','$postcode','$state','$service')";
$conn->query($sql); //insert into db
//get last insert customer id and you already have your customer information
//in the variables above $fname, $lname.....etc
$last_customer_id = $conn->insert_id;
}
else{//do something with your second form
//get last customer info
$sql = "SELECT * FROM serviceType where id = ".$POST_['last_customer_id']."";
$result = $conn->query($sql);
$res = $result->fetch_assoc();
//you can access customer information like res['contactFirstName']
}
}
$conn->close(); //close your connection
?>
<!doctype html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>test</title>
</head>
<body>
<?php
if($whichForm == 1){ //if it is first form
?>
<form id="1" action="test2.php" method="post">
<!-- This input is needed to identify which form -->
<input type="hidden" name="action" value="firstForm" />
<p>First Name: <input type="text" name="firstname" value="<?php echo $fname; ?>"/>
Last Name: <input type="text" name="lastname" value="<?php echo $lname; ?>" /></p>
<p>Business Name: <input type="text" name="businessname" value="<?php echo $bname; ?>"/></p>
<p>Contact Number: <input type="text" name="number" value="<?php echo $phone; ?>"/>
Alt Number: <input type="text" name="altno" value="<?php echo $altphone; ?>"></p>
<p>Email Address:<input type="text" name="email" value="<?php echo $email; ?>"></p>
<p>Street No:<input tyep="text" name="streetno" value="<?php echo $streetno; ?>">
Street Name:<input type="text" name="street" value="<?php echo $street; ?>"></p>
<p>Suburb:<input type="text" name="suburb" value="<?php echo $suburb; ?>">
Postal Code:<input type="text" name="postalcode" value="<?php echo $postcode; ?>">
State: <input type="text" name="state" value="<?php echo $state; ?>"></p>
**<p>Type of Service Required: <select id="category" name="category" >
<option value="nill">---Select Service---</option>
<?php
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
//this if to save the value of the selected category
if($row['jobType'] == $service)
{
echo '<option value= "'.$row['jobType'].'" SELECTED>' . $row['jobType'] . '</option>';
}
else
{
echo '<option value= "'.$row['jobType'].'">' . $row['jobType'] . '</option>';
}
}
}
?>
</select></p>
<button type="submit">Submit</button>
</form>
<?php
}//ending bracket for if($whichForm == 1)
else if($whichForm == 2){ // or just else will do fine
?>
<form id="2" action="test2.php" method="post">
<!-- This input is needed to identify which form -->
<input type="hidden" name="action" value="secondForm" />
<!-- This input is needed to store the last customer id -->
<input type="hidden" name="last_customer_id" value="<?php echo $last_customer_id; ?>" />
<!-- here you put your second form -->
<button type="submit">Submit</button>
</form>
<?php
}//ending bracket for else if($whichForm == 2)
?>
</body>
</html>
Assuming you are using a database object like mysqli to do DB interactions.
Say form1 generate insert query $insertQyery.
And you are executing this query (insert statement) like
$mysqli->query($insertQyery);
After the execution of this insert statement you can use
$customerId = $mysqli->insert_id
Now using this $customerId you can show records details on form2 or use this $customerId as reference on form2.
After customer submit FORM #1
on the next page
let's get the last customer details :-
<?php
//after mysqli connection
$contactFirstName = '';
$contactLastName = '';
$businessName = '';
$sql_get_data = "SELECT * FROM customer ORDER BY customerID DESC limit 1 ";
$query_get_data = mysqli_query($conn, $sql_get_data);
while ($row = mysqli_fetch_array($query_get_data, MYSQLI_ASSOC)) {
//specify which data you want to get from "customer" table
$contactFirstName = $row['contactFirstName'];
$contactLastName = $row['contactLastName'];
$businessName = $row['businessName'];
}
?>
HTML Form#2 :-
<form id="form2" method="post">
<input type="text" value="<?php echo 'contactFirstName'; ?>"
<input type="text" value="<?php echo 'contactLastName'; ?>"
<input type="text" value="<?php echo 'businessName'; ?>"
</form>
Hope this answer will help you.

Why is my form data not posting to the database in php [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'm trying to insert data to a MySQL table with PHP. I have a form that I would like to post form data like username and password. Everything seems to go fine but the data does not get posted to the database. My database connection is simple... Here it is from a file called db_connection.php:
<?php
define("DB_SERVER", "localhost");
define("DB_USER", "");
define("DB_PASS", "");
define("DB_NAME", "global_gl");
// 1. Create a database connection
$connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
// Test if connection succeeded
if(mysqli_connect_errno()) {
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
}
?>
The page that has the form is called newUser.php and it posts to itself. Here's the page:
<?php
require_once("/includes/session.php");
require_once("includes/db_connection.php");
require_once("includes/functions.php");
require_once("includes/validation_functions.php");
?>
<?php
if (isset($_POST['submit'])) {
// Process the form
// validations
$required_fields = array("firstName", "lastName", "email", "username", "password");//TODO: add country and birthday to this after debugging
validate_presences($required_fields);
$fields_with_max_lengths = array("username" => 30);
validate_max_lengths($fields_with_max_lengths);
if (empty($errors)) {
// Perform Create
$firstName = mysql_prep($_POST["firstName"]);
$lastName = mysql_prep($_POST["lastName"]);
$email = mysql_prep($_POST["email"]);
$username = mysql_prep($_POST["username"]);
$hashed_password = mysql_prep($_POST["password"]);
$query = "INSERT INTO useradmin (";
$query .= " firstName, lastName, email, username, hashed_password, ";
$query .= ") VALUES (";
$query .= " '{$firstName}','{$lastName}','{$email}','{$username}','{$hashed_password}'";
$query .= ")";
$result = mysqli_query($connection, $query);
if ($result) {
// Success
$_SESSION["message"] = "User created.";
redirect_to("manage_admin.php");//TODO: After cretion choose a page to return to.
} else {
// Failure
$_SESSION["message"] = "User creation failed.";
}
}
} else {
// This is probably a GET request
} // end: if (isset($_POST['submit']))
?>
<?php include("includes/layouts/header.php"); ?>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/jquery-ui.min.js"></script>
<script type="text/javascript" src="scripts/bday-picker.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#createUserDatePicker").birthdaypicker({});
});
</script>
</head>
<div id="main">
<div id="navigation">
<?php// echo navigation($current_subject, $current_page); ?>
</div>
<div id="page">
<form action="newUser.php" method ="post">
<p>First Name:
<input type = "text" name ="firstName" value=""/>
</p>
<p>Last Name:
<input type = "text" name ="lastName" value=""/>
</p>
<p>Email:
<input type = "email" name ="email" value=""/>
</p>
<p>Username:
<input type = "username" name ="username" value=""/>
</p>
<p>Password:
<input type = "password" name ="password" value=""/>
</p>
Counntry:
<?php
include("countrySelect/index.html");
?><br>
</p>
<p>Birthday:
<div class="picker" id="createUserDatePicker"></div>
</p>
<p>
<input type = "radio" name ="contactMe" value="0"/> Contact me with news and exclusive conent about Global Gaming League and West Coast Chill products.
</p>
<p>
<input type = "checkbox" name ="accept" value="0"/> I accept the terms of service and privacy policy.
</p>
<p>
<input type="submit" name="submit" value="Create User" />
</p>
</form>
<p>
Cancel <!--Note: this should take us back to a previous page
</p>
</div>
</div>
<?php include("includes/layouts/footer.php"); ?>
When I click on the submit button, the form fields are cleared and nothing is saved to the database. Can you please help with determining why data is not posted? Thanks!
try changing
<input type="username" name ="username" value=""/> change type="text"
Here
<form action="newUser.php" method ="post"> newUser.php where is it what does it do??

How to print the mysql result using form form which is readonly

the output didt display on the readonly form
How to print the sql result to the form which is readonly
Provide html code and action.php code. I have try to use &result on readonly form value
<body>
<form action = "action.php" method="post" >
input: <input type="text" name="v_id" />
<input type="submit" />
</body>
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'password';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if (!$conn) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('transport_fyp207');
$id = $_POST['v_id'];
$sql = "SELECT v_price " .
"FROM vehicle " .
"WHERE v_id = $id";
$result = mysql_query($sql);
?>
<body>
<label for="textfield">output:</label>
<input name="textfield"
type="text"
id="textfield"
readonly="readonly"
value = "<?php $result ?>">
</body>
you forgot the "echo" and btw you could have the same result with less typing:
<label>
output:
<input type="text" readonly value="<?php echo $result ?>">
</label>
EDIT: as fred -ii- pointed out, this will only work if $result was set. If you want to display something in case of request failure, simply set $result to a default value, something like:
<?php echo $result ? $result : "undefined"; ?>
And also your sql query is incomplete. Read the PHP manual and see how it's done.

Categories