Creating a Livestock Purchase & Sales App php - php

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'; ?>

Related

Give name to a function in a form

I would like to name the function devtest() in the form as developer so when a user selects the developer it is submitted with the form.
The function I have is this and it is working, it returns the results when you select an item from the dropdown:
function devtest()
{
$db = db();
$stmt = $db->prepare('SELECT developer FROM developers');
$result = $stmt->execute();
?>
<select name="Developer">
<?php
while ($row = $result->fetchArray()) {
$dev = $row['developer'];
echo "<option value='" . $row['developer'] ."'>" . $row['developer'] ."</option>";
}
echo "</select>";
}
on the page itself where I call function and have the form I have
<form method="POST">
Enter game name:
<input type="text" name="name">
<br>
Enter Price
<input type="text" name="price">
<br>
Enter Platform
<input type="text" name="platform">
<br>
Select Developer
<!--<input type="text" name="developer">-->
<?php
devtest();
?>
<br>
Enter quantity
<input type="text" name="quantity">
<br>
Enter shipping
<input type="text" name="shipping">
<br>
<input type="submit" value="save">
</form>
That form goes to this function
function addgame()
{
#$devtest = devtest();
$db = db();
#function to add the form data from the add game page to the database
if(!empty($_POST['name']) && !empty($_POST['price']) && !empty($_POST['platform']) && !empty($_POST['quantity'])&& !empty($_POST['shipping'])){
$name = SQLite3::escapeString($_POST['name']);
$price = SQLite3::escapeString($_POST['price']);
$platform = SQLite3::escapeString($_POST['platform']);
$developer = SQLite3::escapeString($_POST['Developer']);
#$developer = devtest();
$quantity = SQLite3::escapeString($_POST['quantity']);
$shipping = SQLite3::escapeString($_POST['shipping']);
if (strlen($name) < 2)
{
echo("name be 2 char or longer");
}
if (!is_numeric($price))
{
echo("price must be numbers only");
}
if (strlen($platform) < 2)
{
echo("Platform must be 2 char or longer");
}
if (strlen($quantity) < 1)
{
echo("quantity must be more than 1");
}
/*if (strlen($shipping) < 9)
{
echo("shipping must be more than $9");
}*/
else
{
$stmt = $db->prepare("INSERT INTO game (name , price , platform , Developer, quantity, shipping) VALUES ('$name' , '$price' , '$platform' , '$developer', '$quantity' , '$shipping')");
$result = $stmt->execute();
}
}
else
{
echo "Fill in all form fields";
}
}
Without using the devtest() function in the form, and using the everything works fine, I am trying to change it so those on the list can be selected but I am not sure how to pass their select through the form.
you can send data to javascript and write your function in js to add a dropdown every where you need:
...
<script>
var developer = []
</script>
.
.
.
<php>
while ($row = $result->fetchArray()) {
?>
<script>
var developer[]=<?php echo $row['developer']; ?>
</script>
<?php
}
?>
js funtion:
<script>
function devtest(elementID){
developer.forEach(index,item){
$('#'+elementID).append('<select value="'+item+'">'+item+'</select>');
}
}
</script>
}

How to loop through results of a mysql query and display them in option values in an html form

