Insert query not inserting in database - php

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

Related

Why can't I show all the posted newsfeeds of the user? [duplicate]

This question already has an answer here:
PDO Return All Rows [duplicate]
(1 answer)
Closed 3 years ago.
I have a cooperative(user) that can post many newsfeeds, so a one is to many relationship. My goal is to show all the newsfeeds of the cooperative in a list and use that list to link each newsfeeds to an update and delete page. However my code is only showing the first newsfeed and since I put it inside a loop, the first newsfeed is being loop six times. Why is that?
Im using the $loggerUser['coopID'] to get the coopID that is supplied to the where clause of the viewCoopNewsfeed function.
this is my sql command
function viewCoopNewsfeed($coopID)
{
try {
$connection = connect();
$statement = $connection->prepare("SELECT * FROM newsfeed WHERE
coopID = :coopID");
$statement->bindParam(":coopID", $coopID);
$statement->execute();
$statement->setFetchMode(PDO::FETCH_ASSOC);
if ($coopNewsfeed = $statement->fetch()) {
return $coopNewsfeed;
} else {
return NULL;
}
} catch (PDOException $exception) {
die("Error: " . $exception->getMessage());
}
}
and this is the loop in the view
<?php
if(!empty($coopNewsfeeds))
{
foreach($coopNewsfeeds as $coopNewsfeed)
{
?>
<form method="post" enctype="multipart/form-data">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Photo</label>
<img class="profile-pic" src="<?=$coopNewsfeeds['photo']?>"/>
</div>
</div>
<br><br><br><br><br><br><br><br><br><br>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Title</label>
<input type="text" class="form-control" placeholder="Title" name="title" value="<?=$coopNewsfeeds['title']?>" required>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>Body</label>
<textarea class="form-control" name="Body" value="<?=$coopNewsfeeds['Body']?>" placeholder="Body" id="" cols="30" rows="2"></textarea>
</div>
</div>
</form>
<?php
}
?>
<?php
}
?>
$coopNewsfeed = $statement->fetch() this fetches the next result (the first one in your case, because you executed fetch() only once). Since you are returning $coopNewsfeed immediatly after this statement, you are getting only 1 row.
Use fetchAll() instead.
if ($coopNewsfeed = $statement->fetchAll()) {
return $coopNewsfeed; // this now returns all results in a 2d array
} else {
return NULL;
}
And then, in your view :
foreach($coopNewsfeeds as $coopNewsfeed)
{
// some html
// notice the variable name -----v-----------v
<img class="profile-pic" src="<?=$coopNewsfeed['photo']?>"/>
// more html and stuff
}

Insert null or something if value of csv is null

I have a problem uploading a csv to mysql.
I have the following csv.
I need to upload the marked fields the max fields the csv can contain are 48 but some csv contain only 36 or less. I have a form which if csv contains 48 cells uploads succesfully to mysql but if the csv is less than 48 I got error.
This is my form:
<div class="container">
<?php
if(isset($_POST['uploadBtn'])){
$fileName=$_FILES['myFile']['name'];
$fileTmpName=$_FILES['myFile']['tmp_name'];
$fileExtension=pathinfo($fileName,PATHINFO_EXTENSION);
$allowedType = array('csv');
if(!in_array($fileExtension,$allowedType)){?>
<div class="alert alert-danger">INVALID FILE</div>
<?php
}else{
$handle = fopen($fileTmpName, 'r');
$k = 0;
$hardness = array ();
while (($myData = fgetcsv($handle,1000,',')) !== FALSE) {
$k++;
if ( $k > 13 ) {
$hardness[] = $myData[3];
}
}
$query = "INSERT INTO metlab.resultados_dureza_junta
(a_od_r1, a_od_r2, a_od_r3, a_mod_r1, a_mod_r2,
a_mod_r3, a_mid_r1, a_mid_r2, a_mid_r3, a_id_r1,
a_id_r2, a_id_r3,b_od_r1,
b_od_r2, b_od_r3, b_mod_r1,
b_mod_r2, b_mod_r3, b_mid_r1, b_mid_r2, b_mid_r3,
b_id_r1, b_id_r2, b_id_r3,
c_od_r1, c_od_r2, c_od_r3, c_mod_r1, c_mod_r2, c_mod_r3,
c_mid_r1, c_mid_r2, c_mid_r3, c_id_r1, c_id_r2, c_id_r3,
d_od_r1)
VALUES ($hardness[0],$hardness[1],$hardness[2],$hardness[3],
$hardness[4],$hardness[5],$hardness[6],$hardness[7],
$hardness[8], $hardness[9],$hardness[10],$hardness[11],
$hardness[12],$hardness[13],$hardness[14],$hardness[15],
$hardness[16],$hardness[17], $hardness[18], $hardness[19],
$hardness[20], $hardness[21],$hardness[22],$hardness[23],
$hardness[24],$hardness[25],$hardness[26],$hardness[27],
$hardness[28],$hardness[29],$hardness[30],$hardness[31],
$hardness[32],$hardness[33],$hardness[34],$hardness[35],
IFNULL($hardness[36],DEFAULT(0)))";
//ON $hardness[36],DEFAULT I was trying to insert something so I can solve the problem but I cant.
var_dump($hardness);
$run = mysql_query($query);
if(!$run){
die("error in uploading file".mysql_error());
}else{ ?>
<div class="alert alert-success">SUCCESS</div>
<?php
}
}
}
?>
<form action="" method="post" enctype="multipart/form-data">
<h3 class="text-center">
RESULTS
</h3></hr>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input type="file" name="myFile" class="form-control">
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input type="submit" name ="uploadBtn" class="btn btn-info">
</div>
</div>
</div>
</form>
CSV example:
Error:
I would simply try padding your $myData with null
$myData = array_pad( $myData, 48, null );
realistically you should improve your SQL query to not process data that is missing, or review your default null value.
dirty solution but it works
$hardness = array (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);

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
}

