Problem with MySQL update [duplicate] - php

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
table updates empty spaces when user do not enter anything to the textbox
greetings :)
i am having problems updating my database whenever the user clicks on the submit button.
i am going to show you the flow of my program,i already tried figuring out the problem,but i just can't find solutions. i hope someone could help me.
i have 2 problems encountered here:
my database won't update after clicking the submit button
the user may choose which to update,if the textbox is empty,it will update the data with empty spaces.and i want the data to remain as it is if the textbox is empty.
in my program,if you want to update the employee information,you must click the name that contains a link in the page. (in my program its the employee name that needs to be clicked) when clicked,a pop up will open.
the link in my index.php contains the following code:
<td class="sub" width="100" align="center">
<a href="" onclick = javascript:newPopup('empinfo.php?emp=<?php echo $eid ?>');><?php echo$ename?></a>
</td>
NOTE the empinfo.php is my pop up window,it calls the pop up when clicked. emp isthe name i assign to pass in the empinfo.php it contains the employee ID. NO PROBLEM HERE,I JUST WANT TO SHOW YOU THE FLOW
when the empinfo.php appears,it will show this format:
Employee name: //textbox here
Position: /textbox here
Department: /textbox here
Employee Tag: /textbox here
**SUBMIT BUTTON**
when the user clicks the submit button, it should have updated the database with the inputted values,but mine won't update :(
here is the codes i used:
<?php
$con=mysql_connect('localhost','root','mariel') or die(mysql_error());
mysql_select_db('intranet',$con);
if(isset($_POST['submitted']))
{
$qry = "UPDATE gpl_employees_list SET emp_nme = '".$_POST['name']."', emp_pos = '".$_POST['pos']."', emp_dep = '".$_POST['dep']."', emp_tag = '".$_POST['tag']."' WHERE emp_id = '".$_GET['emp']."' ";
mysql_query($qry) or die (mysql_error());
}
?>
this is the content code in my form,together with the submit that i used:
<form action="index.php" method="POST">
<input type='hidden' name='submitted' id='submitted' value='1'/>
<input type='hidden' name='eid' id='eid' value= '<?php echo $_GET['emp']?>' />
<fieldset>
<div class='container'>
<label for='ename' >Employee name:</label><br/>
<input type='text' name='ename' id='ename' value='' maxlength="50" /><br/><br/>
</div>
<div class='container'>
<label for='pos' >Position:</label><br/>
<input type='text' name='pos' id='pos' value='' maxlength="50" /><br/><br/>
</div>
<div class='container'>
<label for='dep' >Department/Division:</label><br/>
<input type='text' name='dep' id='dep' value='' maxlength="100" /><br/><br/>
</div>
<div class='container'>
<label for='tag' >Employee Tag:</label><br/>
<select name="tag" id="tag">
<option value="Y">Yes</option>
<option value="N">No</option>
</select> <br/><br/>
</div>
<div class='container'>
<input type='submit' name='Submit' value='Submit' onclick = "location.reload();window.close()"/>
</div>
</fieldset>
</form>
i hope someone could clear it up for me
MisaChan

It's not updating because you probably need to refer to $_POST['eid'] instead of $_GET['emp'] because you don't have it in index.php like index.php?emp=1. You already have that field so use that:
<input type='hidden' name='eid' id='eid' value= '<?php echo $_GET['emp']?>' />
Also you don't need to do this:
onclick = "location.reload();window.close()"
Type submit reloads the page by default.
Lastly, consider #Sam152's pointers :)

There could be a number of things wrong, but these points should help you debug your script.
Firstly you need to escape your post
variables to ensure things like
apostrophes don't mess up your query,
it's also a security vulnerability.
Secondly, make sure your form action is pointing to the PHP script. Maybe put a print statement at the top of the script to make sure PHP is actually receiving the data.
Then assign the value of the SQL query to a variable and print it out before you run it. You can then easily see what's being sent to the SQL server. Maybe run it in an SQL management tool my phpMyAdmin and observe any errors with it.
Hope this helps. Feel free to update your question with new information as it comes.

Related

PHP foreach executing code multiple times

