php mysql: UPDATE will only work WHERE data = integer - php

I am new to php and mysql so it may be that I am missing something obvious but here goes:
I am setting up a database to store items with stock. Each item is assigned an amount of stock (e.g. 5). Each item is displayed on my webpage with buttons next to it to manually add or remove stock from the database:
$query = "SELECT * FROM classes";
// This uses a mysql function that act upon our $query variable above
$result = mysql_query($query);
// This is a loop that says "while there is data to display...keep looping round and displaying that data".
while($class_data = mysql_fetch_array($result)) {
// Now we are going to echo that data
echo
"<div class=\"classmanagertablecontent\">" . $class_data['name'] . "</div>
<div class=\"classmanagertablecontent\">" . $date['date'] . "</div>
<div class=\"classmanagertablecontent\">" . $class_data['stock'] . "</div>
<div class=\"classmanagertablecontent\">" . $class_data['button_paypal'] . "</div>";
<form action="../url.php" method="post">
<input type="hidden" name="button_paypal_fromform" value="<?php echo $class_data['button_paypal'] ?>">
<input type="submit" value="remove stock" name="remove stock">
</form>
<form action="../url.php" method="post">
<input type="hidden" name="button_paypal_fromform" value="<?php echo $class_data['button_paypal'] ?>">
<input type="submit" value="add to stock" name="add to stock" >
</form>
</div>
}
The code in the url that the "add to stock" button posts to is as follows:
<?php
$button_paypal = $_POST['button_paypal_fromform'];
mysql_query("UPDATE classes SET stock = stock+1 WHERE button_paypal = ". $button_paypal ."");
?>
For whatever reason WHERE button_paypal = "a number" it works...
...but if button_paypal = "a string" it does nothing.
I cannot get my head around this. The paypal hosted buttons I will be using are made up of letter and numbers so it need to work with a combination of the two.
I have tried...
echo "$button_paypal";
...on my url.php page and the button reads fine (e.g. SD76S9SFGV)
in my database "button_paypal" is a TEXT field but i have also tried VARCHAR. STOCK is an INT.
If anyone can help then I will be very grateful. Thanks. #hopethismakessense

