Getting the wrong result in mysql? - php

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

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

Database Query failed error when inserting Row into Table

I am getting Database query failed error while trying to insert a new row into a table. This table (pages) has a column (subject_id) referencing another table (subjects). I am passing the value of the of the subject_id from the url and it is passed on the form correctly. All the values seem to be passed correctly on the form using php, but i get error while i try to insert the row. The form submits to itself.
select_all_pages_by_subject($sid) is a function that selects all rows (pages) from the current subject (passed from the url). It works fine for the position field.
I suspect this error is probably a MySQL syntax error somewhere in my code, but i just cant seem to figure it out yet. I appreciate some help. Thank you.
Here is my code:
<div class="body_content">
<?php
$sid = null;
if(isset($_GET["subject"])) {
$sid = $_GET["subject"];
}
?>
<form action="create_page.php" method="post">
Menu Name: <input type="text" name="menu" /> <br>
Position: <select name="position">
<?php
$new_page_query = select_all_pages_by_subject($sid);
$page_count = mysqli_num_rows($new_page_query);
for($count=1; $count<=($page_count + 1); $count++) {
echo "<option value=\"$count\">$count</option>";
}
?>
</select> <br>
Visible:<br>
No <input type="radio" name="visible" value="0" />
Yes <input type="radio" name="visible" value="1" /> <br>
Subject ID: <input type="text" name="subject_id" value="<?php echo $sid; ?>" /> <br>
Content: <br>
<textarea rows="5" cols="40" name="content"></textarea> <br>
<input type="submit" value="Create Page" name="submit" /> <br>
Cancel <br>
</form>
<?php
if(isset($_POST['submit'])) {
$menu_name = $_POST["menu"];
$position = (int) $_POST["position"];
$visible = (int) $_POST["visible"];
$content = $_POST["content"];
$subject_id = (int) $_POST["$sid"];
$insert_query = "INSERT INTO pages (subject_id, menu_name, position,
visible, content) VALUES ({$subject_id},'{$menu_name}', {$position},
{$visible}, '{content}')";
$page_insert = mysqli_query($connection, $insert_query);
if($page_insert) {
$_SESSION["message"] = "Page created successfully";
redirect_to("admin.php");
} else {
$_SESSION["message"] = "Page creation failed";
redirect_to("create_page.php?subject=$sid");
}
}
?>
</div>
Edit: removed the WHERE statement
The problem is INSERT cannot have a WHERE after it.
$insert_query = "INSERT INTO pages (subject_id, menu_name, position, visible, content) VALUES ({$subject_id},'{$menu_name}', {$position}, {$visible}, '{content}')";
So after some troubleshooting, i decided to separate the form and form processing into 2 different pages, then i realized the problem, in the form action, i did not specify the subject id in the URL since i was passing the id from the URL:
<form action="create_page.php" method="post">
should be:
<form action="create_page.php?subject=<?php echo $sid; ?>" method="post">
Edit: I have also noticed that the "Database query failed" error was being called on the Position form field where i was making a database connection on the "pages" table to pull the number of rows. So when the insert statement failed due to the absence of subject id from the url, php did not process the page past the position form field, it called the error on the field and stopped execution. When insert query fails, parts of the form are displayed on the screen (only the menu name field and the position field with empty values). When i tried to view source code for errors, it requested the page be reloaded again (felt like an infinite loop running or something)

PHP Buttons inside loop

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!

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 to assign text input to php valuables without submitting

Hi I am new to web developing. I am having a submit php page which is submitting datas from previous form page and also showing submit confirming info. But now I am going to make it asking users to enter 2 more things ( name and room number) before submitting to SQL, so... information from previous form and name, room number will be insert to SQL all together. I want to handle this submission within one same page, but for the new added 2 datas (name & room number) I don't want to do one separate submit() since I don't want the page refreshing,
How can I do it? How can I apply value from an input tag(Cname) to $Cname ? without refreshing the page ? Here is my code:
...
<head>
<?php
$T1comment1 = $_POST['T1comment1'];//these are from previous form
$T1comment2 = $_POST['T1comment2'];//these are from previous form
$T1comment3 = $_POST['T1comment3'];//these are from previous form
$T1comment4 = $_POST['T1comment4'];//these are from previous form
$item_1 = $_POST['item_1'];//these are from previous form
$item_2 = $_POST['item_2'];//these are from previous form
$item_3 = $_POST['item_3'];//these are from previous form
$item_4 = $_POST['item_4'];//these are from previous form
$Cname = $_POST['Cname'];
$CRnumber = $_POST['CRnumber'];
?>
</head>
<body>
<div>
<form method="POST" name="namdAndRm" id="namdAndRm" action="<?php echo $PHP_SELF;?>" >
<input type="text" id="Cname" name="Cname" value="your name here"></input>
<input type="text" id="CRnumber" name="CRnumber" value="room no."></input>
</form>
</div>
<div>
<div class="Back"></div>
<div class="submit" onclick="goSubmit();"></div>
</div>
<script type="text/javascript">
function goSubmit(){
<?php
$Cname = $_POST['Cname']; //is this the right way to do it?
$CRnumber = $_POST['CRnumber']; // I tested a lot, seams direct "=" is not working...
$SqlStatement = "INSERT INTO T3survey (T1item_1, T1comment1, T1item_2, T1comment2, T1item_3, T1comment3, T1item_4, T1comment4, Cname, CRnumber, day) VALUES ('$item_1', '$T1comment1', '$item_2', '$T1comment2', '$item_3', '$T1comment3', '$item_4', '$T1comment4', '$Cname', '$CRnumber', NOW())";
$result = mysql_query($SqlStatement,$connection);
if (!$result){ die("Error " . mysql_errno() . " : " . mysql_error());}
?>;
};
</script>
</body>
</html>
All you need to do is create a bunch of hidden fields in your form, like so:
<input type='hidden' name ='T1comment1' value='<?php $T1comment1;?>'>
<input type='hidden' name ='T1comment2' value='<?php $T1comment2;?>'>
<input type='hidden' name ='T1comment3' value='<?php $T1comment3;?>'>
<input type='hidden' name ='T1comment4' value='<?php $T1comment4;?>'>

Categories