At the bottom of this code you'll see an 'Accept Offer' button, when I click on that another piece of code gets executed as you can see on the bottom of this post.
For example this project has 3 bidders, so 3 times bidder_id and writer_bid so I use 'foreach' and load it in divs, works fine, but now I need to store those variables in a database, which technically works but it doesn't store the bids from the row I pull them from, it just takes the data from the last row, that is if I place the code at the bottom of this thread in my header.
However when I put it inside the loop it executes three times, I saw that when I got an error message that I had to close 3 times cause there are 3 rows in the database table that I pull the data from.
How can I prevent this, and either have it load once when the code is inside the foreach loop, or have it pull the correct writer_bid and bidder_id to store.
<div class="WB-Bottom-block lefts">
<?php $getBidders=" AND project_id=$project_id"; $bidders=getBidder($getBidders); foreach($bidders as $bidder) {
$bidder_id=$bidder['writer_id'];
$writer_bid=$bidder['writer_bid'];
?>
<div class="findwriters_boxes">
<div class="findwriters_right">
<div style="float:right;margin-top:6px;width:170px;">
<input type="hidden" name="writer_bid" id="writer_bid" value="<?php echo $writer_bid; ?>" />
<input type="hidden" name="bidder_id" id="bidder_id" value="<?php echo $bidder_id; ?>" />
<input type="submit" class="homebtn11" name="submit" id="submit" value="Accept Offer"/>
</div>
</div>
</div><?php } ?>
Below the code that needs to be executed and that results in issues, whether I place it inside the foreach loop, or inside the header instead.
As you can see I tried to store it in input fields so that it stays there so the header can pull it on refresh of the page / click of the button.
<?php if(isset($_POST['todo']) && $_POST['todo']=='submit_project') {
$balance=get_client_balance_info($current_user->ID);
$writer_bid=$_POST['writer_bid'];
$bidder_id=$_POST['bidder_id'];
if($balance >= $_POST['writer_bid']) {
global $wpdb;
$sql3="UPDATE `wp_project` SET `writer_id` = '".$bidder_id."' WHERE `id` =". $project_id;
$wpdb->query($sql3);
$sql4="UPDATE `wp_project` SET `price` = '".$writer_bid."' WHERE `id` =". $project_id;
$wpdb->query($sql4);
$sql5="UPDATE `wp_project` SET `status` = '2' WHERE `id` =". $project_id;
$wpdb->query($sql5);
$success_msg="You accepted a bid, the money will be deducted from your account.";
}
else $fail_msg="Your balance is not sufficient.";
I think you should make a form for each div that you are adding right now you are putting the bidder_id in the different inputs but the same name.
So it will get the last inputs, maybe it's better to specify the inputs with the row id or to separate the forms or make the input names as array.
I hope this helps you.
I fixed it with the help of Diar Selimi like this:
<div style="float:right;margin-top:6px;width:170px;">
<form action="" name="frmeditor" method="post" id="frmeditor" >
<input type="hidden" name="todo" id="todo" value="submit_project" />
<input type="hidden" name="writer_bid" id="writer_bid" value="<?php echo $writer_bid; ?>" />
<input type="hidden" name="writer_id" id="writer_id" value="<?php echo $writer_id; ?>" />
<input type="submit" class="homebtn11" name="submit" id="submit" value="Accept Offer"/>
</form>
Before that my form and value="submit_project" tags were scattered all over the place!

PHP Autofill or something?

I have seen many questions related to auto fill, but none of them worked for me. I'm not even sure if a solution to my problem lies in HTML or PHP. I am new in both of them and I'm still not used to them. I'm working on a simple chat app. What I have now is chat window, text field, and nick name field. Both of them pass the values to the text file (which is how I want this to work, no change here). Problem is that both these fields work as a form, and each time I submit, nick name field refreshes. What I would want is auto completing nickname field so it stays the same (it'd be the best if it stayed even after browser refreshes, but it will be okay if it only goes through the form submit)
code if needed:
PHP:
<?php
$action = $_GET["action"];
$myText = $_POST["mytext"];
$nick = $_POST["nick"];
if($action = "save") {
$targetFolder = "/var/www/html/xami/";
file_put_contents($targetFolder."htmlinput.txt", $nick.">".$myText);
}?>
HTML:
<form action="?action=save" name="myform" method="post">
<label for="nick">Nick:</label>
<input type=text id="nick" name="nick" placeholder="Nick" value="Name" required><br>
<input type=text name="mytext" placeholder="Text" required>
<input type="submit" value="Send.">
</form>
I was fooling around with autocomplete but no positive results.
I'm leaving post for tomorrow, I'll reply then.
Assuming your HTML is on a .php page you could have...
if(0<strlen($nick)){
echo "<input type=hidden id='nick' name='nick' value='$nick'>";
}else{
echo "<input type=text id='nick' name='nick' placeholder='Nick' value='Name' required><br>";
}
Or, use AJAX as #Rishi says.

