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.
Related
I'm trying to populate a Table after a user picks options from a drop down list when this options are picked the table should be populated based on selected options. I'm not sure how can I get this done and I've searched for tutorias etc but nothing helped me. So I'll be glad if someone can help somehow for example with small test codes etc.
I'm using PHP and the options for the drop-down list come from a MySQL-Database so in summary a person will choose a user from Users-drop down list after that a another option from different drop down list and then there's also going to be a date filter after 1, 2 or all 3 are selected a table will be produced based on the selected values.
So far I've no code done because I have no idea how to do it but I guess I need to put all 3 dropdown lists in a form and after submission I should produce the table, but how can I have more than one <select> ..... </select> in a <form> and submit them all simultaneously.
What I've done so far (I know it's unsafe and that mysql_* doesn't exist anymore in PHP7) but please don't criticize it.
UPDATE
//Database query for User drop-down(DD) population.
$sqlDD = " SELECT DISTINCT `user` FROM `users` " ;
$resultDD = mysql_query($sqlDD);
//Database query for Status drop-down(DD) population.
$sqlDDStatus = " SELECT `status` FROM `status` WHERE `id` = 1 OR
`id` = 123 OR `id` = 182 OR `id` = 12 ";
$resultDDStatus = mysql_query($sqlDDStatus);
<form id="form1" name="form1" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<select name="userSelect">
<?php
while($rowDD = mysql_fetch_array($resultDD)):
echo "<option value='" . htmlspecialchars($rowDD['user']) ."'>" . htmlspecialchars($rowDD['user']) ."</option>"; ?>
<?php endwhile; ?>
</select>
<!-- Second DD-list in the same form -->
<select name="Status" style="max-width: 250px;" >
<?php
while($rowDDS = mysql_fetch_array($resultDDStatus)):
echo "<option value='" . htmlspecialchars($rowDDS['status']) ."'>" . htmlspecialchars($rowDDS['status']) ."</option>"; ?>
<?php endwhile; ?>
</select>
<input type="submit" name="submit" value='Find'/>
</form>
//Get the submited data
<?php if(isset($_POST['submit'])): ?>
<?php echo 'This is submitted ' . $_POST['submit']; ?>
<?php endif; ?>
I've added echo 'This is submitted ' . $_POST['submit'];
because i wanted to see what is submitted but all it get's echoed out is only
"Find".
Any ideas how can i get the data submitted from both 's in the form and populate a table based on it ?
UPDATE 2
After getting an answer from other users I saw that my forms handles the data correctly but my question now is how can I use the data from the Submitted DDL Form and populate a table with them? So far I've tried the following:
<?php if(isset($_POST['submit'])): ?>
<?php $result = mysql_query( "SELECT * FROM `users` WHERE `user` =
$_POST['userSelect'] AND (`id` = 1 OR `id` = 18)" );
?>
<?php endif; ?>
and then in the table
<table>
<?php while ($row = mysql_fetch_assoc($result)) :; ?>
<tr>
<td><?php echo $row['user']; ?></td>
<?php endwhile; ?>
</table>
But I just don't get any response when I try it. How can I fix my problem and get the wanted output?
EDIT
I think that i've found my mistake after some research im not able to test the code now but i'm almost positive that you can't use $_POST['userSelect'] in the Database query so i just need to assign $_POST['userSelect'] to some variable before i use it in the query. So far i've gotten useful 1 little useful tip...... so disappointed from stackoverflow .......
This is a basis HTML/PHP page for getting data from the backend to the frontend, this should get you started. Try to print the data (in the while loop on the HTML page).
<html>
<head>
<title></title>
</head>
<body>
<form action="dropdown.php" method="POST">
<select name='options'>
<option>option 1</option>
<option>option 2</option>>
<option>option 3</option>>
</select>
<input type="submit" value="Submit">
</form>
</body>
</html>
<?php
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}else{
if (!empty($_POST)){
if(!empty($_POST['options'])){
$option = $_POST['options'];
$query = "SELECT * FROM table WHERE option='$option'";
$res = $mysqli->query($query);
while($data = $res->fetch_assoc()){
//print data to HTML page
print_f('%s, $s\n', $data['firstname'], $data['lastname']);
}
}
}
}
?>
Your form is probably working, the reason you only get "Find" is because you are printing the value of the submit button.
To get an overview of your form data, try:
echo '<pre>';
print_r($_POST);
echo '</pre>';
You will get the other values of your form by using the name attribute of your <select> with $_POST:
echo $_POST['userSelect'];
echo $_POST['Status'];
By the way, you are using a deprecated extension (written here for example), it is recommended to use MySQLi or PDO (especially PDO is recommended). If you are working with PHP 7, mysql_connect won't work as it has been removed.
And I'm not sure the use of htmlspecialchars() is relevant on each database data you use.
PHP.net - print_r() (See also var_dump())
PHP.net - $_POST
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'];
}
I need to get the list of diagnosed disease of the patient by choosing his name in the combo box, how can I do that? This is my code.
<select name="pname" class="textfields" id="model" style="width:180px;" onchange="getVal1();">
<option id="0" >--Select Patient Name--</option>
<?php
$con = mysqli_connect("localhost","root","","dbnpatient");
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$pnum = $_GET['pnum'];
$query = mysqli_query($con, "SELECT * FROM tblnpatient");
while($row = mysqli_fetch_array($query)){
$pnum = $row['pnum'];
$pname = $row['pname'];
$addr = $row['addr'];
$complaints = $row['complaints'];
?>
<option id="<?php echo $pnum; ?>" data-pnum="<?php echo $pnum; ?>" data-addr="<?php echo $addr; ?>" data-complaints="<?php echo $complaints; ?>" value="<?php echo $pname; ?>"><?php echo $pname; ?></option>
<?php } ?>
This is my code for filtering the table: And i having a trouble in this code because nothings appear in the table when i select the pname
<?php
$con = mysqli_connect("localhost","root","","dbnpatient");
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$pname = $_GET['pname'];
$result = mysqli_query($con,"SELECT * FROM tbldiagnosis WHERE pname='$pname'");
while($row = mysqli_fetch_array($result)) {
echo '<tr class="record">';
echo '<td>'.$row['diagnosis'].'</td>';
}
?>
This can be easily done using ajax. On change of the select, you can trigger a jQuery call to submit the selected value of the box to your PHP page, which has the MySQL to filter the table. The returned result will then be displayed on the page in the designated area.
Main Page:
<select name="pname">
<option value="pname-value">pname-value</option>
</select><br>
<div id="query_results"></div>
<script type="text/javascript">
$(document).ready(function() {
$('select[name="pname"]).on('change',function() {
var curPname=$(this).val();
$.ajax({
type:'GET',
url:'urltotable.php?pname='+curPname,
success:function(data) {
$("div#query_results").html(data);
}
});
});
});
</script>
This is a simplified ajax call that will grab the value from the select box named "pname" and it will send that value to the "url" variable in the ajax call via "GET". This page can then take that variable via GET and use it to get the query results. Upon successful completion, it will display the results inside the div we added with the ID of "query_results".
You can easily customize the select to use your current PHP as listed above, also.
Now for the "urltotable.php" as we specified above, you can use the table query you have above, but just be sure to add the GET line to it so that your pname variable is accessible to the script:
$pname=$_GET["pname"];
For more information about Ajax for full features list, click here to read about Ajax in the jQuery documentation.
I have a database named Data which has a table in which their are different names of products their id and prices, i want to make a web page using php so that i can edit,add and save the items from the web page to the DB and search the names accordingly.
<html>
<head>
<title>Products store</title>
</head>
<body>
<p style="font-size:20px" align="center"> <b>Product Database Editor</b> </p>
<p>
<form method="post">
Enter Product Name: <input type="text" name="pname" id="pname" size="70">
<input type="submit">
</p>
<form method="post">
<select id="opt" name="opt">
<?php
$pname = $_REQUEST['pname'];
// $pname= mysql_real_escape_string($_POST['pname']);
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("Dataentry", $con);
$result = mysql_query("SELECT * FROM products where name like '%$pname%'");
$result_rows = mysql_num_rows($result);
if($pname==NULL)
{
echo "Please enter a product name!";
}
else if($result_rows==0)
{
echo "Product Name does not exist!";
}
else
{
while($row = mysql_fetch_array($result))
{
$name = $row['name'];
echo "<option value='$name_selected'>$name</option>";
//echo ("<option value = '" . $row['name'] . "'>" . $row['id'] . "</option>");
echo $name_selected;
echo "<br />";
}
}
mysql_close($con);
?>
</select>
</form>
</body>
</html>
when i run this code i get the names list in the dropdown but after i select any name, nothing happens, how should i modify my code so that i can select any name from the dropdown and then be able to fetch the price of that particular name to edit it.
please help, coding will be much helpful.
Suppose you have a question like this in your dropdown menu.
Q - How many colors does the US flag has?
Now, from what I understand you want your choice from the drop down menu to appear instantly..
Well, here is a simple select form.
<form method="post">
<select id="opt" name="opt">
<option value="four">four</option>
<option value="five">five</option>
<option value="two">two</option>
<option value="million">million</option>
</select>
And, the JS code:
$(document).ready(function() {
$("#opt").change(function() {
alert($(this).val());
});
});
Now, click her a DEMO with jsFiddle to show you, how it works.
You can copy/paste the codes and include them in your site, this is a simple code, but you if you small knowledge of Javascript you can manipulate the data the way you need it to appear. .
To get a value of an input (this case, from a dropdown) on the fly, you need to use client-side scripting language javascript (or jquery) and use ajax to sent it to server-side, where the code is in PHP.
I want to do this function in php. i have two fields, one is text box and an
other one is drop down list. Drop down list contains values from sql. When one of the value is selected from the drop down list i want the text box to be filled according to the option which is selected.
Following is the drop down list code,
<td>Test Group ID</td>
<td><select id="testgroupid" name="testgroupid" style="column-width:35">
<option value="<?php echo $testgroupid;?>"><?php echo $testgroupid;?></option>
<?php
$x=new con();
$x->connect();
$retval = "select distinct(Id) from testgroupmaster";
$sql1 = mysql_query($retval) or die (mysql_error());
while($res=mysql_fetch_array($sql1, MYSQL_BOTH)){
?>
<option value="<?=$res['Id'];?>"><?=$res['Id'];?></option>
<?
}
?>
</select></td>
According to the id,I want textbox to be filled, How can i do this ? Pls help friends.
<tr>
<td>Test Group Name</td>
<td><input type="text" name="testgroupname" id="zipsearch" value="<?php echo $testgroupname; ?> "></td>
</tr>
If you want your textbox to be filled immediately after the dropdown selection changes, the simplest way is to use javascript:
<td><select id="testgroupid" name="testgroupid" style="column-width:35"
onchange='document.getElementsByName("testgroupname")[0].value =
document.getElementById("testgroupid").options[e.selectedIndex].value;'>
You need JavaScript for that. Use jQuery (or your favorite library) and bind an event listener to the combobox.
Example with jQuery:
$("#myCombo").change(function(e){
$("myTextField").val( $("#myCombo").val() );
});
I have one suggestion which involves jQuery. I do not know if you are using this library, but I am posting it anyway :)
<script type="text/javascript">
$(function() {
$("#testgroupid").change(function{
$("#zipsearch").text($(this option:selected).val();
});
});
</script>
On change event on the dropbown-box, this function fires, and sets the zipsearch-input accordingly.
I am not sure where $testgroupname comes from but I take it you would like to get that value upon selection in the dropdown. If you don´t have the value available on the client you have to retrieve it from the server somehow.
You can´t use PHP to fill the text box since you do not send your posts when an options is selected in the dropdown. There are many alternatives on how to solve this. I would personally use Ajax to fill the textbox without posting to server.
Good place to start:
http://buffernow.com/2012/08/cascading-dropdown-ajax/
html
<select id="testgroupid" name="testgroupid"
style="column-width:35" onChange=filltext();>
javascript
function filltext()
{
var e = document.getElementById("testgroupid");
var group = e.options[e.selectedIndex].text;
document.getElementById("zipsearch").value= group ;
}
your php code is wrong here
<option value="<?=$res['Id'];?>"><?=`$res['Id']`;?></option>
change to
<option value="<?=$res['Id'];?>"><?=$res['GROUP_NAME'];?></option>
Try like this
<script>
function selecteditem(selectedval)
{
jQuery.post("<?php echo JURI::root().'test.php'?>", { id: selectedval },
function(data) {
jQuery('.zipsearch').val(data);
});
}
</script>
//test.php on the root
<?php
$val=$_POST['id'];
//do what you want with $val
//and say final output is in variable $result than echo it
echo $result;
?>
<!--html code here-->
<select id="testgroupid" name="testgroupid" style="column-width:35" onclick="selecteditem(this.value);">
<option value="<?php echo $testgroupid;?>"><?php echo $testgroupid;?></option>
<?php
$x=new con();
$x->connect();
$retval = "select distinct(Id) from testgroupmaster";
$sql1 = mysql_query($retval) or die (mysql_error());
while($res=mysql_fetch_array($sql1, MYSQL_BOTH))
{
?>
<option value="<?=$res['Id'];?>"><?=$res['Id'];?></option>
<?
}
?>
</select>
<input type="text" name="testgroupname" id="zipsearch" class="zipsearch" value="<?php echo $testgroupname; ?> ">
<?php
// Assume $db is a PDO object
$dbh = new PDO('mysql:host=localhost;dbname=populatedropdown', "root", "");
$query = $dbh->query("select * from position"); // Run your query
echo '<form action="populate.php" method="get" name="send3">';
echo '<select name="populate">'; // Open your drop down box
// Loop through the query results, outputing the options one by one
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
echo '<option value="'.$row['name'].'">'.$row['name'].'</option>';
}
echo '</select>';// Close your drop down box
echo '</form>';
?>
<script language="JavaScript">
function send_input1(){
document.send1.input4.value = document.send3.populate.value;
}
</script>
<form name="send1" action=javascript:send_input1()>
<p><input type=submit value=Enter>
</p><input size=30 name="input4">
</form>