How can I loop through results of a MySQL query and display them in option values in the html form in my script.
I have tried putting the values manually into the option tags and values, but I want to do it depending on whats already inside the database. Do I need another connection to the database to run in the same part as the form element itself?
<title>Add a unit</title>
</head>
<body>
<div class= "container">
<h1>Add a unit</h1>
<?php // Script 12.4 - add_size.php
// This script adds a blog size to the database.
if ($_SERVER['REQUEST_METHOD'] == 'POST') { // Handle the form.
// Connect and select:
$connection = mysqli_connect('localhost', $user, $password, $database);
mysqli_set_charset($connection, 'utf8');
// Validate the form data:
$problem = false;
if (!empty($_POST['unit']) && !empty($_POST['size']) && !empty($_POST['price'] && isset($_POST['building'])) {
$unit = mysqli_real_escape_string($connection, trim(strip_tags($_POST['unit'])));
$size = mysqli_real_escape_string($connection, trim(strip_tags($_POST['size'])));
$price = mysqli_real_escape_string($connection, trim(strip_tags($_POST['price'])));
$building = mysqli_real_escape_string($connection, trim(strip_tags($_POST['building'])));
} else {
echo '<p style="color: red;">Please submit a unit and an size and price.</p>';
}
if (!$problem) {
// Define the query:
$query = "INSERT INTO individualspecs (Space, Size, Price, fk_Id, Id) VALUES ('${unit}', '${size}', '${price}', '${building}', 0)";
// Execute the query:
if (#mysqli_query($connection, $query)) {
echo '<p>The unit has been added!</p>';
// why doesnt print "$msg"; work when using $i
} else {
echo '<p style="color: red;">Could not add the unit because:<br>'.mysqli_error($connection).'.</p><p>The query being run was: '.$query.'</p>';
echo $msg;
}
mysqli_close($connection); // Close the connection.
} // No problem!
} // End of form submission IF.
// Display the form:
?>
<form action="add_units.php" method="post" enctype="multipart/form-data">
<p>Select Building: <select name="building">
<option value="<?php echo ?>"><?php echo ?></option>
<option value=""></option>
<option value=""></option>
<option value=""></option>
</select>
</p>
<p>Enter Unit: <input type="text" name="unit" size="40" maxsize="100"></p>
<p>Enter Size in Sq Feet: <input type="number" name="size" size="40" maxsize="100"></p>
<p>Enter Price: <input type="text" name="price" size="40" maxsize="100"></p>
<!-- removed upload photos -->
<input type="submit" name="submit" value="Add indiviual Space!">
</form>
</div>
</body>
</html>
I would like the select dropdown menu to show a list of all buildings currently in the database so that the user can select a building to add his unit to.
If no buildings exist in database handle situation i.e. echo 'No buildings found in database, you need to
add a building record before attempting to add individual units';
Here is my buildings table:
https://imgur.com/a/2KMOUBD
Here is my units table:
https://imgur.com/a/w24IFuy
Here's a simple code to do what you need
Your code is so messed up, try to clean it :-)
We connect to mysql DB Using PDO class because it's more powerful and secure
you can change root with your db username
pass with your db password
db with your db name
read more about PDO here
// connect to db
$dbh = new \PDO('mysql:host=127.0.0.1;dbname=db', "root", "pass");
// query to select from db
$q = 'SELECT * FROM users';
// prepare and execute the query
$buildsq = $dbh->prepare($q);
$buildsq->execute();
// fetch the results and save them to $build var
$builds = $buildsq->fetchAll();
// check if their is results and print them
if($buildsq->rowCount()) {
foreach ($builds as $build) {
echo '<option value="">' . $build['name'] . '</option>';
}
} else {
echo "<option>No results </option>";
}
It's not the best, but it does what you need.
Try to put connection part in a function to clean up your code.

PHP checklist get ID and value and store it

