I need some help I am trying to create a PHP form using sqlite3 database. I am looking up values from from an existing sqlite3 database in the "lookuptable" where the column "id = 340" and display those values as a dropdown selection. Then once the value is selected by the user then the form is submitted by the user which updates the new value in the "roster" table with the values from the php form. I get it to display the names in the dropdown but when I click on the update button to submit the data it updates what the value is in the array.
How do I post "firstname" and "lastname" from the user to the roster table instead of of the number on the array table?
PHP entry page Code:
<html>
<head>
<title></title>
</head>
<div class = "controlbox">
<body style="font-size:12;font-family:verdana">
<form action="post.php" method="post">
<p>
<h1> </h1>
<br>
<br>
Person : <select name="name">
<option>--Available Options--</option>
<?php
try
{
$db = new PDO("sqlite:DefaultLibrary.db");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(Exception $e)
{
echo $e->getMessage();
}
$stmt2 = $db->query ("SELECT * FROM lookuptable where ID = '340' ");
$rowarray = $stmt2->fetchall(PDO::FETCH_ASSOC);
$cntr = 0;
foreach($rowarray as $row)
{
echo "<option value = $cntr >$row[FirstName] $row[LastName]</option>";
$cntr++;
}
?>
</select><br>
<p>
<input type="submit" name="update" value="update">
</p>
</form>
</body>
</html>
PHP Code: Post.php
<?php
$name = sqlite_escape_string($_POST['name']);
try
{
$db = new PDO("sqlite:DefaultLibrary.db");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(Exception $e)
{
echo $e->getMessage();
}
if (!empty($person)) {
try
{
$stmt = $db->prepare("UPDATE roster SET rotationplace = :name WHERE ID = '340'");
$stmt->bindParam(':name', $name,PDO::PARAM_STR);
$stmt->execute();
}
catch(Exception $e)
{
echo $e->getMessage();
}
echo "submitted successfully";
}
?>
Try:
echo "<option value = $INSERT_NAME_HERE_NOT_COUNTER >$row[FirstName] $row[LastName]</option>";
Related
I have been working on this problem for the past 3 or 4 hours. I have an SQLite database which interacts with PHP. So far, I have been able to perform 3 of the 4 CRUD operations. The only one which won't work is the the U part (update). I am able to print data into my form, but clicking on the submit button will just make the app hang for some time until I get a custom error message from my app. Also, the record doesn't get updated.
Your help is very much appreciated!
Here is my current code for the edit/update form and page from my app:
<?php
// $db->close();
// echo $_GET['id'];
?>
<!-- get database content -->
<?php
// define PDO - tell about the database file
$db = new PDO("sqlite:database.db");
try {
$sql = "SELECT * FROM students_tb WHERE id=:myId";
// prepare statement
$statement = $db->prepare($sql);
// get value from querystring and bind
$id = filter_input(INPUT_GET, "id");
$statement->bindValue(":myId", $id, PDO::PARAM_INT);
// execute the query
$statement->execute();
// create array of records
$r = $statement->fetch();
$db = null;
// check contents of array
if (!$r) {
echo "No record found";
} else {
echo "record found";
}
}
catch (PDOException $e) {
print "We had an error: " . $e->getMessage() . "<br>";
die();
}
?>
<!-- print database content -->
<?php
// has the form been submitted?
// if not, show the HTML form
if (!isset($_POST['submit'])) {
?>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF'] . "?id=" . $r['id']); ?>" method="post">
<label for="sname">Student's Name</label>
<input type="text" name="sname" required value="<?php echo htmlspecialchars($r['sname']); ?>">
<label for="score">Score</label>
<input type="number" name="score" required value="<?php echo htmlspecialchars($r['score']); ?>">
<button type="submit" name="submit">Submit</button>
</form>
<!-- update database content -->
<?php
} else {
try {
$id = $_POST['id'];
$db = new PDO("sqlite:database.db");
// print out error messages is something goes wrong
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE students_tb SET sname = :sname, score = :score WHERE id = $id";
// UPDATE table_name
// SET column1 = value1, column2 = value2...., columnN = valueN
// WHERE [condition];
$stat = $db->prepare($sql);
// named params
$sname = filter_input(INPUT_POST, "sname");
$stat->bindValue(":sname", $sname, PDO::PARAM_STR);
$score = filter_input(INPUT_POST, "score");
$stat->bindValue(":score", $score, PDO::PARAM_INT);
$success = $stat->execute();
// does the value exist?
if ($success) {
echo "The student has been updated in the database.";
echo "<p><a href='/'>Go back to the main page.</a></p>";
} else {
echo "The student has NOT been updated in the database.";
echo "<p><a href='/'>Go back to the main page.</a></p>";
}
$db = null;
} catch (PDOException $e) {
// for development
print "We had an error: " . $e->getMessage() . "<br>";
die();
}
}
?>
After browsing your source files, it is found that the record will be locked because you are doing the select and then doing the update immediately (which is of course not necessary, in all cases).
Hence, Please use the following code to fix the problem (I have included a hidden field known as actionx to prevent the PHP to do both select and update at the same time) :
So for the edit.php, it should be:
<?php
// $db->close();
// echo $_GET['id'];
?>
<?php if ($_REQUEST["actionx"] =="") { ?>
<!-- get database content -->
<?php
// define PDO - tell about the database file
$db = new PDO("sqlite:database.db");
try {
$sql = "SELECT * FROM students_tb WHERE id=:myId";
// prepare statement
$statement = $db->prepare($sql);
// get value from querystring and bind
$id = filter_input(INPUT_POST, "id");
$statement->bindValue(":myId", $id, PDO::PARAM_INT);
// execute the query
$statement->execute();
// create array of records
$r = $statement->fetch();
$db = null;
// check contents of array
if (!$r) {
echo "No record found";
} else {
echo "record found";
}
}
catch (PDOException $e) {
print "We had an error: " . $e->getMessage() . "<br>";
die();
}
?>
<form action="edit.php" method="post">
<label for="sname">Student's Name</label>
<input type="text" name="sname" required value="<?php echo htmlspecialchars($r['sname']); ?>">
<label for="score">Score</label>
<input type="number" name="score" required value="<?php echo htmlspecialchars($r['score']); ?>">
<input type=hidden name=id value="<?php echo $_REQUEST["id"]; ?>">
<input type=hidden name=actionx value="update">
<button type="submit" name="submit">Submit</button>
</form>
<?php } ?>
<?php if ($_REQUEST["actionx"] !="") { ?>
<?php
try {
$id = $_POST['id'];
$db = new PDO("sqlite:database.db");
// print out error messages is something goes wrong
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE students_tb SET sname = :sname, score = :score WHERE id = :id";
$stat = $db->prepare($sql);
// named params
$sname = filter_input(INPUT_POST, "sname");
$stat->bindValue(":sname", $sname, PDO::PARAM_STR);
$score = filter_input(INPUT_POST, "score");
$stat->bindValue(":score", $score, PDO::PARAM_INT);
$id = filter_input(INPUT_POST, "id");
$stat->bindValue(":id", $id, PDO::PARAM_INT);
$success = $stat->execute();
// does the value exist?
if ($success) {
echo "The student has been updated in the database.";
echo "<p><a href='index.php'>Go back to the main page.</a></p>";
} else {
echo "The student has NOT been updated in the database.";
echo "<p><a href='index.php'>Go back to the main page.</a></p>";
}
$db = null;
} catch (PDOException $e) {
// for development
print "We had an error: " . $e->getMessage() . "<br>";
die();
}
}
?>
On the other hand, for the one.php (displaying a single record), please use this:
<?php
echo $_GET['id'];
?>
<?php
// define PDO - tell about the database file
$db = new PDO("sqlite:database.db");
try {
$sql = "SELECT * FROM students_tb WHERE id=:myId";
// prepare statement
$statement = $db->prepare($sql);
// get value from querystring and bind
$id = filter_input(INPUT_GET, "id");
$statement->bindValue(":myId", $id, PDO::PARAM_INT);
// execute the query
$statement->execute();
// create array of records
$r = $statement->fetch();
$db = null;
// check contents of array
if (!$r) {
echo "No record found";
} else {
echo "record found";
}
}
catch (PDOException $e) {
print "We had an error: " . $e->getMessage() . "<br>";
die();
}
?>
<h1><?php echo htmlspecialchars($r['id']); ?></h1>
<p>Description: <?php echo htmlspecialchars($r['sname']); ?></p>
<p>Score: <?php echo htmlspecialchars($r['score']); ?></p>
<form action="<?php echo 'delete.php?id=' . htmlspecialchars($r['id']) ?>" method="POST">
<button type="submit" name="delete">Delete this record</button>
</form>
<form action="edit.php" method="POST">
<button type="submit" name="delete">Edit this record</button>
<input type=hidden name=id value="<?php echo $r['id']; ?>">
</form>
I got DB with multiple tables like Regions/Countries/States/Etc. And I want to make dropdown lists based on other list selected.
I have tried many things, but nothing seems to work.
This is my latest version :
Core.php :
<html>
<body>
<script type="text/javascript" src="jquery-1.11.0.min.js"></script>
<script type="text/javascript">
function abc(){
var val = document.getElementById('Region_ID').value;
$.post("getSecondDropDown.php",{ Region_ID:val}, function( data ) {
$("#Country_ID").html(data);
});
}
</script>
<form action="/NewService.php" id="ServiceForm" method="post">
Name:<input type="text" name="Service_Name"></br>
Region: <select name="Region_ID" onchange="abc()" form="ServiceForm">
<?php
include('config.php');
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT Region_ID, Region_Name FROM Regions");
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach($stmt as $v) {
echo "<option value='" . $v['Region_ID'] ."'>" . $v['Region_Name'] ."</option>";
}
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
</select></br>
Country: <select name="Country_ID" form="ServiceForm">
</select></br>
<input type="submit">
</form>
</body>
</html>
getSecondDropDown.php :
<?php
$Region_ID =$_POST['Region_ID'];
$option="";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT Country_ID, Country_Name FROM Countries WHERE Region_ID ='$Region_ID'");
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach($stmt as $v) {
echo "<option value='" . $v['Country_ID'] ."'>" . $v['Country_Name'] ."</option>";
}
echo $option;
?>
Image
Here is your problem , you didn't write the id attribute in select tag
<select name="Region_ID" id="Region_ID" onchange="abc()" form="ServiceForm">
<option></option>
</select>
And try in javascript:
<script type="text/javascript">
function abc(){
var e = document.getElementById("Region_ID");
var val = e.options[e.selectedIndex].value;
$.post("getSecondDropDown.php",{ Region_ID:val}, function( data ) {
$("#Country_ID").html(data);
});
}
</script>
I'm currently building an inventory system designed for livestock purchases and sales where a user can input cattle details such as description, color, weight, etc. Using JQuery, a percentage of the weight is subtracted(7%), then the remainder is multiplied by the price and the total cost is saved to the database along with all the other input data. The results are then displayed to another page where they can be seen and sold from.
I added new input boxes to the sale page with new weight, new price and new total cost. The new weight is to follow the same formula (-7%), multiply by new price and store these new items into the same row/record in database and redirect to a page where all data (including new weight/new price/new total can be seen). I am using UPDATE with PDO and I am not getting any errors but new data is not being recorded.
Can/Should I include a form in echo?
How to submit that form, given that I have to use $row. id in the submit/href field?
If I can achieve this, the next step is to add a #profit readonly input below new total input that would subtract old cost from new cost. Is this possible with JQuery?
Purchase page, Sell page, Update page and JQuery code below in that order.
Edit***
I have added the result.php page at the very bottom.
The question would be, is placing input fields inside a php echo correct?
Or how would I add new data to that auto-generated row that has to be selected by id?
Last question, would the last piece in JQuery work? I don't know how JQuery would retrieve the old cost in the same row.
Thank you.
<?php include 'includes/header.html' ; ?>
<body>
<form action="result.php" method="POST">
<label for="desc">Description</label>
<input type="text" id="desc" name="desc" placeholder="No horns, mad cow, Herford, etc.." required>
<label for="desc">Color</label>
<input type="text" id="color" name="color" placeholder="Gray, red, black & white, etc.." >
<label for="desc">Weight</label>
<span><input type="number" id="kg" name="kg" placeholder="345kg, 455kg, 660kg, etc.." required>kg</span>
<label for="desc">Price p/kg</label>
<span>$<input type="number" id="precio" name="precio" placeholder="$12.50, $22, $30, etc.." required></span>
<label for="desc">Ear Tag</label>
<input type="text" id="arete" name="arete" placeholder="00453E, 2111RG, etc.." >
<br/><br/>
<label for="costo">Total Cost</label>
<input type="number" name="costo" id="costo" readonly />
<br/><br/>
<input type="submit" id="comprar" name="submit" value="Make purchase">
</form>
</body>
Sell page below
<?php include 'includes/header.html'; ?>
<?php require_once ('db/conn.php');
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
}catch(PDOException $e) {
die('Error');
}
$tableheader = false;
$query = "SELECT * FROM `compras` ORDER BY `id` ASC";
$sth = $conn->prepare($query);
if(!$sth->execute()) {
die('Error');
}
echo "<h1 id='title'>Cattle</h1><table>";
while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
if($tableheader == false) {
echo '<tr>';
foreach($row as $key=>$value) {
echo "<th id='valor'>{$key}</th>";
}
echo '</tr>';
$tableheader = true;
}
echo "<tr>";
foreach($row as $value) {
echo "<td id='valor'>{$value}</td>";
}
/* Add Delete Button with css id to target with CSS and Query */
/*echo "<td><button id='boton1'>Vender</button></td>" * Initial button for Vender */
echo "<td>
<label>New Weight</label>
<input type='number' name='npeso' id='npeso' placeholder='new weight'>
<label>New Price p/kg</label>
<input type='number' name='nprecio' id='nprecio' placeholder='new price'>
<label>Total Sell Price</label>
<input type='number' name='ncosto' id='costo' readonly />
</td>";
echo "<td id='vender1'>
<button id='boton1'>
<a href='update.php?id=" . $row["id"] . "'>Sell</a>
</button>
</td>";
echo "</tr>";
}
echo "</table><br/>";
?>
<?php include 'includes/footer.html'; ?>
Update Page
<?php require_once ('db/conn.php');
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$id = (int)$_GET['id'];
$sqlu = " UPDATE `compras` SET `npeso`= '$npeso', `nprecio`= '$nprecio', `ncosto`= '$ncosto' WHERE id=" . $id;
// use exec() because no results are returned
$conn->exec($sqlu);
header( "Location: exito.php" );
/*echo "New record created successfully";*/
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
JQuery
$(document).ready(function(){
/* Space for Declaring Global Variables and creating total profit calculation*/
costo1 = parseFloat('#costo').val() || 0;
costo2 = parseFloat('#ncosto').val() || 0;
/* JQuery for Cattle price calculation on comprar.php page */
$('#kg, #precio').keyup(function(){
var peso = parseFloat($('#kg').val()) || 0;
var precio = parseFloat($('#precio').val()) || 0;
var deweyo = (peso * .07);
var neto = (peso - deweyo);
$('#costo').val( neto * precio);
});
/* JQuery for Cattle price calculation on modal */
$('#npeso, #nprecio').keyup(function(){
var peso = parseFloat($('#npeso').val()) || 0;
var precio = parseFloat($('#nprecio').val()) || 0;
var deweyo = (peso * .07);
var neto = (peso - deweyo);
var costo2 = parseFloat($('#ncosto').val()) || 0;
$('#ncosto').val( neto * precio);
});
/* Calculation for total profit */
$(costo2, costo1).keyup(function(){
$('#profit').val(costo2 - costo1);
});
});
Result.php
<?php include 'includes/header.html'; ?>
<?php require_once ('db/conn.php');
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO `compras` (`descri`, `color`,`peso`, `precio`,`arete`, `costo`)
VALUES ('$description', '$color', '$kg', '$precio', '$arete', '$costo')";
// use exec() because no results are returned
$conn->exec($sql);
header( "Location: success.php" );
/*echo "New record created successfully";*/
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
<?php include 'includes/footer.html'; ?>
I have built a system where I can create a category and a document. the categories live in the cat_list table and the documents live in the doc_list table. there is a column in the doc_list table called cat_no which takes an array or the categories that belong to that doc.
newfile.php
<?php
require_once '../../db_con.php';
try{
// Selecting entire row from cat_list table
$results = $dbh->query("SELECT * FROM cat_list");
}catch(Exception $e) {
echo $e->getMessage();
die();
}
$cat = $results->fetchAll(PDO::FETCH_ASSOC);
?>
<form action="actions/newDocAdd.php" method="post" id="rtf" name="">
<input type="text" name="doc_title" id="doc_title" required="required" placeholder="Document Title"/><br />
<?php
foreach($cat as $cat){
echo
'<input type="checkbox" value="" name=""> ' .$cat["cat_title"]. '</a><br>';
}
?>
<br><br>
<textarea name="doc_content" id="doc_content" placeholder="Document Content" style="display: none;"></textarea>
<iframe name="editor" id="editor" style="width:100%; height: 600px;"></iframe>
<br><br>
<input onclick="formsubmit()" type="submit" value="Create Document" name="submit"/>
</form>
I have cut alot out of the form because there is alot of JS because it is a WYSIWYG creator hence the iframe. But the key area is where I lsit out categories above as checkboxes, I need to allow for that to then post a number (or array of numbers if more than one is clicked) into the col_no column in the doc)list table.
Here is the script which posts the data:
<?
session_start();
session_regenerate_id();
if(!isset($_SESSION['user'])){
header("Location: ../index.php");
exit;
}
if(isset($_POST["submit"])){
include_once'../../config.php';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=dashboardr",$username,$password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
$sql = "INSERT INTO doc_list (doc_title, doc_content, doc_created, user_id) VALUES ('".$_POST["doc_title"]."','".$_POST["doc_content"]."', NOW(), '".$_SESSION['user']."''".$_POST['cat_no']."' )";
print_r($_POST);
if ($dbh->query($sql)) {
header ('Location: ../docList.php?success=1');
}
else{
}
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
?>
UPDATE
<?php
foreach($cat as $cat){
echo
'<input type="checkbox" value="$cat["cat_id"]" name="cat_no"> ' .$cat["cat_title"]. '</a><br>';
}
?>
So I can get it to post in a value of "0" but I need it to be an array of the ID's of which I am posting, what is it I am doing wrong here?
Hello im trying to delete which ever value is selected in a drop down list.
I cant seem to understand what is going on
I have 2 pages 1 with my connection and functions to view the table in a drop down (which works) and a delete function (which doesn't seem to work) and another to call the function in and to delete which ever value is selected.
connection.php
<?php
//Connect to the database
function getSQLConnection() {
$mysqlConnection = new PDO('mysql:host=localhost;dbname=isad235_100000', "root", "");
return $mysqlConnection;
}
//Get all results from members table
function getResults($tablename) {
$sql = "SELECT * FROM " . $tablename;
$mysqlConnection = getSQLConnection();
$ResultSet = $mysqlConnection->query($sql);
return $ResultSet;
}
//Delete results from members table
function deleteValue($id) {
$sql = "DELETE FROM members WHERE member_id = '$id'";
$mysqlConnection = getSQLConnection();
$ResultSetting = $mysqlConnection->query($sql);
return $ResultSetting;
}
?>
delete.php
<?php
include_once 'connection.php';
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Add</title>
</head>
<body>
<h1> Delete a Member from the Members Table. </h1>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method='post'>
Delete Member:
<select name='members' value='members'id="Mmembers">
<?php
$results = getResults('members');
if ($results) {
foreach ($results as $row) {
echo '<option value="' . $row['member_id'] . '">' . $row['name'] . '</option>';
}
}
else
echo '<option value="0"0"> No Data</option>';
?>
</select>
<input type="submit" id="delete" value="Delete"/>
<br/>
<br/>
</form>
<?php
if (isset($_POST['members'])) {
$ResultSetting = deleteValue(($_POST['members']));
}
?>
<br/>
<br/>
<form action='index.php' method='GET'>
Go Back:
<input type="submit" name="submit" value="Return"/>
</form>
<br/>
</body>
</html>
I ran your code and don't see any errors with it. Make sure the id column on your 'members' table is called 'member_id'. If there is a discrepancy in the name then the values for the option elements wouldn't be set. Also, the value you just deleted would still appear after the initial page submit. If you reload the page after the submit, you'll see the value has disappeared.