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();
Related
This question already has an answer here:
How do I insert Data Into database with many Input which has same name?
(1 answer)
Closed 3 years ago.
i was trying to updating multiple MYSQL rows with one submit button,
before i used to create submit for each row, but since i have a lot of rows now i need to update them all together
index.php
<?php
if (mysqli_num_rows($row){
while($row1= mysqli_fetch_assoc($row){
id<input type="text" value="<?php echo $row["id"];?>" name='id' id="id" >
id<input type="text" value="<?php echo $row["name"];?>" name='name' id="name" >
}
<button type="submit" formaction="update.php">
submit
</button>
}
update.php
$id= $_POST['id'];
$name= $_POST['name'];
$sql = "UPDATE `$tabelname` SET
name='$name'
WHERE id='$id'";
its updating the first row only
Assuming that id is the primary key,
In your html, you need to use an array in the name. This allows the form to send it as an array instead of just taking the last value:
<?php while($row1= mysqli_fetch_assoc($row): ?>
<div>
<label>Name: </label>
<input type="text" value="<?=$row["name"]?>" name="name[<?= $row["id"] ?>]" id="name-"<?= $row["id"] ?> " />
</div>
<?php endwhile; ?>
The key here is name=“name[]”. The square brackets make it an array. I’m using the id as the index. (Note that <?= is just a much more concise way of writing <?php echo)
Then, in your php script, the easiest way to show you is to iterate through the array and do an update each time:
$row = $_POST[‘name’];
foreach($row as $id => $name) {
// This is a big No-No!
// $sql = "UPDATE `$tabelname` SET name='$name' WHERE id='$id'";
// use prepared statements. Always.
$sql = "UPDATE `$tabelname` SET name=? WHERE id=?"; // assuming “tabelname” is not user-provided
// database connection up to you
$stmt = $db->prepare($sql);
$stmt->execute( [$name, $id] );
}
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)
I'm trying to create a website with a Leaderboard for a golf tournament and the idea is to have people be able to post scores for each hole, which will get added to a MySQL database, and then a separate page will display the scores on a leaderboard. I'm in the very beginning stages, but I'm stuck with having the user enter the scores.
My thinking is to store the scores in a table with columns for 'golfer', 'hole_num', and 'hole_score'.
I currently have this on my HTML for entering a score.
<form action="insert.php" method="POST">
Golfer: <input type="text" name="golfer" />
<br>
Hole Number: <input type="number" name="hole_num" />
<br>
Hole Score: <input type="number" name="hole_score" />
<br>
<input type="Submit" value="Add"/></form>
insert.php:
<?php
include ('db_connect.php');
// Escape user inputs for security
$golfer = mysqli_real_escape_string($link, $_POST['golfer']);
$hole_num = mysqli_real_escape_string($link, $_POST['hole_num']);
$hole_score = mysqli_real_escape_string($link, $_POST['hole_score']);
// Attempt insert query execution
$sql = "INSERT INTO scores (golfer, hole_num, hole_score) VALUES('$golfer','$hole_num','$hole_score')";
mysqli_query($link, $sql);
// Close database connection
mysqli_close($link);
?>
This code works, so when I enter a 'golfer', 'hole_num' and 'hole_score' they correctly get added to the table. As the data entry form stands now though, the user has to enter 1 score at a time and has to specify the hole number. What I'm trying to do is to have 18 input boxes for scores displayed so that they can enter multiple scores at once, but I'd also like to have it so that they don't need to enter the hole number. So basically the hole numbers would somehow be tied to corresponding score input boxes already and then when they attempt to add the data to the db, it inserts golfer, hole_num, and hole_score. Sorry if this is confusing. I couldn't figure out an easy way to explain what I'm trying to do. Let me know if I can clarify something.
I put a simple way to do that for you.
Actually, this answer gives you an idea how to make it. For sure, you can do it more pretty.
Note: I did not test it and wrote it right here.
The form:
<form action="insert.php" method="POST">
Golfer: <input type="text" name="golfer" />
<br>
<table>
<tr><th>Hole Number</th><th>Hole Score</th></tr>
<?php
for ($i = 1; $i <= 18; $i++): ?>
<tr>
<td><?php echo $i; ?></td>
<td><input type="number" name="hole_score[<?php echo $i; ?>]" /></td>
</tr>
<?php endfor; ?>
</table>
<input type="Submit" value="Add"/></form>
The insert file:
// Escape user inputs for security
$golfer = mysqli_real_escape_string($link, $_POST['golfer']);
$values = [];
foreach ($_POST['hole_score'] as $key => $score) {
$score = trim(mysqli_real_escape_string($link, $score));
if (!empty($score)) {
$values[] = "('$golfer','$key','$score')";
}
}
if (!empty($values)) {
$values = implode (' , ', $values);
// Attempt insert query execution
$sql = "INSERT INTO scores (golfer, hole_num, hole_score) VALUES $values";
mysqli_query($link, $sql);
}
// Close database connection
mysqli_close($link);
?>
I have a form which passes data from the index.php to the update.php. The code successfully passed the date of birth variable but it didn't pass the $leadid variable. What is wrong with my code?
part of code in index.php
<form method="post" action="update.php">
<table width="400" border="0" cellspacing="1" cellpadding="2">
<tr>
<td width="100">Lead ID</td>
<td>
<?php
mysql_connect('localhost', 'root', '');
mysql_select_db('test');
$sql = "SELECT leadid FROM table WHERE lead_no ='$lead_no'";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
$leadid = $row[0];
echo $leadid;
?>
</td>
</tr>
<tr>
<td width="100">Date of Birth</td>
<td><input name="birth" type="date" id="birth"></td>
</tr>
</table>
</form>
In my update.php i have POST
$id = $_POST['leadid'];
$birth = $_POST['birth'];
In your code there is no input field for the leadid variable. Try adding a hidden field like this:
<input type="hidden" value="<?php echo $leadid;?>" name="leadid" />
Then, that POST variable should be transferred.
Post does only pass the variables that are wrapped by a html form element like <input> <textarea> or others inside the <form> tag.
Since you did not create such a tag for your $leadid variable it's not available for the update.php file.
Put the following code inside your <form> tag to pass the leadid to the second script.
<input type="hidden" value="<?php echo $leadid;?>" name="leadid" />
Relating to your database query: It is recommended to use prepared statements instead of unprepared. The way you're currently selecting values from your database is a huge security leak and can be abused for SQL injections! I know you're currently using it for local testing but it's important to know that the code could cause security problems.
Here is an example on how to do it with prepared statements:
$mysqli = new mysqli('localhost', 'root', '');
$stmt = $mysqli->prepare("SELECT leadid FROM table WHERE lead_no = ?");
$stmt->bind_param("i", $lead_no); // assuming lead_no is an integer value
$stmt->execute();
$stmt->bind_result($leadid);
$stmt->fetch();
// your lead id is now stored inside $leadid
More information can be found here: http://php.net/manual/de/mysqli.quickstart.prepared-statements.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!