Passing a variable from html to mysql with php - php

I'm trying to put info I get from a form in html into a mysql database by way of php and do it all on the same page. My code so far is thus
<?php
require('conn.php');
if( isset($_POST['send'])){
$Product_Name = htmlspecialchars($_POST["product_name"]);
$Stock = htmlspecialchars($_POST["stock"]);
$Price = htmlspecialchars($_POST["price"]);
$insert = "INSERT INTO product (Product_Name, Stock, Price) VALUES ('$Product_Name','$Stock','$Price')";
if (mysqli_query($conn,$insert)){
echo "Values inserted!\n";
}
else {
echo "Error inserting values: " . mysqli_error($conn);
}
}
mysqli_close($conn);
?>
<html>
<body>
<form action="insert.php" method="post">
<table border="1">
<tr>
<td>Product Name</td>
<td align="center"><input type="text" name="product_name" size= "30" /></td>
</tr>
<tr>
<td>In Stock</td>
<td align="center"><input type="text" name ="stock" size="30"/></td>
</tr>
<tr>
<td>Price</td>
<td align="center"><input type="text" name="price" size="30"/></td>
</tr>
<tr>
<td>Submit</td>
<td align="center"><input type="submit" value="send"></td>
<tr>
However when I try and load the page its just comes up blank. It used to at least show the form before I added in the php code but I can't pin down what I broke. What do I need to change so that this puts the users data into the database?
Edit: changed code based upon Jeffry's catches

You're missing the name attribute in your submit button declaration.
update
<input type="submit" value="send">
to
<input type="submit" name = "send" value="send">

