PHP Buttons inside loop - php

I have a problem and I don't know how to sove it.I have an inventory table that contains an id (that is assign to a user)column and id_item column (that is assign to an item from items table) and an items table that also contains an id table.
More specifically this is what my database contains:
items table:
id name
1 Dagger
2 Staff
3 Wood Shield
Each with his unique id.
Inventory table:
id id_item username name
1 3 cristi Wood Shield
2 1 motoc Dagger
2 2 motoc Staff
The id is from every user id and id_item is the item's id from items table.
Problem:
Let's say I'm logged in as motoc who has 2 weapons in his inventory. Til now everything is fine. I want to make a button for every item that he has. The buttons are there but not working properly. When I click the first one is shows me ssss1 which is correct but when I press the second one nothing hapens. I want to show me ssss2 more specifically the next $row1['id_item'].
I really don't know how to solve this.
Thank you.
This is what i've tried:
if (isset($_SESSION['id'])) {
$sth1 = $dbh->prepare("SELECT * FROM inventory WHERE id = ".$_SESSION['id']."");
$sth1->execute();
while($row1 = $sth1->fetch(PDO::FETCH_ASSOC)){
$sth = $dbh->prepare("SELECT * FROM items WHERE id = ".$row1['id_item']."");
$sth->execute();
$row = $sth->fetch(PDO::FETCH_ASSOC);
$ss = print $row1["id_item"];
?>
<form id='<?php echo $row1["id_item"]; ?>' method="POST" action="" >
<input type="hidden" name="refid" value="add" />
<input type="submit" name="submit<?php echo $row1["id_item"]; ?>" value="Add" />
</form>
<?php
}
if (isset($_POST["submit$ss"])) {
$refid = intval($_POST["refid"]);
$sth1 = $dbh->prepare("SELECT * FROM inventory WHERE id = ".$_SESSION['id']."");
$sth1->execute();
$row1 = $sth1->fetch(PDO::FETCH_ASSOC);
echo "ssss".$row1['id_item'];
}
}

This is a bad way of building your form. Since you're building a "personalized" form for EVERY item, there's no need to create dynamic field names, just a hidden form field:
<form ... >
<input type="hidden" name="id_item" value="<?php echo $row1['id_item'] ?>" />
<input type="hidden" name="refid" value="add" />
<input type="submit" name="submit" value="Add" />
</form>
Then you simply check $_POST['id_item'] in the form handling code, instead of having to look for every single possible submit1, submit2, etc...
As well, your form handling code is running within the same context as the form generation code, before the form has even had a chance to be displayed and get a user click. You should at least have somethign like
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
... handle form here ...
echo "ssss...";
}
so the item info retrieval only runs when the form actually HAS been submitted.

Give this a shot. I'm kinda confused on exactly what you want to happen, but I think this will do it.
<?php
if (isset($_SESSION['id'])) {
$sth1 = $dbh->prepare("SELECT * FROM inventory WHERE id = " . $_SESSION['id']);
$sth1->execute();
while ($row = $sth1->fetch(PDO::FETCH_ASSOC)) {
$sth = $dbh->prepare("SELECT * FROM items WHERE id = " . $row['id_item']);
$sth->execute();
$row = $sth->fetch(PDO::FETCH_ASSOC);
$ss = $row["id_item"];
?>
<form id='<?php echo $ss; ?>' method="post" action="?show">
<input type="hidden" name="item_id" value="<?php echo $ss; ?>" />
<input type="submit" name="submit" value="Add" />
</form>
<?php
}
if (isset($_GET["show"]) && isset($_POST['item_id'])) {
echo "ssss" . $_POST['item_id'];
}
}
I cleaned up some of the code and changed the way the form was built. I also changed the PHP code at the bottom to check for the changes in the form.
I will tell you now though. The way you designed the database should be changed. Keeping that updated will be a pain in the ass. You should use an items table, a users table, and have a pivot table between them since it is a many-to-many relationship.
Have fun!

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

Identifying specific row from SQL results

