How to insert multiple textfield? - php

I'm working on a project for school.
It's an invoice program but I'm stuck, can anyone help me
figure out how to get the values out of multiple textboxes /fields
and insert them in to my database.
This is what it looks like.
The user can select the amount of textfields that will be inserted in to the database.
[IMG]http://i61.tinypic.com/2sagwt4.png[/IMG]

Easy example:
<?php
$host=''; //define host
$user='xxx'; //define username
$pass='xxx'; //define password
$db_name='xxx'; //define db name
$db = new mysqli($host, $user, $pass, $db_name);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if(isset($_POST['status'])) { //code called when user sent form
$status = mysqli_escape_string($db, ($_POST['status']));
//same way to save other fields, just rename "status" to your value
$sql = "INSERT INTO /* table name here */ (status, /* define other line in DB here */) VALUES ('$status', /* define other variables to save here */)"; //save into database, see the example below
//example: $sql = "INSERT INTO mydatabase (status, email, name) VALUES ('$status', '$email', '$name')";
if ($db->query($sql) === TRUE) {
echo "Saved.";
}
else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
?>
<form enctype="multipart/form-data" action="<?php $_PHP_SELF ?>" method="POST">
<label for="status">Status: </label>
<input id="status" name="status" value="" />
//add other fields here, just rename "status" to your value
<input type="submit" name="submit" value="Send form" /></form>
It may be what you are looking for, just adapt it yourself.

Related

duplicate row formed in table when using PHP to store a form

I am making a site to display the family relations of an individual...I made use of PHP to store data from a form. I use access code to categorize different relations if an individual. i.e..101-the relations of person X.
I need a bit of help as to why to an entry is being entered twice into the database.(new to PHP and first time asking for help here)
Thank you in Advance!
forms code(IN ct.php):
<form id="frm1" action="ap.php" method="POST">
access code: <input type="text" name="code_entered" value=""><br><br>
position in family: <select name="fpos_entered">
<option>Grandfather</option>
<option>Grandmother</option>
<option>Father</option>
<option>Mother</option>
<option>Brother</option>
<option>Sister</option>
<option>Uncle</option>
<option>Aunt</option>
<option>Nephew</option>
<option>Niece</option>
<option selected>Yourself</option>
</select><br><br>
name: <input type="text" name="name_entered" value=""><br><br>
DOB:<input type="date" name="dob_entered" value=""><br><br>
<input type="submit" value="Submit">
</form>
i use the following PHP code to store the data from the form:
<?php
include 'ct.php';
$temp="temp";
$conn= mysqli_connect ('localhost','root','','familytree');
if (!$conn)
{
die ('Could not connect:' . mysql_error());
}
if (isset($_POST['code_entered']))
{
$acc= $_POST['code_entered'];
}if (isset($_POST['fpos_entered']))
{
$fpos= $_POST['fpos_entered'];
}if (isset($_POST['name_entered']))
{
$n= $_POST['name_entered'];
}if (isset($_POST['dob_entered']))
{
$db= $_POST['dob_entered'];
}
$sql ="insert into temp values ('$acc', '$n','$fpos','$db')";
$result = mysqli_query($conn,$sql);
if ($conn->query($sql) === TRUE) {
echo "<p>New record created successfully</p>.";
}
else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
which results in me having :
pic of the database after 2 enteries
<?php
declare(strict_types=1);
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "familytree";
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
try {
$stmt = $conn->prepare("
INSERT INTO `temp` (code, fpos, name, dob)
VALUES (:code, :fpos, :name, :dob)");
$stmt->bindParam(':code', $_POST['code_entered'] ?? null);
$stmt->bindParam(':fpos', $_POST['fpos_entered'] ?? null);
$stmt->bindParam(':name', $_POST['name_entered'] ?? null);
$stmt->bindParam(':dob', $_POST['dob_entered'] ?? null);
$stmt->execute();
echo "<p>New record created successfully</p>.";
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
I recommend you to use PDO instead of mysqli. Also, bind the attributes coming from outside :)
Official docu: https://www.w3schools.com/php/php_mysql_prepared_statements.asp
you can change the code of this
$result = mysqli_query($conn,$sql);
if ($conn->query($sql) === TRUE) {
echo "<p>New record created successfully</p>.";
}
else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
into this
$result = mysqli_query($conn,$sql);
if ($result === TRUE) {
echo "<p>New record created successfully</p>.";
}
else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
and also you must to be careful about sql injection so i think you must use this

mysql updating data only where post contains data

i have a simple form in html where user selects and ID from the table on the website (required data) and then he can / or not change 2 fields. First is a dropdown list of 2 values (strings), and the second is number of open spots!
So if a user leaves both fields empty and click send by mistake nothing should happen. If a user only changes one of the fields only that one should change!
I have checked every forum and almost all posts in here and i still cannot get it to work.
<form action="viv_settings_tecaji.php" method="post">
Datum termina (izberi ID):
<input type="number" name="ID" required><br><br>
<!--Sprememba tega datuma (če ne želiš spremenit pusti prazno):
<input type="date" name="nov_datum"><br><br>-->
Sprememba statusa (če želiš da ostane isto vpiši trenutni status!:
<select name="STATUS">
<option></option>
<option value="zaprt">Zaprt</option>
<option value="odprt">Odprt</option>
</select><br><br>
Sprememba števila odprtih mest
<input type="number" name="st_odprtih_mest"><br><br>
<input type="submit">
</form><br>
php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "viverius_education";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$update_status = $_POST['STATUS'];
$update_st_odprtih_mest = $_POST['st_odprtih_mest'];
$update_ID = $_POST['ID'];
if (empty($update_status) AND empty($update_status)){
header('Location: viv_settings_tecaji_main.php'); exit;
}
else{
$sql = "UPDATE razpisani_tecaji
SET
STATUS = IF('$update_status'='',STATUS,'$update_status'),
ST_ODPRTIH_MEST = IF('$update_st_odprtih_mest'='',STATUS,'$update_st_odprtih_mest'),
WHERE ID_TECAJA = $update_ID";
}
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
header('Location: viv_settings_tecaji_main.php'); exit;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}$conn->close();
?>
A decent form example would be like the following
<form action='' method='post'>
<input type='text' name='field1' required>
<select name='fieldSelect'>
<option value='value1'>Value1</option>
<option value='value2'>Value2</option>
</select>
<input type='submit' name='send'>
</form>
then the PHP would be like
<?php
if(isset($_POST['send'] && (!empty($_POST['field1']) || !empty($_POST['fieldSelect']))){
$field1 = $_POST['field1'];
$fieldSelect = $_POST['fieldSelect'];
//YOUR SQL CODE
} else {
echo "Please Insert Some Data";
}
?>
In brief:
Give your Submit button a name
Check if the submit button is clicked or not by if(isset($_POST['submit-button-name'])){}
define your form's $_POST variables with names.
Continue with SQL.
There are a couple of ways you can avoid inserting "empty" records in your database. It depends if you want to do it in the client-side (before the form submits) or server-side (when the form is submitted to the server).
I'll show you how to do it server-side, since you posted your php script.
In viv_settings_tecaji.php
...
$update_status = $_POST['STATUS'];
$update_st_odprtih_mest = $_POST['st_odprtih_mest'];
$update_ID = $_POST['ID'];
if($update_status == "" || $update_st_odprtih_mest == "" || $update_ID == ""){
die("One of the form fields was empty");
}
...
That would kill your script if any of the form fields was empty. Potentially, you could check for null or use PHP's empty() function.
I hope this helps!
So i manege to get it to work using the following code. So for the part if user leaves both field empty i will put together a script for at least 1 to be required.
$sql = "UPDATE razpisani_tecaji
SET
STATUS = IF(LENGTH('$update_status')=0, STATUS, '$update_status'),
ST_ODPRTIH_MEST = IF(LENGTH('$update_st_odprtih_mest')=0, ST_ODPRTIH_MEST, '$update_st_odprtih_mest')
WHERE ID_TECAJA = $update_ID";

how to link mysql 'id' to html element

I have a database with some rows of data that display on a webpage. Now, I am looking for a way to link each 'ID' field in mysql to a button so that when the button is clicked, a php script will run that deletes the row of mysql information associated with that ID.
I know this is incorrect but I think its close. Just don't know about the php portion inside the id tag. Help?
<form action="remove.php" method="post">
<input type="submit" value="Remove Entry" id="<?php $row['id'] ?>" />
</form>
Am I even on the right path?
Would remove.php look like...
<?php
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if($conn === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "DELETE from newcars (stock, year, make, model, trim)
WHERE ('$_POST[id] = $row[id]');
if(mysqli_query($conn, $sql)){
echo "Records deleted successfully.";
}
else {
echo "ERROR: Could not execute $sql. " . mysqli_error($link);
}
mysql_close($conn)
?>
Any help would be greatly appreciated.
Thank you!
HTML:
<form action="remove.php" method="post">
<input type="hidden" name="id" value="<?php echo (int)$row['id']; ?>">
<input type="submit" value="Remove Entry" />
</form>
You want to pass the ID in a form element, NOT with the submit button.
The PHP would look like this - and this is more secure than your original code as it uses prepared statements.
<?php
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if($conn === false) {
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$stmt = $conn->prepare("DELETE FROM newcars WHERE id = ?");
// prepare() can fail because of syntax errors, missing privileges, ....
if(false === $stmt) {
// and since all the following operations need a valid/ready statement object
// it doesn't make sense to go on
// you might want to use a more sophisticated mechanism than die()
// but's it's only an example
die('prepare() failed: ' . htmlspecialchars($mysqli->error));
}
$rc = $stmt->bind_param('i', $_POST['id']);
// bind_param() can fail because the number of parameter doesn't match the placeholders in the statement
// or there's a type conflict(?), or ....
if(false === $rc) {
// again execute() is useless if you can't bind the parameters. Bail out somehow.
die('bind_param() failed: ' . htmlspecialchars($stmt->error));
}
$rc = $stmt->execute();
// execute() can fail for various reasons. And may it be as stupid as someone tripping over the network cable
// 2006 "server gone away" is always an option
if(false === $rc) {
die('execute() failed: ' . htmlspecialchars($stmt->error));
}
$stmt->close();
//redirect page back to view page
?>
If you want your Id be posted, it should be like this:
<form action="remove.php" method="post">
<input type="hidden" name="id" value="<?php echo (int)$row['id']; ?>">
<input type="submit" value="Remove Entry" />
</form>
Post a hidden field with the name id and the value $row['id'].
And you should take care of the comments above to avoid mysql-injection in your php.

Database used to populate selection list

i am trying to create a form and in that form have a selection list in which the options are automatically populated with data from a database (namely customer's last names), after which when the last name is chosen from the list and the submit button is hit the "customer ID" that is related to that last name in the database will be submitted to another PHP file (task8.php) to be sent through further queries. I hope i have explained that all in an understandable manner. I have had a go at some code but i am really unsure on how to do this or if what i have written is on the right path.
Here is what i have written so far:
<body>
<?php
$conn = mysql_connect("localhost", "twa312", "dam6av9a");
mysql_select_db("warehouse312", $conn)
or die ('Database not found ' . mysql_error() );
$sql = "select customerID, lastName from customer";
$rs = mysql_query($sql, $conn)
or die ('Problem with query' . mysql_error());
$options= '<option value="0">Choose</option>';
while ($row=mysql_fetch_array($rs)) {
$id=$row["customerID"];
$name=$row["lastName"];
$options="<OPTION VALUE='" . $id . "'>" . $name ."</option>";
}
?>
<form method="GET" action="task8.php" id="custinfo" >
Choose name:<select name="lname" id="lname"><?php echo $options; ?>
</select>
<p><input type="submit" name="submit" value="Save Data"/> <input type="reset" value="Clear Form" />
</form>
What i am trying to do with the code is access the table "customer" and fields "customerID" and "lastName". Using the customer's last name as the option and the customer's ID as the options value in the selection list. Currently the code displays only a single name as an option in the selection list when it should display all the names in the database. Any help on this would be really great as i am fairly unsure.
There is an error in the code that I can see would cause PHP to generate notice error.
In the while loop you're using .= on the $options variable that isn't yet defined so PHP will barf on that.
Aside from that, it doesn't make sense to me that you're waiting for $_GET['submit'] to be set before iterating over the result set from mysql. As far as I can tell, the first time you'd hit this page there would be a single option in the select ("Choose"), and since the form submits to a different page I don't think you'd ever see a list of customer last names.
Finally, it's not really recommended to name your submit buttons 'submit', since when the page is parsed by the browser all the form elements of a specific form are created as attributes of that form, JS form objects have a 'submit' method so when you name an input 'submit' you clobber that value in the form object which makes it really hard to submit that form with JS.
First off move away from the mysql_functions.
Secondly create a model with all querys related to your customers that will handle fetching/puttin/updating the data related to your customer db.
<?php
Class CustomerModel{
private $db;
function __construct($host,$dbname,$user,$pass){
$this->dbhost = $host;
$this->dbname = $dbname;
$this->dbuser = $user;
$this->dbpass = $pass;
}
private function connect(){
if (!$this->db instanceof PDO){
$this->db = new PDO('mysql:dbname='.$this->dbname.';host='.$this->dbhost, $this->dbuser, $this->dbpass);
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$this->db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
}
}
public function select_all_customer($cols="*"){
$this->connect();
$sql = "SELECT $cols FROM customer";
$statement = $this->db->prepare($sql);
$statement->execute();
return $statement->fetchAll(PDO::FETCH_ASSOC);
}
public function select_customer($cols="*",$where=null, $id=null){
$this->connect();
$sql = "SELECT $cols FROM customer WHERE $where = :id";
$statement = $this->db->prepare($sql);
$statement->bindParam(':id', $id, PDO::PARAM_STR);
$statement->execute();
return $statement->fetchAll(PDO::FETCH_ASSOC);
}
}
?>
Now you can access the model like:
<form method="POST" action="task8.php" id="custinfo" >
Choose name:
<select name="customerID" id="customerID">
<option value="0">Choose</option>
<?php foreach($customer->select_all_customer("customerID, lastName") as $row): ?>
<option value="<?php echo $row['customerID']?>"><?php echo $row['lastName']?></option>
<?php endforeach; ?>
</select>
<p><input type="submit" name="submit" value="Save Data"/> <input type="reset" value="Clear Form" />
</form>
<?php
//Get customer from form values
if($_SERVER['REQUEST_METHOD'] == "POST" && isset($_POST['customerID'])){
$result = $customer->select_customer("*", "customerID", $_POST['customerID']);
//Do something with result
echo '<pre>'.print_r($result, true).'</pre>';
}
?>
Hope it helps

connection table for overcoming the checkbox problem

i have a php form with text box,radiobutton and checkboxes.I have connected it to the databse , the values are getting stored into the database except the checkbox values.I want to enter all the checkbox values into the database.I want an backend such that it links to two tables.the text box and the radio button values are to be stored in the first table and the id's of the selected checkbox values in the other table.
u can store only that value in database which is checked, but you can not store all value of check box with same name attribute, because by checking that checkbox, that value is proceed to next page via POST/GET
but if u want all value of check box ( multiple check box) then use name array like below
<form action="checkbox.php" method="post">
<input type="checkbox" name="checkbox[]" value="a">
<input type="checkbox" name="checkbox[]" value="b">
<input type="checkbox" name="checkbox[]" value="c">
<input type="checkbox" name="checkbox[]" value="d">
<br>
<br>
<input type="submit" name="Submit" value="Submit">
</form>
<?
/* and in your checkbox.php you do this: */
if(isset($_POST['Submit']))
{
for ($i=0; $i<count($_POST['checkbox']);$i++) {
echo "<br />value $i = ".$_POST['checkbox'][$i];
}
}
?>
a connection table can be created (i.e A single php page connection is given to two tables of the same database)the code ia as follows. this code should be given as backend to the php page.
$dbhost = "localhost:3306"; // usually is localhost, but if not sure, check with your hosting company, if you are with webune leave as localhost
$dbuser = "root"; // change to your database password
$dbpass = "mysql"; // change to your database password
$dbname = "probe_config"; // provide your database name
$db_table = "mapping"; // leave this as is
$conn = mysql_connect("$dbhost", "$dbuser", "$dbpass");
$select = mysql_select_db("$dbname");
//selecting the urls
$selected = $_POST['urlSelect'];
if (count($selected) > 0)
{
for ($i=0;$i<count($selected);$i++) {
echo "$selected[$i] <br />";
}
}
$timeout=$_POST['timeout'] ;
$wait=$_POST['wait'];
$clearcache=$_POST['clearcache'];
$name=$_POST['name'];
$replication=$_POST['replication'];
//inserting into the databse
$query = "INSERT INTO webmeasurementsuite (wait, timeout, clearcache, name, replication)
values ($wait, $timeout, '$clearcache', '$name', $replication)";
if (!mysql_query($query,$conn))
{
die('Error: ' . mysql_error());
}
else
{
echo "1 record added to WMS";
$query = "SELECT wms_id FROM webmeasurementsuite ORDER BY wms_id DESC LIMIT 1";
if (!($result=mysql_query($query,$conn)))
{
die('Error: ' . mysql_error());
}
else
{
$row = mysql_fetch_assoc($result);
$id=$row['wms_id'];
$selected = $_POST['urlSelect'];
if (count($selected) > 0)
{
for ($i=0;$i<count($selected);$i++) {
$urlentry=$urlentry.", ";
if($i==0)
{
$urlentry="";
$j++;
}
$urlentry=$urlentry .$selected[$i];
}
}
echo $urlentry;
echo '<br />id='.$id;
//insert for the second table
$query= "INSERT INTO mapping(wms_Id, wm_Id) values ($id, '$urlentry')";
if (!mysql_query($query,$conn))
{
die('Error: ' . mysql_error());
}
else
{
echo "Mapping Done";
}
}
}
mysql_close($conn);
?>

Categories