All you need to do is wrap your string value in single quotes:
<?php
mysql_query( "UPDATE classes SET stock = stock+1
WHERE button_paypal = '{$_POST['button_paypal_fromform']}' ");
I wrapped the array variable in {} brackets, so you can include directly within your double-quoted query (no need to concatenate like " . $var . ", and also no need to create a second variable when you can reference this directly)

Related

Populate textbox with table entry plus one?

I am trying to increment project number based on the last entry. The the primary key PROJECTNOID auto-increments but is not the same format as the project number (Ex: PROJECTNOID = 1 and Project Number = 19000). I don't want this to be a dropdown box even though some of my code shows the opposite.
<?php
connect = mysqli_connect("**", "**", "**", "**");
$query4 = "SELECT PROJECTNOID, ProjectNumber FROM tblProjects ORDER BY
PROJECTNOID";
$result4 = mysqli_query($connect,$query4);
$options4 = "";
while($row4 = mysqli_fetch_row($result4);){
$options4 = $options4."<input value=$row4[0]$row4[1]</input>";
}
?>
Here is the html textbox:
<label for="txtfield">Project Number</label>
<!--<input type="text" id="reqtxtfield" name="projectnumber"
value="<?php ?>" readonly/>-->
<?php echo $options4;?>
But it would look like how you had it but instead of '1' inside the
box it would display '19000' and there would be nothing outside of the
box other than the label "Project Number". As far as i'm aware you can
assign a value to the text box, regardless of whatever the input is. I
would like it to display the value from one field name but actually
contain the value from a different field name. Both are in the same
table of course.
OK - gotcha. Unfortunately, you cannot do that. A textbox can only have one value and the user is always free to change that value, even if you make it read-only. You can test that out by using the developer toolbar in your browser. Probably a good time to mention that all user input should be considered dangerous and you should never trust it. Once they have submitted the form you need to verify it.
What I would recommend in your case is to use a hidden <input> which contains the value you actually want to submit; projectnoid. You can then display the Project Number in any manner you choose.
<form>
<h1>Project Number: 19000</h1>
<input type="hidden" name="projectnoid" value="1">
<input type="submit" name="submit">
</form>
To generate this, you would:
<?php
while($row4 = mysqli_fetch_row($result4)){
$projectnoid = $row[0];
$projectNumber = $row[1];
echo '<h1>' . $projectNumber . '</h1>';
echo '<input type="hidden" name="projectnoid" value="'. $projectnoid .'">
}
PHP:
<?php
$query_5 = "SELECT MAX(ProjectNumber) FROM tblProjects;";
$result_5 = mysqli_query($conn, $query_5);
$row_5 = mysqli_fetch_array($result_5);
$nextproject=$row_5['MAX(ProjectNumber)']+1;
?>
HTML:
<html>
<form class="myform" action="<?php echo htmlspecialchars($_SERVER[" PHP_SELF "]);?>" method="post">
<label for="txtfield">Project Number</label>
<input type="text" id="reqtxtfield" name="projectnumber" value="<?php echo $nextproject ?>" readonly/><br>
After running successful insert query:
echo "<meta http-equiv='refresh' content='0'>"; //REFRESH PAGE TO UPDATE PROJECT NUMBER

Retrieve DIV-content inside a Form

I have been searching for help from various forums and similar posts, but without any progress.
I have three pages, one that lets me insert information about projects into my database, a second that show the images and names of every project in the database, and a third page which I want to have a function that shows the image and name of the selected project in the second page.
Code on the second page(dashboardadmin.php):
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
$conn = mysqli_connect("localhost","root","","wildfire");
if(mysqli_connect_errno())
{
echo mysqli_connect_error();
}
$sql= "SELECT pid, project_name, image, image_type FROM project";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_array()) {
echo "<form action='omprojekt.php' method='post'>
<div id='comp' name='comp'>
<img src=pic.php?pid=".$row['pid']." width=100xp height=100xp/>"." ".$row['project_name']."
</div>
<input type='submit' name='submit' value='Choose' />
</form>";
}
}
else {
echo "0 results";
}
mysqli_close($conn);
?>
Code on the third page (omprojekt.php):
<?php
/* Tried both of the $val variables but of course only one at a time. This is only to show you what I have tried. */
$val = isset($_POST['comp']) ? $_POST['comp'] : '';
$val = $_POST['comp'];
if(isset($_POST['submit'])){
echo "$val";
}
?>
In the last code you can see that I have two $val variables, but I have only used one of them at a time in my codes. The purpose of showing both of them here is to show you that I have tried both of them.
What I want to do is to make the third page show the image and name of the selected project in the second page. As you see, I have tried to retrieve the content from the DIV using the same "name". The problem is that the third page(omprojekt.php) doesn't show any content at all, and not even any errors.
You're expecting the div to submit like an input, but it won't, because it's not an input. So put it in an input.
if ($result->num_rows > 0) {
while($row = $result->fetch_array()) {
// Don't use and id attribute because you're in a loop and you might have multiple id's with the same value.
echo "<form action='omprojekt.php' method='post'>
<div>
<img src=pic.php?pid=".$row['pid']." width=100xp height=100xp/>"." ".$row['project_name']."
</div>
<input type='hidden' name='pid' value='".$row['pid']."'>
<input type='hidden' name='project_name' value='".$row['project_name']."'>
<input type='submit' name='submit' value='Choose' />
</form>";
}
}
Then on the next page,
$val = (isset($_POST['pid']) && isset($_POST['project_name'])) ?
"<img src=pic.php?pid={$_POST['pid']} width=100xp height=100xp/> {$_POST['project_name']}" : '';
For the sake of completeness, there are a few other things wrong with your code.
1) The width and height attributes on the iamge should have quotes, and do not accept "px", they are just numbers. If you want to use "px" you should use style instead. <img src='' style='width:20px; height:20px;' />
2) You should be escaping user input before running it through your query.
Data will only be sent from a <form> to the action script if it exists in an <input...> HTML tag. You cannot pick data out of randon <DIV> tags etc.
So you could do this by using a hidden input field like this ( this is only one way )
if ($result->num_rows > 0) {
while($row = $result->fetch_array()) {
echo "<form action='omprojekt.php' method='post'>
<div>
<img src=pic.php?pid=".$row['pid'] .
" style="width:100px;height:100px" /> " .
$row['project_name']."
</div>
<input type='hidden' name='comp' value='" . $row['pid'] . "' />
<input type='submit' name='submit' value='Choose' />
</form>";
}
}
Now when you get to omprojekt.php the $_POST['comp'] variable will exist.
You can have as many hidden input fields as you like so if you want to pass the project_name as well just add another hidden field.