I have a list of 'orders' being pulled out, which consist of product name, description etc, one of the fields is quantity which is in an editable text box, next to that is an update button (which has an unique ID for that row pulled from the DB). Now when the update button is pressed, I want the quantity for that product to be updated. However i'm having problems getting the correct updated quantity to be matched with the ID of that row.
I can see that the problem is me setting the $quantity1 variable with just the last result pulled out inside the IF statement, but I can't think how to get it to relate the row i'm clicking on. Here is part of the code:
echo "<td>".$row['uName']."</td>";
echo "<td>".$row['prodID']."</td>";?>
<form method="post" action="reserved.php">
<td><input name="quantity1" type="text" id="quantity1" size="1" value='<?= $qty ?>' />
<td><input name="order2" id="order2" type="submit" class="button_add" value='<?= $row['ID']?>' /></td><?
echo "</tr>";
}
}elseif(!empty($studyDir) && $rowCount == 0){
?>
<?
}
}
if (isset($_POST['order2'])){
$order2 = $_POST['order2'];
$quantity1 = $_POST['quantity1'];
\\echo $quantity1;
$link3 = mysql_connect('localhost', '******', '******');
$SQL1 = "UPDATE ybsinter_stock.reservedStock SET qty = $quantity1 WHERE ID = '$order2'";
$result1 = mysql_query($SQL1);
mysql_close($link3);
unset($quantity1);
unset($order2);
header("Location:reserved.php");
}
?>
I can't see your form ending i.e. there is no <\form>.
Also note that declaring forms in tables (except entirely enclosed in a td) is bad HTML, run your code through the W3C validator.
Also try PHP heredocs for outputting blocks of HTML with embedded data....
echo <<<EOF
<tr>
<td>{$row['uName']}</td>
<td>{$row['prodID']}</td>
<td>
<form method="post" action="reserved.php">
<input name="quantity1" type="text" id="quantity1" size="1" value="{$qty}" />
// style this button right with CSS if you want ...
<input name="order2" id="order2" type="submit" class="button_add" value="{$row['ID']}" />
</form>
</td>
</tr>
EOF;
The above form will only submit data to your script with the id that you're interested in..
Your SQL query seems roughly correct, but beware of SQL injection - please bind your variables into your queries instead of inserting them. Use the mysqli or PDO libraries instead of the outdated basic mysql functions.
$mysqli = new mysqli( /* your connection params here */ );
$sql1 = 'UPDATE ybsinter_stock.reservedStock SET qty = ? WHERE ID = ?';
$stmt = $mysqli->query( $sql1);
$stmt->bind_param( 'sd', $quantity1, $order2);
$result = $stmt->execute();

Grabbing specific variable from while loop for form submit