just quick check, you miss the closing ) in
$Product_Name = htmlspecialchars($_POST["product_name"];
i also think you need a dot to append the string
$insert = "INSERT INTO product (Product_Name, Stock, Price) VALUES ("$Product_Name","$Stock","$Price")";
and if your product name is a varchar, you might need to quote it

Related

Single submit button should perform multiple actions in php

I have two php pages.
dataentryform.php
report.php
In dataentryform.php through form tag I'm taking 19 user inputs with fcode being a primary key. Upon submit I want two things to happen.
data stored into the database
the data entered in the form should get displayed on the report.php
file.
My Problem:
Able to store values into the database and also retrieve it.
But, the values printed on the report.php file will always
correspond to the first row in the table
How do I fix this?
dataentryform.php
<form method="post" action="includes/dbinsert.php">
<table width="650" border="1" class="table1">
<tbody>
<tr>
<td class="label">Farmer's Code</td>
<td width="350" colspan="2"><input type="text" name="fcode"
class="text" autocomplete="off" required></td>
</tr>
<tr>
<td class="label">Farmer Name</td>
<td width="350" colspan="2"><input type="text" name="fname"
class="text" autocomplete="off" required></td>
</tr>
<tr>
<td class="label">Village/ Town</td>
<td colspan="2"><input type="text" name="village" class="text"
autocomplete="off" required></td>
</tr>
<tr>
<td class="label">Survey Number</td>
<td width="350" colspan="2"><input type="text" name="surnum"
class="text" autocomplete="off" required></td>
</tr>
<tr>
<td class="label">Plot Number</td>
<td width="350" colspan="2"><input type="text" name="plotnum"
class="text" autocomplete="off" required></td>
</tr>
...
...
...
...
...
...
...
...
...
...
...
...
<tr>
<td class="label">Potash (Tons/Acre)</td>
<td width="350" colspan="2"><input type="number" name="potash"
class="range" min="0" step="0.001" autocomplete="off" required></td>
</tr>
</tbody>
</table>
</div>
<button type="submit" name="submit" class="submit">Submit</button>
</div>
</form>
dbinsert.php
<?php
include 'dbconnect.php';
$fcode = $_POST['fcode'];
$fname = $_POST['fname'];
$village = $_POST['village'];
$surnum = $_POST['surnum'];
$plotnum = $_POST['plotnum'];
$acre = $_POST['acre'];
$gunta = $_POST['gunta'];
$soiltype = $_POST['soiltype'];
$wtrsrc = $_POST['wtrsrc'];
$factory = $_POST['factory'];
$labnum = $_POST['labnum'];
$nextcrop = $_POST['nextcrop'];
$coldate = $_POST['coldate'];
$gendate = $_POST['gendate'];
$season = $_POST['season'];
$taryield = $_POST['taryield'];
$nitro = $_POST['nitro'];
$phos = $_POST['phos'];
$potash = $_POST['potash'];
$sql = "INSERT INTO forminfo (fcode,fname,village,surnum,plotnum,acre,gunta,soiltype,wtrsrc,factory,labnum,
nextcrop,coldate,gendate,season,taryield,nitro,phos,potash)
VALUES ('$fcode','$fname','$village','$surnum','$plotnum','$acre','$gunta','$soiltype','$wtrsrc','$factory','$labnum',
'$nextcrop','$coldate','$gendate','$season','$taryield','$nitro','$phos','$potash');";
mysqli_query($conn, $sql);
header('location:../report.php');
?>
dbinsert.php is inserting values into the database. Then redirecting to report.php. Here I'm including dbextract.php. However, values displayed in report.php are incorrect.
Tried with this also but no luck.
dbextract.php
<?php
include 'dbconnect.php';
$fcode = $_POST['fcode'];
$sql = "SELECT * FROM forminfo WHERE fcode=['$fcode']";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($result);
?>
Error: Unidentified variable $fcode.
You could use session variables by adding
session_start();
$_SESSION['data'] = $_POST;
at the beginning of dbinsert.php and then using $fcode = $_SESSION['data']['fcode']; on dbextract.php
To claryfy Twista's answer - The Minimal, Complete, and Verifiable example would probably look like the example below.
NOTE:
I pretty much excluded everything that was causing any sort of errors, i also omitted the actual database insertion, since it doesn't really relate to the problem.
Judging by provided code the was actually one big problem:
Undefined indexes. Judging by provided code dbinsert.php has a lot of them. $acre = $_POST['acre'] and every $_POST[] after it should yeild Warning: Undefined index.
dbextract.php also has a very invalid SQL Query. It probably should have being SELECT * FROM forminfo WHERE fcode='$fcode'.
Actually it would be better if you used MySQLi Prepared Statements
The example below demonstrates working with $_SESSION.
dataentryform.php
<form method="post" action="dbinsert.php">
<table width="650" border="1" class="table1">
<tbody>
<tr>
<td class="label">Farmer's Code</td>
<td width="350" colspan="2"><input type="text" name="fcode" class="text" autocomplete="off" required></td>
</tr>
<tr>
<td class="label">Farmer Name</td>
<td width="350" colspan="2"><input type="text" name="fname" class="text" autocomplete="off" required></td>
</tr>
<tr>
<td class="label">Village/ Town</td>
<td colspan="2"><input type="text" name="village" class="text" autocomplete="off" required></td>
</tr>
<tr>
<td class="label">Survey Number</td>
<td width="350" colspan="2"><input type="text" name="surnum" class="text" autocomplete="off" required></td>
</tr>
<tr>
<td class="label">Plot Number</td>
<td width="350" colspan="2"><input type="text" name="plotnum" class="text" autocomplete="off" required></td>
</tr>
...
...
...
...
...
...
...
...
...
...
...
...
<tr>
<td class="label">Potash (Tons/Acre)</td>
<td width="350" colspan="2"><input type="number" name="potash" class="range" min="0" step="0.001" autocomplete="off" required></td>
</tr>
</tbody>
</table>
<button type="submit" name="submit" class="submit">Submit</button>
</form>
dbinsert.php
<?php
session_start();
// include 'dbconnect.php';
$fcode = $_POST['fcode'];
$fname = $_POST['fname'];
$village = $_POST['village'];
$surnum = $_POST['surnum'];
$plotnum = $_POST['plotnum'];
$_SESSION['fcode']=$fcode;
// $sql = "INSERT INTO forminfo (fcode,fname,village,surnum,plotnum,acre,gunta,soiltype,wtrsrc,factory,labnum,
// nextcrop,coldate,gendate,season,taryield,nitro,phos,potash)
// VALUES ('$fcode','$fname','$village','$surnum','$plotnum','$acre','$gunta','$soiltype','$wtrsrc','$factory','$labnum',
// '$nextcrop','$coldate','$gendate','$season','$taryield','$nitro','$phos','$potash');";
// mysqli_query($conn, $sql);
header('location: dbextract.php');
?>
dbextract.php
<?php
//session_start();
// include 'dbconnect.php';
$fcode = $_SESSION['fcode'];
//$fcode = $_GET['fcode'];
var_dump($fcode);
// $sql = "SELECT * FROM forminfo WHERE fcode=['$fcode']";
// $result = mysqli_query($conn, $sql);
// $row = mysqli_fetch_array($result);
?>
The same can be done without the use of $_SESSION. dataentryform.php stays the same.
dbinsert.php
<?php
//session_start();
// include 'dbconnect.php';
$fcode = $_POST['fcode'];
$fname = $_POST['fname'];
$village = $_POST['village'];
$surnum = $_POST['surnum'];
$plotnum = $_POST['plotnum'];
//$_SESSION['fcode']=$fcode;
// $sql = "INSERT INTO forminfo (fcode,fname,village,surnum,plotnum,acre,gunta,soiltype,wtrsrc,factory,labnum,
// nextcrop,coldate,gendate,season,taryield,nitro,phos,potash)
// VALUES ('$fcode','$fname','$village','$surnum','$plotnum','$acre','$gunta','$soiltype','$wtrsrc','$factory','$labnum',
// '$nextcrop','$coldate','$gendate','$season','$taryield','$nitro','$phos','$potash');";
// mysqli_query($conn, $sql);
header('location: dbextract.php/?fcode='.$fcode);
?>
dbextract.php
<?php
//session_start();
// include 'dbconnect.php';
//$fcode = $_SESSION['fcode'];
$fcode = $_GET['fcode'];
var_dump($fcode);
// $sql = "SELECT * FROM forminfo WHERE fcode=['$fcode']";
// $result = mysqli_query($conn, $sql);
// $row = mysqli_fetch_array($result);
?>
The above shows that it can be done without $_SESSION. The thing that happens in this exaple is that you pass your desired value as a param. Then the GET request happens, and then you use $_GET['fcode'] to get your value.
!!!IMPORTANT!!!
The exapmles above, are just that - examples. You will likely have to customise them a bit to suit your needs. For instance - you will have to actually un-comment parts, that are working with database and re-write them a bit.
Consearning sending data with a single POST request to several different .php files - On the server side as far as i am aware a single POST request sends data to a single file. Note it is possible to send several POST request using AJAX, but AJAX works on client side, so AJAX won't be of assistance if a redirect happens at server side.