Avoid losing POST data when using php pagination

I am working on a renting website that transfer date from page to another, for example the user enter a date and some information and when he goes to another page he should find the information that he entered in the first page. Everything works fine except that when I add pagination like this: [1] [2] [3] [4] every time I click on a page number in the pagination the POST data will be lost. For example if I clicked number 2 in the pagination I get this message:
Undefined index: date......
I found some solutions which is using get method but I don't know how to use get method in this situation.
What should I change to my code to avoid losing POST data?
here is my full code:
<?php
$date= $_POST['date']; // the post data from previous page
$info= $_POST['info']; // the post data from previous page
?>
<form action="next_page.php" method="post" name="myForm">
<input name="date" type="hidden" value="<?php echo $date; ?>" />
<input name="info" type="hidden" value="<?php echo $info; ?>" />
<?php
include(db.php);
$q="select count(*) \"total\" from users";
$ros1=mysql_query($q,$link);
$row=(mysql_fetch_array($ros1));
$total=$row['total'];
$dis=8;
$total_page=ceil($total/$dis);
$page_cur=(isset($_GET['page']))?$_GET['page']:1;
$k=($page_cur-1)*$dis;
$query="SELECT * FROM cars limit $k,$dis";
$ros=mysql_query($query,$link);
while($row = mysql_fetch_array($ros))
{
echo $row["user_id"];
echo $row["user_name"];
echo $row["user_email"];
}
for($i=1;$i<=$total_page;$i++){
if($page_cur==$i){
echo ' <input type="button" value="'.$i.'"> ';
}
else{
echo ' <input type="button" value="'.$i.'"> ';
}}
?>
<input type="submit" name="userId" value="' .$row['user_id'] . '" />
</form>
You should use GET method instead of POST method.
<?php
$date = $_GET['date']; // the post data from previous page
$info = $_GET['info']; // the post data from previous page
?>
<form action="next_page.php" method="get" name="myForm">
<input name="date" type="hidden" value="<?php echo $date; ?>" />
<input name="info" type="hidden" value="<?php echo $info; ?>" />
<?php
include(db . php);
$q = "select count(*) \"total\" from users";
$ros1 = mysql_query($q, $link);
$row = (mysql_fetch_array($ros1));
$total = $row['total'];
$dis = 8;
$total_page = ceil($total / $dis);
$page_cur = (isset($_GET['page'])) ? $_GET['page'] : 1;
$k = ($page_cur - 1) * $dis;
$query = "SELECT * FROM cars limit $k,$dis";
$ros = mysql_query($query, $link);
while ($row = mysql_fetch_array($ros)) {
echo $row["user_id"];
echo $row["user_name"];
echo $row["user_email"];
}
for ($i = 1; $i <= $total_page; $i++) {
if ($page_cur == $i) {
echo ' <input type="button" value="' . $i . '"> ';
} else {
echo ' $i ';
}
}
?>
<input type="submit" name="userId" value="' .$row['user_id'] . '" />
</form>
You can use PHP sessions to store users input on the server:
PHP Sessions
Keep all the data in $_SESSION and read it from there when it's needed in the page.
Update the stored values when the users inputs something new.
You should store this information somewhere between your http-requests. There are some possible solutions for that:
you can store this information in the database
in session (temporarily store, if you don't need this data in your database)
store in every html page as a hidden field
A good way in my opinion is to start the seach with a POST form and if the results exceed a limit then construct pagination links which really are post forms incorporating the search keyword and target page in the form of hidden variables.
Passing the search keyword as a get parameter needs care (url encode) because urls have limits on the characters they allow (ascii letters and digits, and characters such as /, ~, -, _ etc ) for example a user might search for something in japanese or greek or use symbols.
Passing the search keyword as a session variable also needs care. Consider this scenario: a user has opened multiple result pages, but all pages will hereafter have access to the last processed session saved keyword. Also storing the search keyword in a session requires coordination by the developer such as when to destroy the session variable etc.

pre-populating a form field after choosing between many options using a radio button

I have searched across the entire web and I cant seem to find a solution. I am pretty much searching a database for individuals. I can use last name for instance and then if two people have the same last name they both will print on my page. I want to be able to select the individual I would want ( or am for instance ) and click next ( a hyperlink to a page with blank forms ) which is where I would like the info of the individual I selected ( and what was printed on the page ) in the forms pre filled. It allows a more user friendly approach then having to re type the data and also avoid miss spelling of company name or drivers license for example. I have put my code up many times but here it is again.this is the code for the finding and printing of the search results. no radio button yet, as i am trying to figure that out.
<div id="results" style="width:750px;height:225px; text-align: center">
<?php
$host = "localhost"; //server
$db = ""; //database name
$user = ""; //databases user name
$pwd = ""; //password
mysql_connect($host, $user, $pwd) or die(mysql_error());
mysql_select_db($db) or die(mysql_error());
$searchTerm = trim($_GET['searchname']);
// Check if $searchTerm is empty
if($searchTerm == "")
{
echo "Enter name you are searching for.";
exit();
}
else
{
//$sql = "SELECT * FROM contractor WHERE CONCAT(FIRSTNAME,' ',LASTNAME,' ',
ARRIVAL) like '%$searchTerm%' GROUP BY FIRSTNAME";
$sql= "SELECT * FROM contractor WHERE CONCAT(FIRSTNAME,' ',LASTNAME,' ', ARRIVAL)
like '%$searchTerm%'";
$query = mysql_query($sql);
$count=mysql_num_rows($query);
//array_unique($count);
if(($count)>=1)
{
$output = "";
while($row = mysql_fetch_array($query))
{
$output .= "First Name: " . $row['FIRSTNAME'] . "<br />";
$output .= "Last Name: " . $row['LASTNAME'] . "<br />";
$output .= "Arrival: " . $row['ARRIVAL'] . "<br />";
}
echo $output;
//echo array_unique($output);
}
else
echo "There was no matching record for the name " . $searchTerm;
}
?>
</div>
this is the code for my form field which of course is a empty form that is just being submitted to the database after submission.
<form action="insert_submit.php" method="post" style="margin-left:35px;">
First Name: <input type = "text" name="FIRSTNAME" id="FIRSTNAME" />
Last Name: <input type = "text" name="LASTNAME" id="LASTNAME"/>
Purpose: <input type = "text" name="PURPOSE" id="PURPOSE"/>
<br>
</br>
Company: <input type = "text" name="COMPANY" id="COMPANY" />
DL #: <input type = "text" name="DRIVERL" id="DRIVERL" />
<br>
</br>
<input type="radio" name="STATUS" id="STATUS" value="Checked In">Log In
<br></br>
<input type="radio" name="STATUS" id="STATUS" value="Checked Out">Log Out
<br></br>
<input type="submit" value="Submit" >
<br>
</br>
</form>
so your output line would be something like (clean up to suit your formatting)
$output .= '<a href="'.$_SERVER['PHP_SELF'].'?userid='.$row['UNIQUEID'].'">
First Name: '.$row['FIRSTNAME'].'<br />
Last Name: '.$row['LASTNAME'].'<br />
Arrival: '.$row['ARRIVAL'].</a><br />';
and you build into the page a condition that if you have the UNIQUEID coming in to look up and fill out the form such as
Company: <input type = "text" name="COMPANY" id="COMPANY" value="<?PHP echo $row['COMPANY']; ?>" />
edit to suit your database of course
sample code formatting
if(something){
do something
}else{
while(){
} # end while
} # easy to see this matches the if/else set of brackets
additional information for prepopulating
easiest would probably be on the same page. look for the userid coming into the page
if(!isset($_GET['userid'])){
# meaning we do not have a userid from a url that we generated above
# insert all your code to generate the links
}else{
# meaning we *have* a userid from a url that we generated above
# do your database query based on the userid such as
$sql='select * from mytable where userid=?';
$result=sqlsrv_query($db,$sql,array($_GET['userid']),array('Scrollable'=>'static'));
# or use mysqli, pdo or whatever... just watch for sql injection
$row=sqlsrv_fetch_array($result,SQLSRV_FETCH_ASSOC));
# assuming we will not have more than one element returned
?>
First Name: <input type = "text" name="FIRSTNAME" id="FIRSTNAME" value="<?PHP echo $row['firstName']; ?>"/>
and so forth... that should get you started
So basically what you need is in the first page a lis of identical names, or ideally one name, like:
content, content, content,
FirstName, LastName
FirstName, LastName
And than if you click on either of them, than the user is redirected to another page, containing all the details of the selected person, in a form. If I am getting you right.
I would not use checkbos on the first page, simply make the person's name a hyperlink like:
http://domain.com/userdetails?userid=666
So you pass on the user id to the second page. The php code on the second page can thank draw user details from the database and populate the form.
For that purpose you can either generate the form in an echo line-by-line manner, or use DomDocument tofind and fill the relevant value fields.
Second page form generation:
you select the row with the id, than fetch it into an array, named $array.
$array = mysql_fetch_array($query); //this query selected the row for the user with the id
echo '<form method="POST">'."\n";
echo '<input name="firstname" type="text" value="'.$array['firstname'].'">'."\n";
echo '<input name="lastname" type="text" value="'.$array['lastname'].'">'."\n";
echo '</form>';
I hope you get the idea now.