I have a while loop generating information with a checkbox, I would like to update the database with the new "completed" value. How can I select the specific checkbox that is generated. Please help with showing me how I can grab the specific value of a checkbox and the task_name.
Thanks, Ryan
while ($row = mysql_fetch_array($query)){
$task_name = $row['task_name'] ;
$task_description = $row['task_description'];
$task_completed = $row['completed'];
$tasks .= '<div id="tasksBody">
<form action="" method="post">Completed? <input name="completed" type="checkbox" '.
($task_completed == 1?'checked="checked"':'').
' /><input type="submit" value="Update"><br /><br />
<b>'.$task_name.'</b><br /><br />'.$task_description.'<hr><br /></form></div>';
}
}
echo $tasks;
You need to name your input with something unique for the row, such as the task_name, or better, a database record ID.
Then when the user submits the form, you will use $_POST["YourTaskNameOrIDHere"] to check the value.
What you have currently calls all the check boxes the same thing.
EDIT: I'm sorry, you're isolating all of these in their own forms, I just realized that.
What you can add is an <input type="hidden" value="$task_name" name="TaskName" /> to the form, so you can look what the checkbox is corresponding to. Then, when the user submits the form, use $_POST["TaskName"] to find out the name of the task.
Add a hidden field to each of your forms containing the task_id
<form action="" method="post">
Completed?
<input name="completed" type="checkbox" <?=($task_completed == 1?'checked="checked"':'')?> value="1" />
...
<input name="task_id" value="<?=$task_id"?> type="hidden" />**strong text**
</form>
After submit:
if (isset($_POST['task_id']) { // form has been submitted
$task_id = $_POST['task_id'];
$completed = $_POST['completed'];
$sql = "UPDATE task SET task_completed=$completed WHERE task_id=$task_id LIMIT 1";
// code for updating database
// better use PDO or mysqli-* instead of old and deprecated mysql_*
}

how can i view the data resulting from one of the choices in the dropdown list?

im new to php so im having some problems creating what i want
i'll explain first what i need .. there conferences, each conference has a list of reviewers and authors.
i have create a dropdown list where the user chooses which conference ... i want to show a list of the reviewers and the authors that are in this conference after clicking submit.
that is my code
<?php
$con = mysql_connect("localhost:3306","root","");
mysql_select_db("messaging_dd", $con);
$sql_drop = "SELECT conference_ID,conference_name FROM Conferences";
$drop_result = mysql_query($sql_drop,$con) or die(mysql_error());
$num_rows = mysql_num_rows($drop_result) or die(mysql_error());
mysql_close($con);
?>
<form name="choose" action="savedata.php" method="POST">
<br />
Conference: <select name="conference">
<?php
for($i=0 ; $i<$num_rows ; $i++)
{
$idofconference = mysql_result($drop_result,$i,0);
$nameofconference = mysql_result($drop_result,$i,1);
echo '<option value=" '.$idofconference.' ">'.$nameofconference.'</option>';
}
?>
</select>
<br />
<input type="submit" value="submit" name="submit" />
</form>
Try this,
$conf_id = $_POST['conference'];
$con = mysql_connect("localhost:3306","root","");
mysql_select_db("messaging_dd", $con);
$sql = "SELECT review, author FROM Reviews WHERE conf_id = ".$conf_id;
$review_list = mysql_query($sql,$con) or die(mysql_error());
mysql_close($con);
Or you can go for Ajax. Updating your search result, without reloading the whole page. Reference for Ajax: http://www.w3schools.com/php/php_ajax_database.asp
All the data being submitted gets stored in the $_POST variable as an array. Your conference ID will be in $_POST['conference'] as the name of your select element is conference.
An other approach is to load the desired data (reviewers and authors) through an AJAX request so that the viewer of your website won't leave the webpage.
it's similar to what you have done, just add conference id details like this:
$sql = "SELECT reviewer, author FROM Conferences where conference_ID = " . $_POST['conference'];
In your file savedata.php you can put
$whatever = $_POST['conference']
$_POST is one of several arrays in php that is reserved for system data, for example you can make calls to $_server to find out details about the server(eg the time on the server)
you could also change the method='POST' to method='GET' and it would be in the GET array
$whatever = $_GET['conference']
this is a bit less secure, but if that's not a priority its worth considering
I think you should Try this.
<form name="choose" action="savedata.php" method="POST">
<br />
Conference: <select name="conference">
<?php
while($row=mysql_fetch_array($drop_result)
{
echo '<option value=" '.$idofconference.' ">'.$nameofconference.'</option>';
}
?>
</select>

Getting the wrong result in mysql?

Hello i have a html form in side php everything is working fine and i have just been showed how to do hidden fields from this website.
I have a submit button on each and every result letting the user pick what they want. When they press the submit button i want the info to be submitted and added to the database. But for some reason when the user click submit on item 1 it adds the last item into the database e.g item 6 ?? So there is 6 results and a submit button for each one so 6 buttons. When the user presses submit on number 1 item it submits number 6 for some resson.
<form method="post" action="buydo.php">
<label><br />
<br />
</label>
<p>
<?php
$sql = "SELECT * FROM sell
ORDER BY Pokemon_level ASC";
$res = mysql_query($sql) or die(mysql_error());
while ($v = mysql_fetch_array($res)) {
echo '
<div class="auction_box">
<img src="http://myrpg.net/new_rpg/'.$v['Pokemon_pic'].'" width="100" height="100"><br/>
£'.$v['price'].'<br/>
<label id="pokemonName'.$v['id'].'">'.$v['pokemon_name'].'</label><br/>
<label>Level '.$v['Pokemon_level'].'</level><br/>
<label>Exp '.$v['exp'].'</level><br/>
<label>Time Left:';
echo '</label>
<br/>
<input type="hidden" name="Name" value="'.$v['pokemon_name'].'">
<input type="hidden" name="level" value="'.$v['Pokemon_level'].'">
<input type="hidden" name="vid" value="'.$v['id'].'">
<input type="hidden" name="price" value="'.$v['price'].'">
<input type="hidden" name="exp" value="'.$v['exp'].'">
<input type="submit" id="'.$v['id'].'" class="buy_submit" value="Buy Now" /> </div>';
}
?>
</p>
<p> </p>
</form>
That is the select with the submit buttons for each result.
Then i insert the info they have chosen.
include 'config.php';
session_start() ;
$name = mysql_real_escape_string($_POST['Name']);
$Pokemon_level = mysql_real_escape_string($_POST['level']);
$idofpokemonsell = mysql_real_escape_string($_POST['vid']);
$price = mysql_real_escape_string($_POST['price']);
$exp = mysql_real_escape_string($_POST['exp']);
$sql = "SELECT * FROM `users` WHERE `username` = '" . $_SESSION['username'] . "'";
$result = mysql_query($sql) or die(mysql_error());
$values = mysql_fetch_array($result);
echo $values['money'] ;
if ( $values['money'] == $price ) {
echo "Give them the pokemon yay";
}
if ( $values['money'] > $price ) {
mysql_query("INSERT INTO `user_pokemon` (`pokemon`, `belongsto`, `exp`, `slot`, `level`) VALUES ('$name','" . $_SESSION['username'] . "','$exp','0','$Pokemon_level')") or die(mysql_error());
echo "Your money is over";
}
Like i say the insert only inserts item 6 no matter if u press item 1 - 5 it inserts 6 the level , exp, name everything of item 6
Since you display it all in one form, the latest values are overwriting the earlier ones. Try making each item its own form by moving your <form> and </form> tags inside your while loop
or try to track with jquery clicked button id and fill a hidden field with the clicked id
This is because your html is wrong. The values get overwritten
Basically you have to options:
render a form for each item
do it with a dropdown or radio buttons
With the second option you need to rewrite your code more, but it is more elegant, if you ask me. So what do you need to do.
Move the submit button out of the loop
Only generate code with the id and labels like this:
<option value="'.$v['id'].'"/>YOUR LABEL</option>
When the form is submitted, you have to retrieve the values corresponding to your the submitted id

Categories