How to add an PHP IF statement in this Script?

$sql = "SELECT * FROM item";
$stmt = $conn->prepare($sql);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$data['result_2'] .= '
<div class="col-sm-4 col-md-4">
<div class="content-boxes style-two top-column clearfix animated flipInY" style="opacity: 1;">
<div class="content-boxes-text">
<form action="php/additem.php" method="post" class="form-inline pull-right">
<h4>'.$row['itemName'].'</h4><input type="hidden" name="itemName" value="'.$row['itemName'].'">
<img src="../wholesale/img/sourdough.jpg" class="img-reponsive">
<p>'.$row['description'].'</p><input type="hidden" name="description" value="'.$row['description'].'">
<div class="form-group">
<label class="sr-only" for="exampleInputAmount">Qty</label>
<div class="input-group">
<input type="number" name="qty" class="form-control" id="exampleInputAmount" placeholder="How Many?">
</div>
</div>
<button type="submit" class="btn btn-primary">Add</button>
</form>
</div>
<!-- //.content-boxes-text -->
</div>
<!-- //.content-boxes -->
</div>
';
}
I want to be able to add an if statement in this result_2 string.
This is for displaying a product, and i would like to display price depending on users session value?
eg.
if ($_SESSION['customer_x'] == a) {
display price a
}
else if ($_SESSION['customer_x'] == b) {
display price b
}
Is this the correct method to be able to add an if statement to a JSON query?
After Starting your while loop, put a if else there,
$price ="";
if ($__SESSION['customer_x'] == a) {
$price='display price a';
}
else if ($_SESSION['customer_x'] == b) {
$price='display price b';
}
and now echo this price where ever you want to in your html
this is more neet and less messy way
You can use a ternary if operator to have conditional statements inside strings, example
$bool = false;
echo "The value of \$bool is " . ($bool == true ? "TRUE" : "FALSE");
Example in use
To add that you can keep doing the same but:
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){ // the next of the content
$priceOfSession = ($__SESSION['customer_x'] == a) ? 'pricea' : 'priceb';
$data['result_2'] .= '
<div class="col-sm-4 col-md-4">
'.$priceOfSession.'
</div>
</div>
<button type="submit" class="btn btn-primary">Add</button>
</form>
</div>
<!-- //.content-boxes-text -->
</div>
</div>
';
}
So if you want to evaluate only two conditions if otherwise the if you want, simply add it there. Do as you add the $ row but before defining value.

Linking data within MySQL tables into 1 table with PHP Code

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)

Categories