How To Do Mathematical calculation on a previously saved mysql data and new form input data in PHP?

I have a form with an input field that would update data on a mysql table column on submission.
Here is the table:- screenshot
Here is my form:-
<form name=updateamount method=post>
<table width="500" >
<tr>
<td width="161">New Due Amount: </td>
<td width="329"><label>
<input name="new_due" type="text" class="StyleTxtField" id="new_due">
</label></td>
</tr>
<tr>
<td><div align="center">UPDATE
</div></td>
</tr>
</table>
</form>
What i want to do is, to get the new input data from the form and add it to the data saved in amount column based on its ID in the table and update the new calculated data to that particular amount column. But its not working.
Here is my php code:-
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db ("store_records", $con);
if(isset($_GET['ID']))
{
$id=$_GET['ID'];
$sql_query="SELECT * FROM due_payments WHERE ID='$id'";
$result_set=mysql_query($sql_query);
$row=mysql_fetch_array($result_set);
}
if(isset($_POST['submit']))
{
$amount2=$row['amount'];
$p_date=$_POST['pdate'];
$newdue=$_POST['newdue'];
$newamount=$amount2+$newdue;
$sql_query = "UPDATE due_payments SET date='$p_date', amount='$newamount' WHERE ID='$id'";
}
?>
How can i make the codes correct so that i can get the calculation done and update the data on the table??
You are doing so much wrongs, any way I just tell your problem
Use your id in an input field and submit it with others
<form name=updateamount method=post action="updatenewdue.php">
<table width="500" >
<tr>
<td width="161">New Due Amount: </td>
<td width="329"><label>
<input name="new_due" type="text" class="StyleTxtField" id="new_due">
</label></td>
</tr>
<input type="hidden" name="id" value="<?php echo $row_updatenewdue['ID']; ?>">
<tr>
<td><div align="center"><button name="submit" type="submit">UPDATE</button>
</div></td>
</tr>
</table>
</form>
IN your updatenewdue.php
$con=mysql_connect("localhost","root","");
mysql_select_db ("store_records", $con);
if(isset($_POST['submit']))
{
$id=$_POST['id'];
$sql_query="SELECT * FROM due_payments WHERE ID='$id'";
$result_set=mysql_query($sql_query);
$row=mysql_fetch_array($result_set);
$amount2=$row['amount'];
$p_date=$_POST['pdate'];
$newdue=$_POST['new_due'];
$newamount=$amount2+$newdue;
$sql_query = "UPDATE due_payments SET date='$p_date', amount='$newamount' WHERE ID='$id'";
}
NB:I KNOW MYSQL IS DEPRICATED BUT I AM HELPING A BEGINNER