So I have a form to add a new item to database with a checkbox as follows
So my difficulty is the checkbox. I can easily enough create the array for all items checked but I need an ID for them along with it. I've tried to think of many ways and searched a lot but I just can't think of a way to get the ID in a way that is then useable to me along with the name of the feature (checklist). Since I have to get each feature item and add it to the table houses_has_features.
<?php
$title = 'Add a new house';
require_once 'header.php';
require_once 'nav.php';
require_once 'mysqli-con.php';
$conn = new MYSQLI($hn, $un, $pw, $db);
// If house name and type is set then add them into the database
if( !empty($_POST['h_name']) && !empty($_POST['h_type']) ) {
$house_name = $conn->real_escape_string($_POST['h_name']);
$house_type = $conn->real_escape_string($_POST['h_type']);
//show names added
echo '<b>House name: </b>'.$house_name . '<br><b> House type:</b> ' . $house_type;
$query = "INSERT INTO `house_names` (`id`, `name`) VALUES (NULL, '$house_name')";
$result = $conn->query($query);
if (!$result) die ("<b class='text-danger'><p>Insert failed ERRROR: " . $conn->error. "</p>");
global $house_name_id;
$house_name_id = $conn->insert_id;
$query = "INSERT INTO `house_types` VALUES ('$house_name_id', '$house_type')";
$result = $conn->query($query);
if (!$result) die ("<b class='text-danger'><p>Insert failed ERRROR: " . $conn->error. "</p>");
} else {
global $house_name_id;
$house_name_id= NULL;
}
//Start container for page content
echo '<div class="container">';
//Display an error message if house name is filled in but not house type
if ( !empty($_POST['h_name']) && empty($_POST['h_type']) || empty($_POST['h_name']) && !empty($_POST['h_type']) ) {
echo "<p class='error-text'>* Please fill in both the house name and house type *</p>";
}
$query_feat = $conn->query('SELECT * FROM features');
$rows = $query_feat->num_rows;
$features_list = $_POST['check_list'];
$feature_id = $_POST['feature_id'];
//display checked boxes.
if(isset($_POST['check_list'])) {
for ($i=0; $i<sizeof($features_list); $i++){
//echo '<br>House name id:' . $house_name_id . '<br> $_POST[] = ' . "$features_list[]";
print_r($features_list); echo '<br>';
print_r($feature_id);
}
}
// Add house form
echo <<<_END
<h1>Add a house</h1>
</div>
<div class="container">
<form action="add.php" method="post">
<p>House Name: <input type="text" name="h_name"></p>
<p>House type: <input type="text" name="h_type"></p>
<b>features:</b>
<ul class="list-group">
_END;
for ($c = 0 ; $c < $rows ; ++$c){
$query_feat->data_seek($c);
$feat = $query_feat->fetch_array(MYSQLI_NUM);
echo '<li><input type="checkbox" name="check_list[]" value="' .$feat[1]. '">'.$feat[1].'</li>';
}
echo <<<_END
<ul>
<input class="btn-primary" type="submit" value="Submit">
</form>
</div>
_END;
require_once 'footer.php';
I'm really lost on this one any help would be greatly appreciated :)
change your value of checkbox to id or anything you want.
<li><input type="checkbox" name="check_list[]" value="' .$feat[0]. '">'.$feat[1].'</li>
$feat[1] => $feat[0] or else

Create table dynamically from mysql query