Listbox with javascript action not posting values

I have the following form:
<form name='progObj_form' method='POST' enctype='multipart/form-data' action='processpage.php'>
<select name='manageObj[]' id='objectives' multiple="multiple">
<option value=0>there are no objectives for this program</option>
</select><br />
<a href='#nogo' onclick="delItem(objectives,0,'objEditBtn')" class='shiftOpt'>delete selected</a><br />
<input name='newObjective' type='text' id='newObjective'/>
<input name='addNew' type='button' onclick="AddItem(newObjective.value,6,'objectives','objEditBtn');" value='add objective'/>
<input name="passProgID" type="hidden" value="1" /><br />
<input name="objectiveEdit" id="objEditBtn" type="submit" value="save changes" disabled=disabled/>
</form>
that allows data (objectives in this case) to be added and deleted from a list box. That all works well but for some reason the updated listbox values aren't being passed to the process page.
I'm catching the data like so (simplified):
if (isset($_POST['objectiveEdit'])){
$progID=$_POST['passProgID'];
for ($v=1;$v<count($_POST['manageObj']);$v++){
$value=$_POST['manageObj'][$v];
$sqlObj="INSERT INTO progObjective (progID,objective,objectiveOrder) VALUES ($progID,$value,$v)";
$result = mssql_query($sqlObj,$linkProbation) or die('Query failed: '.$sqlObj);
}//end for ($a=0;$a<count($_POST['manageObj']);$a++)
$objMsg=print_r($_POST['manageObj']).$sqlObj;
}//end if (isset($_POST['objectiveEdit'])
For $objMsg, I get a response of 1 and the array doesn't print because ostensibly, it's empty which means that it also doesn't enter the for loop.
I can include the javascript as well but started with just this for simplicity since I'm probably just overlooking something obvious?!
Option elements are never sent to the server. Only the value of the selected option will be sent.
In your case, something like manageObj=x will be sent to the server, where x is the value of the option element that is selected by the user. It is possible that you misunderstand the [] when it's used in a name attribute.
You should try to find a different method if you want to send the objectives created by the user to the server. You could store the data in hidden inputs for example.
So I finally figured it out! There's no array because there are no selections made! I updated the submit button to call a SELECT ALL function and now it's all good.
<input name="objectiveEdit" id="objEditBtn" type="submit" value="save changes" onclick="selectAll('objectives',true)" />
name='manageObj[]' - shouldn't that be name='manageObj' ?

PHP $_POST Alert

