I have a database table as followed:
Using the code below, I display all rows in the text column:
$stmt = $con->query("SELECT * FROM test");
if($stmt->rowCount() > 0) {
$replyid = $row['ID'];
while($row = $stmt->fetch()) {
echo'
'.$row['text'].'
<form method="post">
<input name="testing" type="submit">
</form>
';
}
}
When the user clicks the submit button, the code below is supposed to display the ID corresponding to the column text. For example:
If the submit button next to 'hello' was clicked, the number 2 should display.
If the submit button next to 'adios' was clicked, the number 4 should display.
if(isset($_POST['testing'])) {
echo $replyid;
}
My problem is that only the ID from the first row in the table is displaying. If the user clicks the submit button next to 'bonjour', the number 1 will display (instead of 3!)
You must add hidden field to form with your value:
echo'
'.$row['text'].'
<form method="post">
<input name="replyid" type="hidden" value="'.$row['ID'].'">
<input name="testing" type="submit">
</form>
';
and then display that value from form
if(isset($_POST['testing'])) {
echo $_POST['replyid'];
}
First and foremost, I'd always suggest using a PDO method rather than MySQL/MySQLi
class Connection {
public function __construct() {
return new PDO('mysql:host=X;dbname=X', 'user', 'pass');
}
}
$Con = new Connection;
$Con->Prepare("SELECT * FROM test");
$Con->execute();
foreach($Con->FetchAll() as $row) {
echo $row['id'] . '\n';
}
The above section of code shows the ease of basic SQL statements, for future notice you can also use the PDO bindValue() for secure Queries.
[...]
$Con->Prepare("SELECT * FROM test WHERE id = :paramhere");
$Con->bindValue(":paramhere", 1);
[...]
I hope this helped, you can find more on PDO and SQL from the below links:
PDO Manual
SQL Select Where Clause
EDIT: In addition to best practice, you should use conditional statements where using HTML.
<?php foreach($Con->FetchAll() as $row): ?>
<div class="example">
This is HTML, Your ID is: <?php echo $row['id']; ?>
</div>
<?php endforeach; ?>
try like this, but I'm actually not very sure that this is what you want.
$stmt = $con->query("SELECT * FROM test");
if($stmt->rowCount() > 0) {
while($row = $stmt->fetch()) {
echo'
'.$row['text'].'
<form method="post">
<input name="testing" type="submit" value="'.$row['ID'].'">
</form>
';
}
}
and your echo command should look like this
if(isset($_POST['testing'])) {
echo $_POST['testing'];
}
Related
guys. I was going ok with my app until I got to this type of form, written below. I have 2 items in this table and the ID's are "1" and "2". Even though, if I press "Submit" on the "1" ID item, it prints me "2" every time. Does anyone have a clue what might be the problem? Thank you.
<form method="POST">
<?php
$query = "SELECT * FROM table";
while($row = $query->fetch_array())
{
$id = $row['id'];
?>
<input type="hidden" name="id" value="<?php echo $id; ?>" >
<input type="submit" name="submit">
<?php } ?>
</form>
<?php
if(isset($_POST['submit']))
{
echo $_POST['id'];
}
?>
You're outputting two items into the same form with the same name. When you click the Submit button, it gathers all of the fields in the form based on the name attribute and sends them on to wherever the form is being posted.
If you want to have a button that submits each ID with a separate button, you'd want to try having a new form for each ID. There are other ways of doing this too, but based on your current code, try something like this:
<?php
$query = "SELECT * FROM table";
while($row = $query->fetch_array())
{
$id = $row['id'];
?>
<form method="POST">
<input type="hidden" name="id" value="<?php echo $id; ?>" >
<input type="submit" name="submit">
</form>
<?php } ?>
<?php
if(isset($_POST['submit']))
{
echo $_POST['id'];
}
?>
I have a form that I need to load data in when the user selects a title from a list. When I save a record, I query the database and put the title of the record in a list, with an Edit and Delete link. I'm having difficulty adding an "a href" to the Edit button, and getting the record data to load in the form.
Here's the code for the query:
<div class="content">
<ul class="nav">
<div>Home</div>
<div class="container">
<?php
include('connect-db.php');
$result = mysql_query("SELECT * FROM 'my_table' ORDER BY id ASC");
while($row = mysql_fetch_array($result))
{
$id=$row['id'];
$title=$row['title'];
?>
<div class="show">
<Table width="300" Border="0">
<TR><TD width="260"><?php echo $title; ?></TD>
<TD width="20">EDIT</TD>
<TD width="20">DELETE
</TD></TR>
</Table>
</div>
<?php
}
?>
</div>
Here's the code for the form:
<form name="myForm" action="process.php" method="post">
<div>
<?php
include"connect-db.php";
$sql="SELECT * FROM my_table";
$result=mysql_query($sql);
$rows=mysql_fetch_array($result);
?>
<input type="text" name="title" id="title" value="<? echo $rows['title']; ?>">
<textarea name="chords" id="chords" rows="1" cols="16"><? echo $rows['chords']; ?></textarea>
<textarea name="lyrics" id="lyrics" rows="4" cols="16"><? echo $rows['lyrics']; ?></textarea>
If 'process.php' should show the results of 1 record from the database, you need to change the href of the link and pass the ID to process.php as a GET parameter in the URL. In that page, you need to query using that ID parameter.
change links to:
EDIT
...
DELETE
In process.php, you need to add some if/else statements:
if(isset($_GET["action"]) && isset($_GET["id"]) && is_numeric($_GET["id"])) {
include"connect-db.php";
$sql="SELECT * FROM my_table WHERE id = " . $_GET["id"];
$result=mysql_query($sql);
$rows=mysql_fetch_array($result);
if($_GET["action"] == "edit") {
// output editing form
}
else if($_GET["action"] == "delete") {
// delete
}
}
You could also use different pages for editing and deleting, change your link accordingly if that's what you want. You might want to have a confirmation section before deleting too...
Please note that passing data like this in the URL makes it very vulnerable to hacking. One could easily change the ID or the action.
Also, you need to migrate your code to use PHP's mysqli function instead of mysql. The mysql ones are deprecated...
I have an HTML select where the drop down list is created from a SQL query.
I'm wondering how I can then save the item that the user selects into a PHP variable that I can pass on to other PHP pages.
Thanks.
<tr>
<td>DRM Staff List</td><span class="required">*</span>:<br />
<td>
<select name="unit">
<?php
$conn = oci_connect("username", "password", "url");
$sql = 'select distinct "DRM Primary" from GIS_DATA_LOAD where "DRM Primary" is not null order by "DRM Primary" asc' ;
$stid = oci_parse($conn, $sql);
$success = oci_execute($stid);
echo $success;
while ($row = oci_fetch_array($stid, OCI_RETURN_NULLS+OCI_ASSOC))
{
echo "<option value=\"unit1\">" . $row['DRM Primary'] . "</option>";
}
?>
</select>
</td>
</tr>
Add you code inside the form tag as below and make a form submit action ($_POST or $_GET) using javascipt as onselect.
Since the code is on client side so you have to for sure submit it to the server to save the selected option in a php variable.
<tr>
<td>DRM Staff List</td><span class="required">*</span>:<br />
<td>
<form action="" method="POST" name="myform">
<select name="unit" onchange="this.form.submit()>
<?php
$conn = oci_connect("username", "password", "url");
$sql = 'select distinct "DRM Primary" from GIS_DATA_LOAD where "DRM Primary" is not null order by "DRM Primary" asc' ;
$stid = oci_parse($conn, $sql);
$success = oci_execute($stid);
echo $success;
while ($row = oci_fetch_array($stid, OCI_RETURN_NULLS+OCI_ASSOC))
{
echo "<option value=\"unit1\">" . $row['DRM Primary'] . "</option>";
}
?>
</select>
</form>
</td>
</tr>
// now to save the submitted form as value in a php we will use the following code
<?php
if(isset($_POST['myform']))
$selected_unit=$_POST['unit'];
?>
you can also use onselect() function ... not sure about that..
Hope it helps..thanks :)
You might want to set a unique value for each option, else there's no telling which option was actually selected.
When you submit the form PHP will internally generate a super global array. This, as it sounds, is global and can be accessed anywhere within the script execution via variables:
$_POST
$_GET
So after submitting your form, if it is a HTTP post request then you should find your value like this:
echo $_POST['unit']; // Unit 1 etc
There are other 'superglobals'. See the documentation for more information.
Its not possible to set a variable from client side.
Using AJAX to submit the form may help. It won't require the page reload.
So, I have a page with a bunch of workorders on it. Each workorder is a row in a single table, and gets put on the page with a while() statement.
I'm trying to update each row with a simple form that I put inside the while(), and an UPDATE/WHERE statement to actually add the information to the table.
Instead of adding it to the specific row, it adds it to Every row. The only thing I can think of is that my WHERE condition is wrong, but I can't seem to figure it out. Maybe it just needs fresh eyes, or maybe I'm heading in Completely the wrong direction.
Also, any specific instructions on security, a better way to do it, etc. would be very helpful. I'm learning PHP on the fly and could use a helping hand. :)
<?php
$query = "SELECT * FROM client_information";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$which_ad = $row['ID'];?>
<b>Name:</b> <? echo $row['billing_name']; ?> <br>
<b>Job Type:</b> <? echo $row['job_type']; ?> <br>
<b>Size:</b> <? echo $row['size']; ?> <br>
<b>Text:</b> <? echo $row['text']; ?> <br>
<b>Notes:</b> <? echo $notes; ?> <br>
<br><br>
<form action="small_update.php" method="POST">
<strong>Email Message:</strong><br>
<textarea rows="8" cols="60" name="email_message"></textarea>
<input type="submit" name="submit" value="Submit"></form>
<?
$email_message = htmlspecialchars ("{$_POST['email_message']}", ENT_QUOTES);
if (mysql_errno() != 0) {
die(mysql_error());
}
mysql_query(
"UPDATE client_information
SET email_message='$email_message'
WHERE ID='$which_ad'"
);
if (mysql_errno() != 0) {
die(mysql_error());
}
}
?>
You don't specify the id in your form:
<form action="small_update.php" method="POST">
<strong>Email Message:</strong><br>
<textarea rows="8" cols="60" name="email_message"></textarea>
<input type="hidden" name="id" value="<?php echo $which_ad; ?>">
<input type="submit" name="submit" value="Submit">
</form>
you need to also make sure you know what id was submitted:
"UPDATE client_information
SET email_message='$email_message'
WHERE ID='$_POST['id']'"
Of course, you're wide open to attacks like this as everyone else is saying. You need to look into mysqli or pdo to sanitize your input...
Ans also upon inspection you're evaluating your post data in the loop. Don't do that. Just do your evaluation before everything else is processed on the page...
<?php
if($_POST)
{
//run processing here
}
// do your fetch code here and display the forms...
I would like some help with my code. I've already searched answered questions on this site but haven't found anything that works unfortunately. I'm doing a website where you can write, save, delete and update notes. Now I'm trying to fix an update button were you can change a posted note using its unique ID. The update button is on a separate page from the notes, and you choose the ID of posted notes using using a drop-down menu showing the existing IDs in my database table. You choose it, write a new note and then click update.
This is my current code:
<li id="id_number"><label>ID number: <select name="id_number">
<option value =" ">Select number</option>
<?php $query = "SELECT * FROM notes";
$result2 = mysql_query($query);
while ($row = mysql_fetch_array($result2)) {
$id = $row ['id'];
$select = "";
if ($id == $idID2) {
$select = "selected" ;
}
?><option <?php print $select ?> value="<?php print $id; ?>"><?php print "$id";
?></option><?php
}
?>
</select>
</label></li>
<li id="note">New note:</li>
<li id="note"> <textarea rows="10" cols="30" name="note" value="<?php print $note;?>"/></textarea></li>
<li id="send"><input type="submit" name="submit" value="Update!"/></li>
</ul>
</form>
<?php
$id= $_POST ['id'];
$subject= $_POST ['subject'];
$note= $_POST ['note'];
?>
<?php
if (isset($_POST['submit'])) { //validates the data
$error="0";
if ( $note == "" ) {
$error++;
$wrong .= "<p> You forgot to write a new note.</p>";
}
if ($error > 0) {
print "<p><strong>You have made these errors:</strong></p>";
?>
<?php print $wrong; ?>
<?php
}
//if no errors
else {
$note = mysql_real_escape_string($note);
$note = htmlspecialchars($note);
$id = mysql_real_escape_string($id);
$id = htmlspecialchars($id);
$date = date("j/n, Y, H:i");
$query = ("UPDATE notes SET note='$note' WHERE id='$id'");
$result = mysql_query($query) or die (mysql_error());
if ($result) {
print "<p>Note updated!</p>";
}
}
}
?>
When choosing an existing ID and change the note and clicking update it says "Note updated" but the note in the database remains the same.
What am i doing wrong?
$id = $_POST['id']
should be
$id = $_POST['id_number']
As far as I can tell, you aren't referring to any input with name "id".
Instead of answering "what am I doing wrong?" I'm going to answer "How can I do this right?"
Your interface is set up in a fashion that is not intuitive. The dropdown should contain information about the notes (the ID is sufficient here), and when the user selects a note from the dropdown, your text input should be populated with what's already there. If no note ID is selected from the dropdown and the user clicks "update", the system should insert a new note record (if the text area has content).
So, how do we do this? First let's set up our form:
<form action="" method="post">
<select id="noteIds" name="noteId">
<option value=''>Select a Note</option>
<option value='1'>1</option>
<option value='2'>2</option>
.
.
.
</select> <br />
<textarea name="noteContents" id="noteContents"></textarea><br />
<input type="submit" value="Update" />
</form>
Now that we have our form set up we can control the behavior of the elements using jQuery:
<script language="javascript" type="text/javascript">
$("#noteIds").on('change', function() {
$.post("getNoteInfo.php", {
noteId: $(this).val()
}, function(data) {
$("#noteContents").html(data);
}
);
});
</script>
The above code will set the output of geNoteInfo.php to the contents of your textarea.
Next let's work on getNoteInfo.php (in pseudo-code).
<?php
$noteId = $_POST['noteId'];
$noteText = // retrieve note text from database where note ID = $noteId
echo $noteText;
Now, when the user clicks Update, check to see that an ID is selected. If the ID was selected, update that row. If no ID has been selected, insert a new row IF there is text in the textarea.
NOTE: You should stop using mysql_* functions. They're being deprecated. Instead use PDO (supported as of PHP 5.1) or mysqli (supported as of PHP 4.1). If you're not sure which one to use, read this SO article.