HTML dropdown menu issue

I have a dropdown HTML menu with some values which I want to insert into an input table. When the 'Insert Production' button is clicked I want it to insert these values into the relevant data table.
Previously I just entered the 'genre' details manually as text and they input into the table ok, but have now changed the input to a dropdown, but the value doesn't get entered into the table. Is there a simple way of ensuring that this value gets uploaded to the table? Sorry if this is painfully basic, but am still pretty new to all this.
<html>
<head>
<title>Inserting Production</title>
</head>
<body>
<form method="post" action="insert_product.php" enctype ="multipart/form-data">
<table width="500" height="650" align="center" border="2" bgcolor="#c6ff1a">
<tr align="center">
<td colspan="2"<h1>Insert new production:</h1></td>
</tr>
<tr>
<td align="right"><b>Production Name:</b></td>
<td><input type="text" name="prod_name" size="40"/></td>
</tr>
<tr>
<td align="right"><b>Production Genre:</b></td>
<td><select>
<option value="Drama">Drama</option>
<option value="Thriller">Thriller</option>
<option value="Comedy">Comedy</option>
<option value="Children">Children</option>
<option value="Sci-fi">Sci-fi</option>
<option value="Horror">Horror</option>
<option value="Documentary">Documentary</option>
<option value="Fantasy">Fantasy</option>
</select></form></td>
</tr>
<tr>
<td align="right"><b>Production Year</b></td>
<td><input type="text" name="prod_year"</td>
</tr>
<tr>
<td align="right"><b>Production Description</b></td>
<td><textarea name="prod_desc" cols="35" rows="10"/></textarea></td>
</tr>
<tr>
<td align="right"><b>Product Keywords</b></td>
<td><input type="text" name="prod_keywords"</td>
</tr>
<tr>
<td align="right"><b>Production Image</b></td>
<td><input type="file" name="prod_img"</td>
</tr>
<tr align="center">
<td colspan="2"><input type="submit" name="insert_production" value ="Insert Production"/></td>
</tr>
</form>
</body>
</html>
<?php
//fetches product title, cat etc and submits them to database
if(isset($_POST['insert_production'])) {
//text data variables
$product_name = $_POST['prod_name'];
$product_genre = $_POST['prod_genre'];
$product_year = $_POST['prod_year'];
$product_desc = $_POST['prod_desc'];
$product_keywords = $_POST['prod_keywords'];
//Inserting image names in db and image files saving in my htdocs/Admin_area/product_images/$product_img1
//Images names
$product_img1= $_FILES['prod_img']['name'];
//Image temporary name(we have to set image temporary names)
$temp_name1= $_FILES['prod_img']['tmp_name'];
if ($product_name == '' OR $product_genre == '' OR $product_desc == '' OR $product_year == ''){
//Simple validation alert. If user leaves any of above fields empty
//will pop-up alert box saying 'Please insert your data etc ...'
echo "<script>alert('Please complete all fields!')</script>";
exit();
}//if
else {
move_uploaded_file($temp_name1,"product_images/$product_img1");
$insert_product = "insert into productions (prod_name, prod_genre, prod_year, prod_desc, prod_keywords, prod_img)
values ('$product_name', '$product_genre', '$product_year', '$product_desc', '$product_keywords', '$product_img1')";
$run_product = mysqli_query($db, $insert_product);
//If this query runs
if ($run_product) {
echo "<script>alert('Production inserted successfully!')</script>";
echo "<script>window.open('index.php?insert_product', '_self')</script>";
}//if
}//else
}//if
?>
just add this line and try again to submit the from.
<select name="prod_genre">
You forgot to give your select tag a name. You need to give it a name if you want to use this form element for e.g. database storage etc.
So change <select> to <select name="prod_genre">
I hope this helps you!

HTML Form calling PHP returns blank

