Hi there I am struggling with getting my form to post its data to MySQL database.
I have a config file setup like this:
// server info
$server = 'localhost';
$user = 'root';
$pass = '';
$db = 'cms';
// connect to the database
$mysqli = new mysqli($server, $user, $pass, $db);
// show errors (remove this line if on a live site)
mysqli_report(MYSQLI_REPORT_ERROR);
The form php page:
<?php
include("config_database.php")
?>
<?php
include("addproduct.php")
?>
<article>
<section class="Input">
<fieldset><legend><span> Add a product to the database </span></legend>
<form action="addproduct.php" method="post">
<label> product name: </label><input type="text" name="name"><br />
<label> product quantity: </label><input type="text" name="quantity"><br />
<label> product description: </label><input type="text" name="description"><br />
<label> product price: </label><input type="text" name="price"><br />
<input type="submit" class="reg">
</form>
then a "addproduct.php" to hopefully send the data to the database:
require_once ("config_database.php");
if (isset($_POST['name']) &&
!empty($_POST["name"]) &&
isset($_POST['quantity']) &&
!empty($_POST["quantity"]) &&
isset($_POST['description']) &&
!empty($_POST["description"]) &&
isset($_POST['price']) &&
!empty($_POST["price"]))
{
$name = get_post('name');
$quantity = get_post('quantity');
$description = get_post('description');
$price = get_post('price');
$query = "INSERT INTO products VALUES" .
"('', '$name', '$quantity', '$description', '$price')";
}
function get_post($var)
{
return mysql_real_escape_string($_POST[$var]);
}
How do I get the data entered in my form into my database?
You try the insert query like this using mysqli.
$query = "INSERT INTO products VALUES (NULL, '$name','$quantity', '$description','$price')";
$mysqli->query($query);
and also use real escape string like this for mysqli.
$mysqli->real_escape_string($_POST[$var]);
Related
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.
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
My .php page is connected to mySql database successfully. It can see the table and pull from the tables but won't save data from the text-box in my php form to the database.
config.php
<?php
try{
$db = new PDO("mysql:host=localhost;dbname=nolarec;port=3307","root","");
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$db->exec("SET NAMES 'utf8'");
} catch(Exception $e) {
echo $e->getMessage();
exit;
}
?>
fball_event.php
<form method="post" action="fball_create.php">
<input type="hidden" name="submit" value="true">
<fieldset>
<legend>New Event</legend>
Id: <input type="text" name="id"/> <br/>
Name: <input type="text" name="name"/> <br/>
Time: <input type="text" name="time"/> <br/>
Type: <input type="text" name="type"/> <br/>
</fieldset>
<br />
<input type="submit" value="Create New Event" />
</form>
<?php
require_once('config.php');
if (isset($_POST['submit'])){
include ('config.php');
$id = $_POST['id'];
$name = $_POST['name'];
$time = $_POST['time'];
$type = $_POST['type'];
$results = $db->prepare ("INSERT INTO nolarec.fball_event (id, name, time, type) VALUES ('$id','$name','$time','$type')");
}
?>
First of all you should be using placeholders for your data inputs in the query, second of all you need to actually execute it, you've just prepared it. Try:
$id = $_POST['id'];
$name = $_POST['name'];
$time = $_POST['time'];
$type = $_POST['type'];
$results = $db->prepare ("INSERT INTO nolarec.fball_event (id, name, time, type) VALUES (:id,:name,:time,:type)");
$results->bindValue(":id", $id);
$results->bindValue(":name", $name);
$results->bindValue(":time", $time);
$results->bindValue(":type", $type);
$results->execute();
I've spent the last day trying to figure out how to incorporate PDO into my code to prevent sql injections. This is what I have come up with. However, whenever I submit my information from the browser, it is not updated into my table and no error messages are shown. Something is wrong but I'm not sure what. I'm postive the syntax is not the problem because I've checked that multiple times. I know my database can be accessed so I'm thinking there is a problem with the way I'm using PDO. Please help me guys.
The PSBE_LOGIN contains all the information to access my database
<?php
require_once 'PSBE_LOGIN.php';
$db_server = mysql_connect($db_hostname, $db_username, $db_password);
if (!$db_server) die("Unable to connect to MySQL:" . mysql_error());
mysql_select_db($db_database, $db_server)
or die("Unable to select database:" . mysql_error());
if (isset($_POST['title']) &&
isset($_POST['author']) &&
isset($_POST['isbn']))
//This checks to see if there is a value inputted into the form at the bottom
{
$title = get_post('title');
$author = get_post('author');
$isbn = get_post('isbn');
//This retrieves information from the user and assigns it to a variable
$stmt = $pdo->prepare('INSERT INTO classifieds(title, author, isbn)
. VALUES(:title, :author, :isbn)');
$stmt->execute(array('title'=> $title, 'author'=> $author, 'isbn' => $isbn));
}
echo <<<_END
<form action="PSBE_POST_AD.php" method="post">
Title <input type="text" name="title" />
Author <input type="text" name="author" />
ISBN <input type="text" name="isbn" />
<input type="submit" value="ADD RECORD" />
</form>
_END;
?>
EDIT: CODE REWRITTEN TO INCLUDE PDO API.
<?php
require_once'connection.php';
$db = new PDO('mysql:host='.$db_host.';dbname='.$db_name,$db_username,$db_pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
if (isset($_POST['title']) &&
isset($_POST['author']) &&
isset($_POST['isbn']))
//This checks to see if there is a value inputted into the form at the bottom
{
$title = get_post('title');
$author = get_post('author');
$isbn = get_post('isbn');
//This retrieves information from the user and assigns it to a variable
$stmt = $pdo->prepare('INSERT INTO classifieds(title, author, isbn)
. VALUES(:title, :author, :isbn)');
$stmt->execute(array('title'=> $title, 'author'=> $author, 'isbn' => $isbn));
}
echo <<<_END
<form action="PSBE_POST_AD.php" method="post">
Title <input type="text" name="title" />
Author <input type="text" name="author" />
ISBN <input type="text" name="isbn" />
<input type="submit" value="ADD RECORD" />
</form>
_END;
function get_post($var){
return mysql_real_escape_string($_POST[$var]);
}
?>
Get rid of both
$title = get_post('title');
$author = get_post('author');
$isbn = get_post('isbn');
and
function get_post($var){
return mysql_real_escape_string($_POST[$var]);
}
because the function you're using is based on an mysql_ function and those two APIs do not mix.
You don't need it, because you're already using placeholders.
while replacing it with
$title = $_POST['title'];
$author = $_POST['author'];
$isbn = $_POST['isbn'];
You also need to change
$stmt = $pdo->prepare(...
to
$stmt = $db->prepare(...
given your PDO connection $db = new PDO(...
You are not using them correctly. You need to connect using the PDO API (you're connecting using the mysql_ API). Otherwise, the preparation is correct.
I'm working on a Joomla module. I'm trying to take input from a form and insert it into a database. Here's my "helper.php" code:
<?php
/** post form to db module **/
// No direct access
defined( '_JEXEC' ) or die( 'Restricted access' );
//--build the form------------>
?>
<form name="names" id="names" action="<?php echo JURI::current(); ?>" method="post">
<p><input type="text" name="fname" id="fname" value="" /></p>
<p><input type="text" name="lname" id="lname" value="" /></p>
<p><input id="submit" name="submit" type="submit" value="Submit Names" /></p>
</form>
<!-- //--END BUILD THE FORM--------| -->
<?
if( (isset($_POST['lname'])) || (isset($_POST['fname'])) ) {
//first name or last name set, continue-->
$lname = $_POST['lname'];
$fname = $_POST['fname'];
/* $data =new stdClass();
$data->id = NULL;
$data->firstname = $fname;
$data->lastname = $lname;*/
$db =& JFactory::getDBO();
$query = "INSERT INTO `#__names` (`fname`, `lname`)
VALUES ($fname, $lname);";
$db->setQuery( $query );
$db->query();
} else {
echo '<h4>One Field Is Required!</h4>';
}
?>
I can see the form, but when I submit the data it doesn't update the database table. I've checked the Apache error log but it doesn't contain any information about it. What am I missing?
For your query it should be more like this, the way you have it will not work in 2.5.
$db = JFactory::getDbo();
$query = $db->getQuery(true)
->insert($db->quoteName('#__names'))
->columns(array($db->quoteName('fname', 'lname')))
->values($db->quote($fname),$db->quote($lname));
$db->setQuery($query);
$db->execute();
Remove ; from query and add quotes to the strings $fname and $lname
$query = "INSERT INTO `#__names` (`fname`, `lname`)
VALUES ('".$fname."', '".$lname."')";
And OPTIONALLY you need to insert NULL if the fields are empty like
$lname = (trim($lname) != '') ? $lname : 'NULL';
$fname = (trim(fname) != '') ? $fname : 'NULL';
Try this:
$query = "INSERT INTO `#__names` (`fname`, `lname`)
VALUES ('$fname', '$lname');";