Linking data within MySQL tables into 1 table with PHP Code - php

Background info:
I am trying to create a digital job raising system. Admin raises a job sheet and pulls in a client from "tblclient" table, fills out the details of the job and then assigns the job sheet to a employee user.
With this being said I am having difficulty pulling data from the clients table and users table then linking them to a row in the jobs table. I am new to PHP coding and am unsure how to script it out so my user can select the client and all the client details are attached to the job sheet and then coding it so the job sheet can be moved around between users.
This is so that when the job is complete the Admin can preview the job sheet with all the client details on it, job details and print with all the information on screen.
Is there any tutorials I can use for this procedure?
Notes:
I currently have a form that will insert the job data into the job table, I just don't know what code to use to pull in users/clients and link it to that specific job.
Thanks
<?php
include 'core/init.php';
include 'include/overall/overall_header.php';
protect_page();
admin_protect();
$today_date = date("Y-m-d");
?>
<div id="container">
<div id="content-container">
<div id="sidenav">
<?php include 'include/sidenav.php'; ?>
</div>
<div id="content">
<h1>Add a new job</h1>
<?php echo $today_date; ?>
<?php
if (isset($_GET['success']) && empty($_GET['success'])) {
echo 'Job added successfully!';
} else {
if (empty($_POST) === false && empty($errors) === true) {
$job_data = array(
'date' => $_POST['date'],
'description' => $_POST['description'],
'artworkbrief' => $_POST['artworkbrief'],
'extracosts' => $_POST['extracosts'],
'stock1' => $_POST['stock1'],
'orderno1' => $_POST['orderno1'],
'ordered1' => $_POST['ordered1'],
'stock2' => $_POST['stock2'],
'orderno2' => $_POST['orderno2'],
'ordered2' => $_POST['ordered2'],
'stock3' => $_POST['stock3'],
'orderno3' => $_POST['orderno3'],
'ordered3' => $_POST['ordered3'],
'subtotal' => $_POST['subtotal'],
'extracosts1' => $_POST['extracosts1'],
'total' => $_POST['total']
);
raise_job($job_data);
header('Location: raise_job.php');
exit();
}
}
?>
<select id="clientname" name="clientname">
<?php
$pdo = new PDO('mysql:host=localhost;dbname=formation_ims', 'root', 'form8tion');
#Set Error Mode to ERRMODE_EXCEPTION.
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare('Select clientname from tblclients');
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo '<option>'.$row['clientname'].'</option>';
}
?>
</select>
<div id="job-sheet">
<form action="" method="post">
<div class="row-3">
<div class="description">
<p>Description:</p>
<textarea type="text" name="description"></textarea>
</div>
</div>
<div class="row-4">
<div class="artwork-brief">
<p>Artwork Brief:</p>
<textarea type="text" name="artworkbrief"></textarea>
</div>
</div>
<div class="row-5">
<div class="extra-costs-container">
<div class="extra-costs">
<p>Extra Costs:</p>
<textarea type="text" name="extracosts"></textarea>
</div>
</div>
<div class="total-container">
<div class="sub-total">
Sub Total:
<input type="text" name="subtotal">
</div>
</div>
<div class="extra-num-container">
<div class="extra-costs-num">
Extra Costs:
<input type="text" name="extracosts1">
</div>
</div>
</div>
<div class="row-6">
<div class="stock-material-container">
<div class="stock-material">
<p>Stock/Material:</p>
<div class="stock-material-row">
<div class="stock-material-col01">
<input type="text" name="stock1">
</div>
<div class="stock-material-col02">
Order No.<input type="text" name="orderno1">
</div>
<div class="stock-material-col03">
Ordered:<input type="checkbox" name="ordered1">
</div>
</div>
<div class="stock-material-row">
<div class="stock-material-col01">
<input type="text" name="stock2">
</div>
<div class="stock-material-col02">
Order No.<input type="text" name="orderno2">
</div>
<div class="stock-material-col03">
Ordered:<input type="checkbox" name="ordered2">
</div>
</div>
<div class="stock-material-row">
<div class="stock-material-col01">
<input type="text" name="stock3">
</div>
<div class="stock-material-col02">
Order No.<input type="text" name="orderno3">
</div>
<div class="stock-material-col03">
Ordered:<input type="checkbox" name="ordered3">
</div>
</div>
</div>
</div>
<div class="total-container">
<div class="sub-total">
Sub Total:
<input type="text" name="subtotal">
</div>
</div>
<div class="extra-num-container">
<div class="extra-costs-num">
Extra Costs:
<input type="text" name="extracosts1">
</div>
</div>
</div>
</div>
<input type="submit" value="Submit">
</form>
</div>
</div>
<div class="clear"></div>
<?php include 'include/overall/overall_footer.php'; ?>
ahh yes, I understand what this code is doing but not familiar with the syntax. I got an error:
Parse error: syntax error, unexpected ';' in...
I think you left out an ")" but even after reinstating it, my dropdown menu isn't populated:
<select name='clientid'>
<?php
$query="SELECT * FROM tblclients";
$result=mysql_query($query) or die(mysql_error());
while($row=mysql_fetch_assoc($result)){
echo "<option value='".$row['Client_ID']."'>".stripslashes($row['ClientName']." </option>";
}
?>
`

When inputting your job, you will want a field in your form containing clientid and another containing userid. The following is an example of how that might be done.
<select name='clientid'>
<?php
$query="SELECT * FROM ClientTable";
$result=mysql_query($query) or die(mysql_error());
while($row=mysql_fetch_assoc($result)){
echo "<option value='".$row['ClientID']."'>".stripslashes($row['ClientName']."</option>";
}
?>
</select>
Then when you want to output the job with all it's information, when you run the query you should use the LEFT JOIN command, for example
$query="SELECT * FROM JobTable
LEFT JOIN UserTable ON UserTable.UserID=JobTable.UserID
LEFT JOIN ClientTable ON ClientTable.ClientID=JobTable.ClientID
WHERE JobID='".mysql_real_escape_string($jobid)."'";
$result=mysql_query($query) or die(mysql_error());
That grabs the appropriate client and user informations by their IDs (which I hope you've set up with auto-increment by the way)

Related

Display inline arrays

var html3 = '<div class="row" id="parent-autor"> <p id="auth-del"><i class="fa fa-minus-square" aria-hidden="true"></i></p> <div class="col-md-4"> <div class="form-group"> <input type="text" class="form-control" name="altautorprenume[]" placeholder="Prename"> </div> </div> <div class="col-md-4"> <div class="form-group"> <input type="text" class="form-control" name="altautornume[]" placeholder="Name"> </div> </div><div class="col-md-4"> <div class="form-group"> <input type="text" class="form-control" name="institutie[]" id="institutie" placeholder="Institutions"> </div> </div></div>';
$("#add_aut").click(function(e){
$('#auth-rows').append(html3);
});
$('#auth-rows').on('click', '#auth-del', function(E){
$(this).parent('div').remove();
});
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
<div class="add-plus"></div>
<div class="col-md-12">
<h5>Add more persons </h5>
<span class="btn btn-primary" id="add_aut" style="">Click here to add</span>
</div>
</div>
<div id="auth-rows"></div>
i have an formular which user can add more clients to invite at party when user click on Add a new row with 3 fields appear he can add how many he want,
these values dynamically i want to show on email, for example:
User fill all fields and add 3 more users where they have Name PreName Instituional,look what i did:
$personName= $_POST['personname'];
$personPrename= $_POST['personprename'];
$institution= $_POST['institution'];
$otherPersonName=" ";
$otherPersonPreName="";
$otherPersonInstitution= "";
foreach($personName as $product) {
$otherPersonPreName.= "$product";
}
foreach($personPrename as $products) {
$altiautoriNume .= "$products";
}
foreach($institution as $productss) {
$otherPersonInstitution.= "$productss";
}
EXAMPLE:
And in email content i want to display like this:
<hr>
John(first name of person added) Doe(first Prename of person added) Microsoft(first Institution of person added)
<hr>
Mike(second name of person added) Stuart(second Prename of person added) Facebook(second Institution of person added)
<hr>
I know i did something wrong.
I put even html to see truly what i want to do, i want to group Name Prename Institution per line
You can use array-map with null as first parameter to group the array and then use implode to concat the strings.
Consider the following:
$arr = array_map(null, $personName, $personPrename, $institution);
foreach($arr as $e)
echo implode(" ", $e) . PHP_EOL;
Live example: 3v4l

Insert query not inserting in database

So I'm trying to insert some text into a already existing table. If I insert the text into the text field and press submit, I'll get a var_dump on a other page that shows the information that I want to insert but it doesnt send it to the database or something. I hope you can help me with what I'm doing wrong.
This is my insert query
public function insertComment($commentaar, $idBestelling){
try{
$stmt = $this->_db->prepare('UPDATE `apotheek`.`Bestelling` SET `commentaar` = :commentaar WHERE `Bestelling`.`idBestelling` = :idBestelling;');
if($stmt->execute(array(
':commentaar' => $commentaar,
':idBestelling' => $idBestelling))){
return true;
} else {
return false;
}
} catch(PDOException $e) {
echo '<p class="bg-danger">'.$e->getMessage().'</p>';
}
}
And here you can find the code from the webpage.
<div class="row">
<form role="form" method="post" action="/?content=bezorgen">
<div class="col-xs-12 col-sm-12 col-md-12 loginborder">
<h2 class="loginhead">Bestelling no. <?php print($data['idBestelling']); ?> <?php ($data['isSpoed'] == '0') ? print('') : print('deze bestelling is met SPOED') ?></h2>
<hr>
<div class="row col-6 col-md-6 col-sm-12 col-xs-12">
<div class="loginhead">
<h3>Commentaar</h3>
<hr>
</div>
<div>
<textarea rows="9" cols="74" name="commentaar"><?php print($data['commentaar']); ?></textarea>
</div>
</div>
<div class="row registerbtn">
<div class="col-xs-12 col-md-12" style="text-align:right;"><input type="submit" name="submit" value="Verstuur" class="btn btn-lg" tabindex="5"></div>
</div>
</div>
</form>
And the php
$data = $user->getBestellingPatient($_POST['idBestelling']);
if(isset($_POST['submit'])){
$user->insertComment($_POST['commentaar'], $_POST['idBestelling']);
};
I think you are trying to update a comment which is already exist in the database.
You should add a hidden field in the form to hold the id of the the post (Mostly auto incremented id from DB)
Add the below element below your textarea element
<input type='hidden' name='idBestelling'<?php print($data['idBestelling']); ?>/>
So when you are updating id will be passed as a part of the form then you can receive it usinig $_POST
you should try this:
$stmt = $this->_db->query('UPDATE `apotheek`.`Bestelling` SET `commentaar` = :commentaar WHERE `Bestelling`.`idBestelling` = :idBestelling;');

Button form submission not submitting NULL

I am working with a fairly straight forward form yet for some reason it is not submitting NULL results and instead submits them as empty results.
<div class="span6">
<form action="" method="POST">
<div class="block-fluid without-head">
<div class="toolbar clearfix">
<div class="right">
<div class="btn-group">
<button type="submit" class="btn btn-small btn-warning tip" data-original-title="Submit Aritcle">
<span class="icon-ok icon-white"></span>
</button>
<button type="button" class="btn btn-small btn-danger tip" data-original-title="Delete Article">
<span class="icon-remove icon-white"></span>
</button>
</div>
</div>
<div class="left">
<div style="font-size: 11pt; font-family: -webkit-body; font-weight: bolder;">Article Exchange Request</div>
</div>
</div>
<div class="row-form clearfix">
<div class="span3">Title</div>
<div class="span9"><input type="text" name="title" value="" placeholder="main subject title"></div>
</div>
<div class="row-form clearfix">
<div class="span3">First Sentence</div>
<div class="span9"><input type="text" name="s1" value="" placeholder="Sentence with max of 200 characters"></div>
</div>
<div class="row-form clearfix">
<div class="span3">Second Sentence</div>
<div class="span9"><input type="text" name="s2" value="" placeholder="Optional sentence with max of 200 characters"></div>
</div>
<div class="row-form clearfix">
<div class="span3">Third Sentence</div>
<div class="span9"><input type="text" name="s3" value="" placeholder="Optional Sentence with max of 200 characters"></div>
</div>
<div class="row-form clearfix">
<div class="span3">Website Url</div>
<div class="span9"><input type="text" name="link" value="" placeholder="Url to be included in articles"></div>
</div>
<div class="row-form clearfix">
<div class="span3">Website Url Title</div>
<div class="span9"><input type="text" name="link_text" value="" placeholder="Url text to be included in articles limit 150 characters"></div>
</div>
<div class="row-form clearfix">
<div class="span3">Credit Offer</div>
<div class="span9"><input type="text" name="cost_value" value="" placeholder="Example: 100"></div>
</div>
</div>
</form>
</div>
The problem is someone can just come along and submit the form without entering any data at all, and it still submits, and adds empty results to every column in the database. Meaning no NULL values are being set in the database.
My form processing
<?
if (isset($_POST[cost_value])) {
$stmt = $db->prepare("SELECT credits from member_credits WHERE username = :username");
$stmt->bindParam(':username', $username);
$stmt->execute();
$row = $stmt->fetch();
$count = $row[credits];
if ($count > $_POST[cost_value]) {
$stmt = $db->prepare('INSERT INTO article_requests (title, s1, s2, s3, link, link_text, offer, username) VALUES (:title, :s1, :s2, :s3, :link, :link_text, :offer, :username)');
$stmt->bindValue(':title', $_POST[title]);
$stmt->bindValue(':s1', $_POST[s1]);
$stmt->bindValue(':s2', $_POST[s2]);
$stmt->bindValue(':s3', $_POST[s3]);
$stmt->bindValue(':link', $_POST[link]);
$stmt->bindValue(':link_text', $_POST[link_text]);
$stmt->bindValue(':offer', $_POST[cost_value]);
$stmt->bindValue(':username', $username);
$stmt->execute();
}
}
?>
What I expect to happen on submission is if no value is entered in the form it should be set to NULL... that would mean if no $_POST[cost_value] was set, the form wouldn't submit. As it stands now, it is ALWAYS seeing $_POST[cost_value] as being set - sometimes to a value such as $_POST[cost_value] = '100'; and other times $_POST[cost_value] = ''; but in both cases, the form will submit. Equally I have the database set so that only the values of s2 and s3 should be able to be null, however when everything is submitting empty instead of null, thats mostly useless.
What exactly am I missing? Why will it not say $_POST[cost_value] = NULL; if the user has not input a value? Why is it submitting ''?? I have a feeling its going to be something basic I am overlooking, I just don't see it....
UPDATE FOR CLARITY
I know there are a number of ways to fix this. I can use if then tests, I can use temporary variables, I can check for the value itself is something other than ''. I know WHAT the work arounds are. I don't understand WHY they are needed. Why is it I make forms every day of the week using if isset, and everyday that works. If a form has no values input from the user, the form won't submit because an if isset returns false. So why is it on this particular form it is submitting '' instead of saying !isset don't process.
// Assign a var to the post.
$DIRTY_Var = $_POST['varinputname'];
// ensure the var is cleaned (no funny business when submitting)
$CLEAN_Var = filter_var($DIRTY_Var,` FILTER_SANITIZE_STRING);
// check if the var is empty, or has value. If empty it will set the var to null;
if (!$CLEAN_Var) { return $CLEAN_Var = null; }
// validate input
$valid = true;
// insert data
if ($valid) {
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO Table ("
."ColumnNames"
.")"
."VALUES("
."?"
.")";
$q = $pdo->prepare($sql);
$q->execute(array($CLEAN_Var));
// Once INSERT is completed, we will redirect.
header("Location:" 'link.php'); exit;
}
Try
If(isset($_POST['cost_value']) && !empty($_POST['cost_value']){
// your code
}

Associate a text field with a primary key in a row using codeigniter

I am trying to build a bidding application. I want to a associate a textfield with the primary key of the row outputted. e.g textfield is bid_amount.
When entering the bid amount I want the bid_amount entered and the person who bid (truckerid) and the product bid on (luggage_id) to be stored in a bids table.
The outputted products to bid for are stored in another table (consignment table) Below is my model, view and controller.
View
<h2 class="page-header">
<i class="fa fa-legal"></i> &nbsp <font color="orange"> Loads To Bid For </font>
</h2>
</div><!-- /.col -->
</div>
<?php
foreach ($h->result() as $row) {}
?>
<div class="row invoice-info">
<div class="col-sm-1 invoice-col">
</div>
<div class="col-sm-3 invoice-col">
<img src="<?php echo base_url()?>/res/images/goods/1.png">
</div>
<div class="col-sm-4 invoice-col">
<address>
Description: <?php echo $row->description;?><br>
Location Address: <?php echo $row->l_area;?><br>
Destination Address: <?php echo $row->d_area;?><br>
Date: <?php echo $row->dom;?><br>
Time: <?php echo $row->tom;?>
</address>
</div>
<div class="col-sm-2 invoice-col">
<address>
</address>
</div><!-- /.col -->
<div class="col-sm-2 invoice-col">
<?php echo form_open('truckeraccount_ctrl/bid'); ?>
<input type="hidden" class="form-control" name="truckerid" value="<?php
$truckerid = $this->session->userdata('truckerid');
echo $truckerid; ?>" required>
<input type="text" class="form-control" name="bid_amount[$row->luggage_id]" placeholder="Bid">
<button type="submit" class="btn bg-orange btn-flat margin">Place Bid</button>
</div>
</div>
Controller
public function bid() {
$this->load->model('Truckeraccount_model');
// $luggage_id = $this->uri->segment(3);
$this->Truckeraccount_model->bid();
redirect('truckeraccount_ctrl');
}
Model
function bid() {
$data = array(
'luggage_id' => $this->input->post('luggage_id'),
'bid_amount' => $this->input->post('bid_amount'),
'truckerid' => $this->input->post('truckerid')
);
//$this->db->where('luggage_id', $luggage_id);
$query=$this->db->update('bids', $data);
return $query;
}
You can use the input as an associative array by changing the name. This will make the keys in the array the product ids
try
<input type="text" name="bidAmount[$row->productId]" />
then in your PHP you can loop through the values
foreach ($_POST['bidAmount'] as $productId => $bidAmount) {
// do your logic here
}
You can use hidden text box to get bid.
<?php
foreach ($products->result() as $row)
{ ?>
<?php echo $row->price;?>
<input type="hidden" name="bid[]" value="<?php echo $row->bid;?>">
<input type="text" name="bidAmount[]" placeholder="place bid amount">
<?php } ?>
Now bid and bidAmount both will have same counts of array. So that use for loop to get bid value and bidAmount value.
for ($i=0; $i < count($_POST['bid']); $i++) {
$bid = $_POST['bid'][$i]; \\ You can get bid value here
$bidAmount = $_POST['bidAmount'][$i]; \\ You can get bid amount value here
}
Hope this answer will be helpful. If it is correct then don't forget to mark as correct answer. Cheers.

Placing a bid inside a bids table using codeigniter

I am trying to build a bidding application. I want to a associate a textfield with the primary key of the row outputted. e.g textfield is bid_amount . when you enter the bid amount i want the bid_amount entered and the person who bidded(truckerid) and the product bidded for (luggage_id) to be stored in bids table . the outputted products to bid for are stored in another table (consignment table) Below is my model, view and controller.
Below are the errors that am getting
A Database Error Occurred
Error Number: 1054
Unknown column 'Array' in 'field list'
UPDATE `bids` SET `luggage_id` = NULL, `bid_amount` = Array, `truckerid` = '84K7B7'
Filename: models/Truckeraccount_model.php
Line Number: 129
A PHP Error was encountered
Severity: Notice
Message: Array to string conversion
Filename: database/DB_driver.php
Line Number: 1524
Below is my model, view and controller.
View
<h2 class="page-header">
<i class="fa fa-legal"></i> &nbsp <font color="orange"> Loads To Bid For </font>
</h2>
</div><!-- /.col -->
</div>
<?php
foreach ($h->result() as $row)
{
?>
<div class="row invoice-info">
<div class="col-sm-1 invoice-col">
</div>
<div class="col-sm-3 invoice-col">
<img src="<?php echo base_url()?>/res/images/goods/1.png">
</div>
<div class="col-sm-4 invoice-col">
<address>
Description: <?php echo $row->description;?><br>
Location Address: <?php echo $row->l_area;?><br>
Destination Address: <?php echo $row->d_area;?><br>
Date: <?php echo $row->dom;?><br>
Time: <?php echo $row->tom;?>
</address>
</div>
<div class="col-sm-2 invoice-col">
<address>
</address>
</div><!-- /.col -->
<div class="col-sm-2 invoice-col">
<?php echo form_open('truckeraccount_ctrl/bid'); ?>
<input type="hidden" class="form-control" name="truckerid" value="<?php
$truckerid = $this->session->userdata('truckerid');
echo $truckerid; ?>" required>
<input type="text" class="form-control" name="bid_amount[$row->luggage_id]" placeholder="Bid">
<button type="submit" class="btn bg-orange btn-flat margin">Place Bid</button>
</div>
</div>
Controller
public function bid(){
$this->load->model('Truckeraccount_model');
// $luggage_id = $this->uri->segment(3);
$this->Truckeraccount_model->bid();
redirect('truckeraccount_ctrl');
}
Model
function bid(){
$data = array(
'luggage_id' => $this->input->post('luggage_id'),
'bid_amount' => $this->input->post('bid_amount'),
'truckerid' => $this->input->post('truckerid')
);
//$this->db->where('luggage_id', $luggage_id);
$query=$this->db->update('bids', $data);
return $query;
}
The error is in this bid_amount[$row->luggage_id] section in the form. You can not put a third bracket in field name, if it is written it will be treated as an array.

Categories