I'm trying to create a page where I input a MYSQL query: SELECT column1,column2 FROM table;, and dynamically create an HTML table with column titles.
EDIT: removed most of my question, just left the question part. I have since created a script that does this and included it as an answer. I hope someone else makes use of it like I do (when I'm too lazy to log into phpmyadmin ... hahaha).
I would try mysql_fetch_assoc which gives back an associative array (map). Then you can use array_keys to get the column names.
This sounds like it might be related to testing where you sometimes just need to spit out the results to see them on a screen , so I'm going to put this here...
The php class dbug is an awesome tool for quickly getting a nicely formatted table out of a php array or even a MySQL result:
http://dbug.ospinto.com/
Well. Here's how I accomplished this, building on webjprgm's tip to use mysql_fetch_assoc:
php code to dynamically create a table with column titles, from PHP to mysql to html! :)
<head>
<title>mysql Table maker</title>
</head>
<body>
<center>
<?php
/* posted data sent to this page (from this page)*/
$pdatabase = htmlentities($_POST['database'], ENT_QUOTES); // database
$phost = htmlentities($_POST['host'], ENT_QUOTES); // host
$puser = htmlentities($_POST['user'], ENT_QUOTES); // user
$ppassword = htmlentities($_POST['password'], ENT_QUOTES); // password
$pcolumns = htmlentities($_POST['columns'], ENT_QUOTES); // comma seperated columns
$columns = explode(",",$pcolumns); // array of column names
$ptable = htmlentities($_POST['table'], ENT_QUOTES); // table
$pwhere = str_replace(array(";",'"'),array('',''),$_POST['where']); // WHERE clause
if (!empty($pwhere)) {$pwhere = "WHERE $pwhere";} // if not empty, prepend with "WHERE"
$porder = htmlentities($_POST['order'], ENT_QUOTES); // ORDER BY clause
$psort = htmlentities($_POST['sort'], ENT_QUOTES); // SORTING (asc or desc)
if (!empty($porder)) {$porder = "ORDER BY $porder $psort";} // if order is not empty, prepend with "ORDER BY"
$pgroup = htmlentities($_POST['group'], ENT_QUOTES); // GROUP BY clause
if (!empty($pgroup)) {$pgroup = "GROUP BY $pgroup";} // if not empty, prepend with "GROUP BY"
$plimit = htmlentities($_POST['limit'], ENT_QUOTES); // LIMIT clause
if (!empty($plimit)) {$plimit = "LIMIT $plimit";}
/* The finished product....or query...so to speak...if you will */
$query = "SELECT $pcolumns FROM $ptable $pwhere $pgroup $porder $plimit";
/* Safety precautions */
$query = str_replace(array("delete","drop","update","alter"),array('','','',''),$query);
// print_r($columns);
?>
<form action="mysql-table.php" method="POST">
<span style="position:fixed;top:0;left:0;width:100%;height:30px;background:#35AFE3">
host: <input name="host" type="text" value="<?php echo $phost;?>"/>
user: <input name="user" type="text" value="<?php echo $puser;?>"/>
password: <input name="password" type="password" value="<?php echo $ppassword;?>"/>
database: <input name="database" type="text" value="<?php echo $pdatabase;?>"/>
</span>
<hr/>
<span style="position:fixed;top:30px;left:0;width:100%;height:205px;background:#35FC39;">
SELECT
<input name="columns" type="text" value="<?php echo $pcolumns;?>"/><br/>
FROM
<input name="table" type="text" value="<?php echo $ptable; ?>"/><br/>
WHERE
<input name="where" type="text" value="<?php echo trim(str_replace("WHERE","",$pwhere)); ?>"/><br/>
ORDER BY
<input name="order" type="text" value="<?php echo trim(str_replace("ORDER BY","",$porder)); ?>"/><br/>
SORT
<select name="sort">
<option value=""></option>
<option value="ASC">ASC</option>
<option value="DESC">DESC</option>
</select><br/>
GROUP BY
<input name="group" type="text" value="<?php echo trim(str_replace("GROUP BY","",$pgroup)); ?>"/><br/>
LIMIT
<input name="limit" type="text" value="100"/><br/>
GO:
<input type="submit" value="submit" />
</span>
</form>
<span style="position:absolute;top:235px;left:0;width:100%;height:auto;background:#28c7d6;z-index:-1;">
<?php
if (!empty($_POST['columns']) && !empty($_POST['table'])) {
echo "<h3><b>Query:</b> <i>$query</i></h3><hr/>";
$mysqli = new mysqli($phost,$puser,$ppassword,$pdatabase); // Connect to DB
/* check connection */ // check for connection error
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if ($result = $mysqli->query($query)) {
echo "<table border='1' style='word-wrap:break-word'>"; // New table
/* Column Title */
echo "<tr>"; // New Row for the titles
foreach($columns as $c) { // For each column, create a column
echo "<td><b>$c</b></td>\r\n";
}
echo "</tr>"; // Close the titles' row
/* DATA RESULTS */
while ($row = $result->fetch_assoc()) { // for each set of rows:
echo "<tr>\r\n\r\n"; // create new row
foreach($columns as $c) { // for each column in the row:
// create a cell
echo "
<td style='max-width:400px;'>
<div style='max-height:300px;overflow-y:auto;'>
$row[$c]
</div>
</td>";
}
echo "</tr>"; // end of that row
} // end foreach results
echo "</table>"; // closing of the table
/* free result set */
$result->free();
} else {
echo "query failed.<hr/>";
}
/* close connection */
$mysqli->close();
} elseif (isset($_POST['columns']) || isset($_POST['table'])) { // end of !empty columns,table
echo "<b>MISSING IMPORTANT INFORMATION.<br/>
For column, you entered: <u> ".$_POST['columns']." </u><br/>
For table you entered: <u> ".$_POST['table']." </u>";
}
?>
</span>
</center>
</body>

php form arrays and sqlite - updated

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>";

Categories