Good afternoon StackOverflowers,
I've got a pretty simple question. (I guess:))
Everytime I submit a form with many other input fields it takes the last value of a input field.
I had a similar problem a month ago, but I fixed it somehow.. I just can't fix this problem..
Below you can see my HTML form. (No markup, I know)
<?php
include_once("database.php");
$sql = "SELECT * FROM statements";
$stmt = $db->prepare($sql);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($rows as $row){
echo "<b>";
echo $row['question'];
echo "<br/></b>";
$sqlA = "SELECT * FROM question_answer WHERE question_id =" . $row['id'];
$stmtA = $db->prepare($sqlA);
$stmtA->execute();
$rowsA = $stmtA->fetchAll(PDO::FETCH_ASSOC);
echo "<form id='modify' name='modify' action='modify.php' method='POST'>
<div id='answers'>";
foreach($rowsA as $rowa){
if($rowa['correct_answer'] == 1){
$rowAnswer = $rowa['answer'];
$rowId = $rowa['question_id'];
echo "<input type='text' checked value='" . $rowAnswer . "' name='" . $rowId."' style='background:lightgreen;'><br/>";
echo "</div>";
}
else{
$rowFalseId = $rowa['question_id'];
echo "<input type='text' value='" . $rowAnswer . "' name='" . $rowFalseId."'><br/>";
}
}
}
?>
<input type='submit' name='modify_answers' value="Modify Answers">
</form>
Below you can see my Update Query;
<?php
include_once("database.php");
// foreach($_POST as $val){
// print_r($val);
// }
$sql = "SELECT * FROM statements";
$stmt = $db->prepare($sql);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($rows as $row){
$sqlA = "SELECT * FROM question_answer where question_id =" . $row['id'];
$stmtA = $db->prepare($sqlA);
$stmtA->execute();
$rowsA = $stmtA->fetchAll(PDO::FETCH_ASSOC);
foreach($rowsA as $rowa){
foreach($_POST as $id => $value){
$update = "UPDATE question_answer SET answer = '".$value."' WHERE question_id ='". $id."'";
$stmt = $db->prepare($update);
$stmt->execute();
}
}
}
?>
Everytime It submits to the modify.php file it updates the last value of a input field.
In example if I have 16 input fields, it takes the 4th, 8th, 12th and 16th value of the input field.
So the problem is probaly with the name of the input field, but it could be also the modify.php..
Any help is appericiated! I'm struggling days with this easy problem:(
Thanks in Advance Guys!!
I think I can see what's happening here. You need to move this line...
$rowAnswer = $rowa['answer'];
... so it doesn't fall within your if statement (move them up above it). It's only been assigned, currently, if $rowa['correct_answer'] == 1 evaluates to true.
It is fixed guys! Thanks for your help.. #d0ug7a5 thanks for the answer, that helped me. But my main problem was that I was getting the Question_id instead of the id. Thanks!!
Related
I have a table that displays tuples of books and data about them. There is also a radio button for each row. The idea is that the user selects the button to indicate that they want to order that book.
function displayAllBooks(){
$dbhost = 'localhost:3306';
$dbuser = 'root';
$conn = mysqli_connect($dbhost, $dbuser);
//sql statement to use the database
$sql = 'use BookStore';
mysqli_query($conn, $sql);
$sql = 'SELECT * FROM Author, Books, Written_By, Book_Categories, Assigned_To '
. 'WHERE Author.Author_ID = Written_By.Author_ID'
. ' AND Books.ISBN = Written_By.ISBN'
. ' AND Books.ISBN = Assigned_To.ISBN'
. ' AND Assigned_To.Cat_Code = Book_Categories.Cat_Code'
. ' ORDER BY ALname ASC';
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
echo '<form action = "customerDashboard.php" method = "post">';
echo 'First name:
<input type= "text" name ="CFname"<br>
Last name:
<input type= "text" name ="CLname"<br>';
echo '<p style="text-align:center"><b> All Books </b></p>';
echo '<table class="center">'
. '<tr>'
. '<th>Order</th>'
. '<th>Title</th>'
. '<th>Price</th>'
. '<th>Author</th>'
. '<th>Publication Date</th>'
. '<th>User Review</th>'
. '<th>Category</th>'
. '</tr>';
if (mysqli_num_rows($result) > 0) {
$bookCt = 0;
//mysqli_fetch_assoc associates an array with the results
while ($row) {
$retTitle = $row["Title"];
$retPrice = $row["Price"];
$retALname = $row["ALname"];
$retPubDate = $row["Publication_Date"];
$retReview = $row["User_Reviews"];
$retCat = $row["Cat_Desc"];
//fetch ISBN for each book, for use with the radio buttons to
//place orders
$sql = 'SELECT ISBN from Books WHERE Title="'.$retTitle .'"';
$resultISBN = mysqli_query($conn, $sql);
$rowISBN = mysqli_fetch_assoc($resultISBN);
$currISBN = $rowISBN["ISBN"];
echo"<tr>";
echo '<td><input type="radio" name="'.$currISBN.'"></td>';
echo "<td> $retTitle </td>";
echo "<td> $retPrice </td>";
echo "<td> $retALname </td>";
echo "<td> $retPubDate </td>";
echo "<td> $retReview </td>";
echo "<td> $retCat </td>";
echo "</tr>";
$row = mysqli_fetch_assoc($result);
}
}
else {
echo "0 results";
}
echo "</table>";
echo '<input type="submit" name="placeOrder" value="Order Selected Book">';
echo '</form>';
I've been trying something like onselect="load the button name into a session variable" but I have been unable to implement it.
Each radio button has a name value that is the ISBN (primary key) for the current book thats being put into the table. I want to be able to select a radio button, have that ISBN be stored in a session or global variable, and use that specific ISBN for another method, placeOrder(). After a radio button is checked, the user inputs their first and last name and presses "order selected book", which reloads the page and triggers the placeOrder() function via:
else if(isset($_POST["placeOrder"])){
//for placing orders on a single book
placeOrder();
}
which is present at the beginning of the PHP portion, alongside other function calls.
I'm pretty new to PHP and HTML, so forgive me if the answer is obvious. I could do this if the radio button name was explicit, but since it is changing with each row, I cannot figure it out.
Main idea: How can i capture info that a selected radio button corresponds with so I can use said info in another function?
The answer doesn't have to involve session or global variables, any help is appreciated.
You could an array to represent the radio buttons with the isbn as the index
echo '<td><input type="radio" name="books['.$currISBN.']"></td>';
and then loop through it on the server side
foreach ($_POST['books'] as $isbn => $on){
// do something with $isbn
}
I have been struggling with this for several days now. I have searched on how to update tables and have managed to get as far as to update rows, but only the last one in the table. So now i am trying to get a loop that loops through all the inputs and updates the database with the inputted values. I think the code that needs to be corrected is located near the end of the code
What i want to do:
Get/display database in html table
Change values of certain columns
Update the database table using a submit button which updates every row in database
Here is a picture of what the table looks like in web view:
<?php
//Connect to database
include '../db/connect.php';
?>
<form action='test7.php' method="post">
<table border='1'>
<?php
$result = $MySQLi_CON->query("SELECT * FROM users");
echo "<tr>";
echo "<td colspan='3'>CLASS 1</td>";
echo "</tr>";
//All table rows in database presented in html table
while($row = $result->fetch_array()){
echo "<tr>";
echo "<td><input type='hidden' name='user_id[]' value='".$row['user_id']."' /></td>";
echo "<td>username :<input type='text' name='username[]' value='".$row['username']."' /></td>";
echo "<td>email :<input type='text' name='email[]' value='".$row['email']."' /></td>";
echo "<td>rank :<input type='number' name='rank[]' value='".$row['rank']."' /></td>";
echo "</tr>";
}
echo "<input type='submit' name='update' value='UPDATE' />";
?>
<table>
</form>
<?php
if(isset($_POST['update'])){
$total = count($_POST['rank']);
$user_id_arr = $_POST['user_id'];
$rank_arr = $_POST['rank'];
for($i = 0; $i < $total; $i++){
$user_id = $user_id_arr[$i];
$rank = $rank_arr[$i];
$query = "UPDATE users SET `rank`= '".$rank."' WHERE `user_id`= '".$user_id."'";
$MySQLi_CON->query($query);
header('Location: test7.php');
}
}
?>
When I press the UPDATE button, i get PHP Notice: Array to string conversion in....
It refers to line 30 which is this line:
$query = "UPDATE user SET rank=$_POST[rank][$row] WHERE user_id=$value ";
EDIT: Edited the code above to the working code. Thank you #Frayne Konok for your help.
You are very close.
The issue is that in this code $_POST[rank][$row] - rank is an undefined constant. You need it to be a string, like so $_POST['rank'][$row]. Also, pull the $POST variable out of the query directly to allow typecasting - you should always be very uncomfortable when you see a query that has $_POST data directly:
if(isset($_POST['update'])){
foreach ($result as $row => $value) {
// typecast to a number with decimals below. If you only need integers, than use (int)
$rank = (float)$_POST['rank'][$row];
$query = "UPDATE user SET rank={$rank} WHERE user_id={$value}";
$MySQLi_CON->query($query);
}
}
However, it would be better to use mysqli prepared statements rather than insert the variables directly - as it stand, the above code is vulnerable to SQL Injection attacks.
Your code should be modified to look something like so to prevent sql injection attacks:
if(isset($_POST['update'])) {
$stmt = $MySQLi_CON->prepare("UPDATE user SET rank= ? WHERE user_id= ?");
foreach ($result as $row => $value){
$stmt->bind_param('di', $_POST['rank'][$row], $value);
$stmt->execute();
}
$stmt->close();
}
You did a great mistake here, Why you use the $result in foreach
loop?? FRom where the $result comes?? The $result is the resource
of the sql query.
Try this:
if(isset($_POST['update'])){
$total = count($_POST['rank']);
$user_id_arr = $_POST['user_id'];
$rank_arr = $_POST['rank'];
for($i = 0; $i < $total; $i++){
$user_id = $user_id_arr[$i];
$rank = $rank_arr[$i];
$query = "UPDATE users SET `rank`= '".$rank."' WHERE `user_id`= '".$user_id."'";
$MySQLi_CON->query($query);
}
}
Try with this and let me know if there is any problem.
I am attempting to get the sql row that a user checks with a checkbox and post the id to a script that will save the users selected rows to a db so they can pull "saved" rows at a later data.
Below is my code -- the issue is when I post the checkbox value it is appearing as "1" and I am not sure why this is happening. All checkbox values are appearing as "1".
require('./wp-blog-header.php');
$current_user = wp_get_current_user();
$school = $_POST['school'];
$connection = mysql_connect('198.71.225.63:3306', 'newmslsuper', '');
mysql_select_db('msl_data');
$query = "INSERT INTO searches (ID, school, type) VALUES('$current_user->ID', '$school', '1')";
mysql_query($query);
$search = mysql_query("SELECT * FROM `data` WHERE `school` LIKE '%$school%'");
$count=mysql_num_rows($search);
if ($count==0) {
echo 'Sorry your search for'; echo " $school "; echo 'returned no results. Please try again.';
}
else {
$fields_num1 = mysql_num_fields($search);
echo "<form action='save.php' method='post'>";
echo "<p>Check the box next to a Scholarship you would like to save and hit the SAVE button.<p/><table><tr><th>Save Search</th>";
// printing table headers
for($i=0; $i<$fields_num1; $i++)
{
$field1 = mysql_fetch_field($search);
echo "<th>{$field1->name}</th>";
}
echo "</tr>\n";
// printing table rows
while($row = mysql_fetch_array($search)){
foreach($row as $rowarray)
while($row1 = mysql_fetch_row($search)){
echo "<tr>";
echo "<td><input type='checkbox' value='$rowarray' name='cell'></td>";
// $row is array... foreach( .. ) puts every element
// of $row1 to $cell1 variable
foreach($row1 as $cell1)
echo "<td>$cell1</td>";
echo "</tr>\n";
}
}
}
echo "<input type='submit' value='SAVE'>";
mysql_close(); //Make sure to close out the database connection
Your checkboxes should be as array as they are multiple. The reason why you get them all as 1 as they override each other.
<form method='post' id='form' action='page.php'>
<input type='checkbox' name='checkboxvar[]' value='Option One'>1
<input type='checkbox' name='checkboxvar[]' value='Option Two'>2
<input type='checkbox' name='checkboxvar[]' value='Option Three'>3
<input type='submit'>
</form>
<?php
if(isset($_POST['submit']){
$v = $_POST['checkboxvar'];
foreach ($v as $key=>$value) {
echo "Checkbox: ".$value."<br />";
}
}
?>
TBH, this thing was a mess. The base of your problem was a) only having a single named element (as the other answer pointed out) and b) trying to give it an array as a value. But even after fixing that this was never going to work.
You had your database results inside four separate loops, I don't know what the thinking was there. As well, if you presented me with this web page, I could easily erase your entire database with a single click.
Here's what it looks like after 5 minutes of work. I'd still not call this a reasonable script, but hopefully it will give you something to learn from. You need to make a priority to learn about preventing SQL injection, and the first way to do this is to stop using a database engine that's been unsupported for 5 years. PDO is the easiest alternative as it's built into PHP for nearly a decade now. It provides convenient methods for dumping a result set into an array easily.
<html>
<head>
<link rel="stylesheet" type="text/css" href="results.css">
</head>
</html>
<?php
require('./wp-blog-header.php');
$current_user = wp_get_current_user();
$school = $_POST['school'];
$db = new PDO("mysql:host=198.71.225.63;dbname=msl_data", "newmslsuper", "");
$stmt = $db->prepare("INSERT INTO searches (ID, school, type) VALUES(?,?,?)";
$stmt->execute(array($current_user->ID, $school, 1));
$stmt = $db->prepare("SELECT * FROM `data` WHERE `school` LIKE ?");
$stmt->execute(array("%$school%"));
// put it in an array. presto!
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (count($result) === 0) {
echo "Sorry your search for '$school' returned no results. Please try again.";
}
else {
$fields = array_keys($result[0]);
echo "<form action='save.php' method='post'>";
echo "<p>Check the box next to a Scholarship you would like to save and hit the SAVE button.<p/><table><tr><th>Save Search</th>";
// assume "id" field is first
unset($fields[0]);
// printing table headers
foreach($fields as $field) {
echo "<th>$key</th>";
}
echo "</tr>\n";
// printing table rows
// just one loop
foreach($result as $row) {
echo "<tr>";
// assume the column is named "id"
echo "<td><input type='checkbox' value='$row[id]' name='cell[]'></td>";
unset($row["id"]);
foreach($row as $cell) {
echo "<td>$cell</td>";
}
echo "</tr>\n";
}
echo "<input type='submit' value='SAVE'>";
echo "</form>";
}
?>
I've updated the code but keep getting new errors.
I'm really hoping that someone can help me and look at my code to see what is wrong.
I have a database table on a webpage and I have one edit button and one delete button on each table row. At the moment I'm just trying to get the delete button to work and it will just not delete the row in the database even though I selected that ID. It looks like it's picking up the correct ID.
Can someone tell what is wrong? Below is the code...
<?php
require 'connect.inc.php';
if (isset($_POST['delete']) && isset($_POST['id'])) {
$id = get_post('id');
$query = "DELETE FROM movies WHERE id='.$id.' LIMIT 1";
if (!mysql_query($query, $db_server))
echo "DELETE failed: $query<br>".
mysql_error() . "<br><br>";
}
$query = "SELECT * FROM movies, categories WHERE movies.genre_id = categories.genre_id";
$result = mysql_query($query);
if (!$result) die ("Database access failed:" .mysql_error()) ;
$rows = mysql_num_rows($result);
echo '<table><tr><th>Title</th><th>Release year</th><th>Genre</th><th>Director</th><th>Update</th><th>Delete</th></tr>';
for ($j = 0 ; $j < $rows ; ++$j) {
$row = mysql_fetch_row($result);
//$id = $row[0];
echo '<tr><td>' .$row[1] . '</td>' ;
echo '<td>' .$row[2] . '</td>' ;
echo '<td>' .$row[3] . '</td>' ;
echo '<td>' .$row[4] . '</td>' ;
echo '<td>'."<a href='edit_movie.php?edit=" . $row[0] . "'>Edit</a>".'</td>';
echo '<td><form action="index.php" method="POST">
<input type="hidden" name="delete" value="yes" />
<input type="hidden" name="id" value="'. $row[0] .'" />
<input type="submit" value="Delete" /></form>
</td></tr>' ;
}
echo '</table>';
include 'add_movie.php';
?>
You forget to close action attribute.
You have echo '<td><form action="index.php method="POST"> change it to
echo '<td><form action="index.php" method="POST">
Just to be clear: 'mysql_query' and accompanying commands is deprecated and should really not be used. The OP however stated that it was required for an assignment. The easiest way to replace them is to use 'mysqli_*' instead. For an example using parameter binding to avoid sql-injection:
http://www.php.net/manual/en/mysqli-stmt.bind-param.php
Shouldn't it be:
if (isset($_POST['delete']) && isset($_POST['id'])) {
$id = mysql_real_escape_string($_POST['id']);
...
See this link for some info on 'get_post':
PHP: Having a problem with get_post
The problem there was that the function 'get_post' was defined on the next page of the course literature, wich the asker hadn't noticed.
The variable $_POST['id'] contains the id-value sent from a form via an HTTP POST-request. You check if that value is set, and then you should assign it to '$id' like i wrote.
Your delete sql has wrong quotes
$query = "DELETE FROM movies WHERE id='.$id.' LIMIT 1";
change to either
$query = "DELETE FROM movies WHERE id=".$id." LIMIT 1";
or
$query = "DELETE FROM movies WHERE id=$id LIMIT 1";
Try changing the form action
'<td><form action="index.php" method="POST">
Also check your database connection is properly established
Perhaps this might help for get_post
PHP: Having a problem with get_post
I am going nuts here, I have an array of checkboxes from a form that I am trying to $_POST with PHP. EVERYTHING on my form posts fine except the check boxes. The checkboxes DO post, but in the wrong order. For instance when I want checkbox[0] and checkbox[2] I actually get checkbox[0] and checkbox[1].
I have tried many different ways to get the value of the checkbox, including isset but I still have the same problem. I just need the checkbox value of on to be stored in my database if the checkbox is indeed checked.
My code is below. $in_production is the checkbox. I can provide the code that generates the checkbox too if it is needed.
Thanks in advance.
if ($_GET['action'] == 'Edit_Product'){
include("../dbinfo.php");
$q_id = $_GET['q_id'];
for ($i = 0; $i < count($_POST['p_id']); $i++){
$result = mysql_query('SELECT * FROM products WHERE q_id = '.$q_id);
$num = mysql_num_rows($result);
$p_id = ($_POST['p_id'][$i]);
$in_production = ($_POST['in_production'][$i]);
$p_name = ($_POST['p_name'][$i]);
$p_price = ($_POST['p_price'][$i]);
$p_name_conflict = FALSE;
for ($ii = 0; $ii < $num; $ii++){
$row = mysql_fetch_array($result);
$p_name_conflict_check = $row['p_name'];
$p_id_conflict_check = $row['p_id'];
if($p_name_conflict_check == $p_name &&
$p_id_conflict_check != $p_id){
$p_name_conflict = TRUE;
}
}
if ($p_name_conflict == FALSE){
$query = "UPDATE products SET p_name='$p_name',
p_price='$p_price', in_production='$in_production',
last_modified=CURDATE() WHERE p_id = '$p_id'";
mysql_query($query);
}
else{
$update_failures =+1;
}
}
mysql_close($link);
if($update_failures == 0){
header("Location: Products_Updated.html");
}
elseif ($update_failures != 0){
header("Location: Products_Exist.php?update_failures=".$update_failures);
}
}
P.S. I don't know why but the code block icons are not present on SO right now... so my code is not all pretty. Also, I know my code is horribly inefficient, but I am just trying to get this working right now, then fine tune later. I am open to efficiency suggestions as well, but that is not my primary objective with this question.
EDIT: Here is the form from the HTML...
<form id="form" name="form" method="post" action="/Management/Products/Product_Management.php?action=Edit_Product&q_id=<?php echo "$q_id" ?>">
<?php
include("../dbinfo.php");
$result = mysql_query('SELECT * FROM products WHERE q_id =' . $q_id);
$num = mysql_num_rows($result);
mysql_close($link);
for ($i = 0; $i < $num; $i++){
$row = mysql_fetch_array($result);
$p_id = $row['p_id'];
$p_name = $row['p_name'];
$p_price = $row['p_price'];
$in_production = $row['in_production'];
$date_added = $row['date_added'];
$last_modified = $row['last_modified'];
if($in_production == 'on'){
$checked = 'checked';
}
else{
$checked = '';
}
echo "<div>Product ID# " . $p_id . "<label style=\"font-style:italic\"> (Originally added on " . $date_added . ", last modified on " . $last_modified . ")</label></div><br/>";
echo "<input id=\"p_id" . $p_id . "\" class=\"text\" type=\"hidden\" name=\"p_id[]\" value=\"" . $p_id . "\"/>";
echo "<label>Product Name *</label><br/>";
echo "<div><label style=\"font-style:italic\">(Product still in production <input type=\"checkbox\" name=\"in_production[]\"" . $checked . " style=\"width:15px\"/>)</label></div>";
echo "<input id=\"p_name" . $p_id . "\" class=\"text\" type=\"text\" name=\"p_name[]\" maxlength=\"20\" onfocus=\"on_focus(this)\" onblur=\"on_blur(this)\" value=\"" . $p_name . "\"/><br/><br/>";
echo "<label>Product Price *</label><br/>";
echo "<div><label style=\"font-style:italic\">(Without taxes)</label></div>";
echo "<input id=\"p_price" . $p_id . "\" class=\"text\" type=\"text\" name=\"p_price[]\" maxlength=\"6\" onkeypress=\"return currency(this, event)\" onchange=\"currency_format(this)\" onfocus=\"on_focus(this)\" onblur=\"on_blur(this)\" value=\"" . $p_price . "\"/><br/><br/><br/><br/>";
}
?>
<input class="button" type="button" value="Submit" onclick="product_edit_form_check()"/><br/><br/>
</form>
It would be helpful if you could post some of the HTML-part so we could see how you create your form. It seems you're generating your checkboxes without indexes in your array, so all checkboxes have the name/id "checkbox[]", which is ok if you don't care about the index, but if posted, the array will be numbered starting from "0" and then counting up which is the reason why you'll get "0" and "1" posted, even if "0" and "2" were checked.
Try to give your checkboxes' name/id numbers when generating the HTML, like "checkbox[0]", "checkbox[1]", "checkbox[2]", and so on. So when checkbox 0 and 2 are checked, you should get those values (including the correct index) posted.
The thing you have to bear in mind with HTML checkboxes is that they only POST a value if they are checked. If they are not checked, they don't get posted.
With this in mind, you should give each checkbox a name and then test for it in the POST to detect whether or not it has been passed back.
if (isset($_POST['MyCheckbox'])) {
} // else it wasn't checked!
Show us the HTML for the checkboxes.
Also, you have an SQL injection attack waiting to happen - a user can get any SQL they like onto the end of your query. Something like this illustrates what you should do with untrusted data:
//we're expect a number, so ensure we get one
$q_id = intval($_GET['q_id']);
//get into the habit of quoting query params,
//or better yet, use a wrapper library to help you
$sql="select * from products where q_id='".mysql_real_escape_string($q_id)."'";
If you declare checkbox name like (p_id[]), it's like telling PHP "I'm adding element to an array, enumerate it for me". Like in php $array[] = 't'; If you have several form elements with different names and you want to have synchronised IDs you HAVE to add index because otherwise browser will/may send only selected ones and PHP will enumerate it continuously.
You can specify indexes by using p_id[INDEX] and so on, where index is anything (I suggest numeric or alphanumeric).
Also, checkbox value can be altered and I encourage you to do it. value="1" helps, then you're sure that you get it.
<input type="checkbox" name="p_id[0]" value="1" />
In PHP you'll receive
$_POST['p_id'] ===> array(0 => 1);
et caetera.