Inputting multiple values in database from HTML form using PHP

I'm trying to add multiple values into a database using PHP from an HTML. However, I can't just refer to the name attribute of the HTML form because each field in the form is generated by a PHP script. I've tried Googling around, but since I don't exactly know what I'm looking for, my search has been futile.
Here's the bit of code that I use to generate the HTML form:
<form action="input_points.php" method="post">
<?php
while($row = mysql_fetch_array($result)) {
echo $row['Name'] . ' <input type="text" name="userpoints">';
}
?>
<button type="submit" name="add_points">Add Points </button>
</form>
I don't know what names are currently in the directory so I need this piece of php to determine what names are in the database. Afterwards, I want to have a bunch of boxes for people to input points (hence the form). I'm having trouble figuring out how to link the particular text box with the user.
For example, if I have a text box for Bob, how would I link up the input text field that contains the number of points Bob earns with Bob's entry in the database?
I know you can do this with regular form fields:
$userpoints = $_POST['userpoints'];
UPDATE members SET points = $userpoints where $user = "Bob";
But since I have multiple users, how do I link up the correct database entry with the right user? Also, how would I determine which boxes are empty and which boxes are updated with a value?
If you want to update multiple filed then are using array
Please changes some code
<form action="input_points.php" method="post">
<?php
$userCount=mysql_num_rows($result);
echo '<input type="hidden" name="userCount" value="' .$userCount. '">';
while($row = mysql_fetch_array($result)) {
echo '<input type="hidden" name="userid[]" value="' .$row['id']. '">'; //Give the uniq id
echo $row['Name'] . ' <input type="text" name="userpoints[]">';
}
?>
<button type="submit" name="add_points">Add Points </button>
</form>
PHP Code -
$userCount = $_POST['userCount'];
for($i=1; $i=$userCount; $i++){
$userpoints = $_POST['userpoints'];
$userid = $_POST['userid'];
//UPDATE members SET points = $userpoints where $user = $userid;
//YOUR CODE HERE
}
The update you're trying to do is not safe unless you treat values to prevent SQL injection... but if you really want it, instead of mysql_fetch_array(), try using mysql_fetch_assoc().
Using mysql_fetch_assoc() you can extract the keys (database field names) with array_keys(). The keys will be your the name property of your form fields and the values of will be the fields' values.
Hope it helps.
You can use an array to store all the data that you need and add a hidden field that contains the missing data:
<form action="input_points.php" method="post">
<?php
for($i=0; $row = mysql_fetch_array($result); $i++ ) {
echo ' <input type="hidden" name="user[0]['name'] value ='". $row['name'] ."'">';
echo $row['Name'] . ' <input type="text" name="user[$i]['points'] ">';
}
?>
<button type="submit" name="add_points">Add Points </button>
</form>
Problem when you hit submit userpoints contain only the last value previous all values are overwritten
solution
name="userpoints"
must be different each time why not you define it in database and then fetch it just like you fetch $row['Name']?

Categories