My html form is:
<form enctype="multipart/form-data" action="AddEmail.php" method="GET>
<table>
<tr>
<td>Email Address</td>
<td>First Name</td>
<td>Surname</td>
<td><td>
</tr>
<tr>
<td> <input type="text" name="emailAddress" value="example#email.com"> </td>
<td> <input type="text" name="firstName" value="First Name"> </td>
<td> <input type="text" name="surname" value="Surname"> </td>
<td> <input type="submit"> </td>
</tr>
</table>
</form>
and the php that it is calling is:
$Email = $_GET["email"]
$firstName = $_GET["fName"]
$surName = $_GET["surname"]
$sql = "INSERT INTO emailaddress (EmailAddress, FirstName, LastName)
VALUES ($Email, $firstName, $surName)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>`
It is meant to pass the inputted information on to a database. It is connecting to the database without an issue when I use already use pre-created values for it to input, but as soon as I try and get it to use inputted values and call the php it just returns with a blank page.
You are missing the semicolons at the end of the line for the first 3 lines of the php file.
A blank page is typical for a syntax error. Whenever a blank page is displayed for no good reason put the following lines at the top of your php file and you should see the php error displayed.
error_reporting(E_ALL);
ini_set('display_errors', 1);
Besides that:
You will also receive a SQL error because you are not enclosing the php variables in quotes when you construct the query. You should REALLY consider escaping all user submitted data.
$_GET["email"] should be $_GET["emailAddress"] as set in the form
$_GET["fName"] should be $_GET["firstName"] as set in the form
Consider using the html attribute "placeholder" instead of writing the hint as a value.
Also, what user3590911 said about the quote
Your
<form enctype="multipart/form-data" action="AddEmail.php" method="GET>
should be:
<form enctype="multipart/form-data" action="AddEmail.php" method="GET">
try this,
<form enctype="multipart/form-data" action="AddEmail.php" method="GET>
<table>
<tr>
<td>Email Address</td>
<td>First Name</td>
<td>Surname</td>
<td><td>
</tr>
<tr>
<td> <input type="text" name="email_address" value="example#email.com" > </td>
<td> <input type="text" name="firstName" value="First Name"> </td>
<td> <input type="text" name="surname" value="Surname"> </td>
<td> <input type="submit"> </td>
</tr>
</table>
</form>
<?php
$Email = $_GET["email_address"]
$firstName = $_GET["firstName"]
$surName = $_GET["surname"]
$sql = "INSERT INTO emailaddress (EmailAddress, FirstName, LastName) VALUES ($Email,$firstName, $surName)";
$queries = $conn->query($sql);
if ( $queries ) {
echo "New record created successfully";
}
else
{
die('Invalid query: ' . mysql_error());
}
$conn->close();
?>
<form enctype="multipart/form-data" action="AddEmail.php" method="GET>
to
<form enctype="multipart/form-data" action="AddEmail.php" method="post>

UPDATE mysql database and the id and the image in relation to the id?

I have this php file which will update a table in mysql database.
it works to a certain. it will update the name of the product (product_name) and it will update the (date_added) too. but it is not updating the id and as a result the image that was uploaded with that id is not showing!!
here is the code:
<?php
// Parse the form data and add inventory item to the system
if (isset($_POST['product_name'])) {
$product_name = mysql_real_escape_string($_POST['product_name']);
// See if that product name is an identical match to another product in the system
$sql = mysql_query("SELECT id FROM tomProduct WHERE product_name='$product_name' LIMIT 1");
$productMatch = mysql_num_rows($sql); // count the output amount
if ($productMatch > 0) {
echo 'Sorry you tried to place a duplicate "Product Name" into the system, click here';
exit();
}
// Add this product into the database now
$sql = mysql_query("UPDATE tomProduct SET product_name='$product_name', date_added=now()") or die (mysql_error());
$pid = mysql_insert_id();
// Place image in the folder
$newname = "$pid.jpg";
move_uploaded_file( $_FILES['fileField']['tmp_name'], "../tom/$newname");
header("location: verify_members.php");
exit();
}
?>
and here is the form:
<form action="verify_members.php" enctype="multipart/form-data" name="myForm" id="myform" method="post">
<table width="90%" border="0" cellspacing="0" cellpadding="6">
<tr>
<td width="20%" align="right">Product Name</td>
<td width="80%"><label>
<input name="product_name" type="text" id="product_name" size="64" />
</label></td>
</tr>
<tr>
<td align="right">Product Image</td>
<td><label>
<input type="file" name="fileField" id="fileField" />
</label></td>
</tr>
<tr>
<tr>
<td> </td>
<td><label>
<input type="submit" name="button" id="button" value="Add This Item Now" />
</label></td>
</tr>
</table>
</form>
anyone knows why this is happening?
Thanks
mysql_insert_id() returns the last INSERT record, not UPDATE.

Categories