I have this form which allows the input of any product quantity from 1-10:
<form method='post' action='cart.php'>
<input type='number' name='quantitychange' size='2' min='1' max='10' value=".$_SESSION["itemsSelected"][$i][1].">
<input type='hidden' name='ProductID' value=".$_SESSION["itemsSelected"][$i][0].">
<input type='submit' value='Update'>
</form>
And another form (button) to display a selection of payment modes:
<form action='cart.php' method='post'>
<input type='hidden' name='next'>
<input type='submit' value='Select Payment Mode'>
</form>
What I want to happen is that when a user did not input anything (1st form), ex. null or 0, I want to display an alert box that says 'Product quantity can't be null or 0'.
Here's my code for that:
if (isset($_POST['next'])) {
if ($_POST['quantitychange']==null || $_POST['quantitychange']==0) {
?>
<script type='text/javascript'>
alert('Product quantity can't be null or 0.');
</script>
<?php
}
else {
echo "
//Payment modes here
";
}
}
The error is that even when a user inputs a quantity bet. 1 to 10, it still displays the alert message. Any help? Thank you.
By the way, the input type "number" only works in Google Chrome browser.
Use a small javascript (or jQuery) function to validate the form before posting it. Have this function throw up the alert if your condition isn't met and then return false. If the condition is met, return true, and it gets submitted.
Edited to add since this might get googled, I'll help a bit with code snippet I have used. The below example is jQuery and was used in production for a web application I made for my employees. document.form.doit.submit(); should be the pure javascript way of submitting the form.
<script type="text/javascript">
function subForm() {
// document.form.doit.submit();
if( test condition passes ) {
$('#save_order').submit();
}
}
</script>
<form id="save_order" action="oms_db.php" method="POST">
<input id="doit" type="button"
value="i am a button" onClick="subForm();">
</form>
I think you have some error in your forms. Instead of the below:
<input type='number' name='quantitychange' size='2' min='1' max='10' value=".$_SESSION["itemsSelected"][$i][1].">
<input type='hidden' name='ProductID' value=".$_SESSION["itemsSelected"][$i][0].">
you should be using something like this:
<input type='number' name='quantitychange' size='2' min='1' max='10' value="<?php echo $_SESSION["itemsSelected"][$i][1]; ?>">
<input type='hidden' name='ProductID' value="<?php echo $_SESSION["itemsSelected"][$i][0]; ?>">
The value parameters in the hidden input fields needs to be echoed from PHP. What you have now is like the value is simple strings ".$_SESSION["itemsSelected"][$i][0].".
I suggest you use
if(empty($_POST['quantitychange'])) { echo 'yourerror'; }
As it is far cleaner then your script. (http://php.net/manual/en/function.empty.php)
Update:
Also, you can't use two seperate forms like you do, your browser only posts whats between
<form>
</form>
Using only one will fix your problem.

Sowing an updated value in a HTML page

I'm trying to use AJAX to make my website a little slicker than it currently is.
I have a block of code that shows the following
if($guess == 0){
echo "Enter a guess:;
*AJAX form* ---> inserts a MySQL database record with the users guess
<div to show results of script for form> - not necessarily needed
}else{
echo "Update your guess:";
*SAME AJAX form* ---> updates the MySQL database record with the users new guess
<div to show results of script for form> - - not necessarily needed
}
The problem I'm having is that I want part of the webpage to show:
Your latest guess is: £x.xx
However because a user will start off with 0 guesses, and AJAX sends the form "behind" the scenes, I'm struggling in knowing how to show the above line once the user has made a guess.
So also that way when they revisit the page at a later date, it shows the last guess they had.
Those are the only 2 elements of the page I want to be able to refresh, the rest of the information doesn't have to refresh.
Some more code here:
<?php
if($guessess_open == 1){
echo "<h2>guesses are CLOSED</h2>";
}
else{
//it's this part that I want to have always shown on the page, but when I visit the page fresh it doesn't show me any results.
<div id="results"></div>
<form name="myform" id="myform" action="" method="POST">
<!-- The all important guess field -->
<label for="guess" id="guess_label">Guess<br></label>
<input type="text" name="guess" id="guess" size="10" value=""/>
<?php
echo "<input type='hidden' name='user_id' id='user_id' size='10' value='$user'/>";
echo "<input type='hidden' name='item_id' id='item_id' size='10' value='$itemID'/>";
echo "<input type='hidden' name='title' id='title' size='100' value='$title2'/>";
echo "<input type='hidden' name='owner_id' id='owner_id' size='10' value='$ownerid'/>";
echo "<input type='hidden' name='guesses_open' id='guesses_open' size='10' value='$guesses_open'/>";
echo "<input type='hidden' name='exist' id='exist' size='10' value='$exist'/>";
?>
<!-- The Submit button -->
<br>
<input type="image" name="submit" src="URL" width="150px" height="100px">
</form>
The only way I can get it to show something in that part of the page is to have some code in which checks a database for a guess and if it exists display the result, but then when I submit a new form, because it only updates the results it doesn't update the part of code for example could include
else{
include("URL.php?item_id=" . $itemID. "&user=" .$user. "");?>
//it's this part that I want to have always shown on the page, but when I visit the page fresh it doesn't show me any results.
<div id="results"></div>
which shows the latest guess when a user visits the page, but then when a new guess is made, this doesn't update... I don't have to have my forms php up display the result if the above part of code would update each time I make a guess... I hope this is clearer?

Categories