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...
Related
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'];
}
this codes below came from my friend. i want to make a search under this codes . from this codes , it will display all the users to delete. what i want is i want to put search box and search button . so when i insert user id and press search only then it display which user that i want . where should i put this search text , button and php ? i want to put it under this else if codes . help me. im new :(
else if($_SESSION['jawatan'] == 'ADMIN') { ?>
<li> VIEW PROFILE </li>
<li> VIEW REQUEST </li>
<li>LOG OUT</li>
<li><img src="msc.jpg" width = "240" height ="80"></li>
<form method="get">
<input type="text" name="userid" placeholder="search" />
<inpu type="submit" value="Search" />
</form>
<h3>View User</h3>
<table border='1'>
<tr>
<td><b>#</b></td>
<td><b>Nama</b></td>
<td><b>Email</b></td>
<td><b>Division</b></td>
<td><b>Department</b></td>
<td><b>Delete</b></td>
</tr>
<?php
$i = 1;
$whr="";
if(isset($_GET['userid'])){
$whr.= " and mem_id='".$_GET['userid']."'"; // which field you want. If you want to do search name use LIKE instead =(equal to)
}
$result = mysql_query("SELECT * FROM members WHERE mem_role='USER' ".$whr);
if(mysql_num_rows($result)>0) {
while($row = mysql_fetch_array($result)) {
?>
<tr>
<td>
<?php echo $i; ?>
</td>
<td>
<?php echo $row['mem_name']; ?>
</td>
<td>
<?php echo $row['mem_email']; ?>
</td>
<td>
<?php echo $row['mem_division']; ?>
</td>
<td>
<?php echo $row['mem_department']; ?>
</td>
<td>Delete</td>
</tr>
<?php
$i++;
}
} else {
echo '<tr><td>No results found</td></tr>';
}
?>
</table>
<?php
}
HTML
<form method="get">
<input type="text" name="userid" placeholder="search" />
<inpu type="submit" value="Search" />
</form>
PHP
$whr="";
if(isset($_GET['userid'])){
$whr.= " and mem_id='".$_GET['userid']."'"; // which field you want. If you want to do search name use LIKE instead =(equal to)
}
MYSQL
$result = $result=mysql_query("SELECT * FROM members WHERE mem_role='USER' ".$whr);// add whr variable here
I can tell you the steps:
Create search text field and search button ( wrap in form if you want to do with php only)
on click of button ( that would be submit ), fetch that value from search text box and run query based on that
when results appear , fill the table data with that results using foreach.
hope it helps. Ask me for any issue.
So here is goes. I have a website that has a login. Upon a successful login, a session variable called user is created which contains an array of the userid, username, email and so on. Then from there I have links to other pages. What is giving me trouble is that I have a page called membership.php. This page does a select query for the userid, username, email and generates a table with all of the users. There is also a submit button beside each user that is entitled "Edit". When this button is clicked it redirects to a page edit_account.php. My goal here is when i click on the edit button, a session variable is created containing the userid of that specific user. Then when it redirects to the edit_account.php page I can use that session as part of my select statement to gather data from the table and then edit that users details. Below is a snipit of my code so you can see what I am talking about.
<?php
// First we execute our common code to connection to the database and start the session
require("common.php");
// At the top of the page we check to see whether the user is logged in or not
if(empty($_SESSION['user']))
{
// If they are not, we redirect them to the login page.
header("Location: ../../index.php");
// Remember that this die statement is absolutely critical. Without it,
// people can view your members-only content without logging in.
die("Redirecting to index.php");
}
// We can retrieve a list of members from the database using a SELECT query.
// In this case we do not have a WHERE clause because we want to select all
// of the rows from the database table.
$query = "
SELECT
id,
roleid,
username,
email
FROM user
";
try
{
// These two statements run the query against your database table.
$stmt = $db->prepare($query);
$stmt->execute();
}
catch(PDOException $ex)
{
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code.
die("Failed to run query: " . $ex->getMessage());
}
// Finally, we can retrieve all of the found rows into an array using fetchAll
$rows = $stmt->fetchAll();
if (isset($_POST['Edit'])) {
$_SESSION['id'] = $_POST['id'];
header("Location: edit_account.php");
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Registration</title>
<link href="../../css/default.css" rel="stylesheet" type="text/css" />
</head>
<div id="container">
<div id="header">
<h1>
</h1>
</div>
<div id="navigation">
<ul>
<li>Home</li>
<li>About</li>
<li>Services</li>
<li>Contact us</li>
<li>Logout</li>
</ul>
</div>
<div id="content">
<h2>
Users
</h2>
<form action="" method="post">
<table border="0" align="left" cellpadding="25px">
<tr>
<th>ID</th>
<th>Role ID</th>
<th>Username</th>
<th>E-Mail Address</th>
</tr>
<?php foreach($rows as $row): ?>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['roleid']; ?></td> <!-- htmlentities is not needed here because $row['id'] is always an integer -->
<td><?php echo htmlentities($row['username'], ENT_QUOTES, 'UTF-8'); ?></td>
<td><?php echo htmlentities($row['email'], ENT_QUOTES, 'UTF-8'); ?></td>
<td><input name="Edit" type="submit" value="Edit" /></td>
<td><input name="id" type="hidden" value="<?php echo $row['id']; ?>" /></td>
</tr>
<?php
endforeach;
?>
</tr>
</table>
</form>
</div>
<div id="footer">
Copyright © 2013
</div>
</div>
<body>
</body>
</html>
I believe the problem resides in the block of code:
if (isset($_POST['Edit'])) {
$_SESSION['id'] = $row['id'];
header("Location: edit_account.php");
}
But I have tried many things and nothing seems to work. Also on edit_account.php page I have this code at the top:
echo '<pre>';
var_dump($_SESSION);
echo '</pre>';
which spits out everything in the session variable. When I select the submit button and it redirects, this is the output of the above code.
array(2) {
["user"]=>
array(4) {
["id"]=>
string(1) "1"
["username"]=>
string(5) "admin"
["roleid"]=>
string(1) "1"
["email"]=>
string(15) "admin#admin.com"
}
["id"]=>
NULL
}
Thank you in advance for the help. Anything is greatly appreciated.
The main problem is that you're basically building a form that looks (stripping out all the fluff html):
<form>
<input name="Edit" type="submit" value="Edit" />
<input name="id" type="hidden" value="foo" />
<input name="Edit" type="submit" value="Edit" />
<input name="id" type="hidden" value="bar" />
<input name="Edit" type="submit" value="Edit" />
<input name="id" type="hidden" value="baz" />
etc...
</form>
There's just ONE form, with multiple submit buttons, and multiple copies of the same hidden field with the same name. As such, PHP will use the LAST hidden id value to populate $_POST with. There is NO way for PHP to tell which of the many submit buttons was clicked, or that it should try to use the id value next to that one particular submit button - that's not how HTTP forms work.
You need something more like this:
<table>
<tr><td><form><input type="hidden" name="id" value="foo"><input type="submit"></form></td></tr>
<tr><td><form><input type="hidden" name="id" value="bar"><input type="submit"></form></td></tr>
<tr><td><form><input type="hidden" name="id" value="baz"><input type="submit"></form></td></tr>
etc..
</table>
Note now EACH row has its OWN form, with one submit button and one hidden field within. This way, only that ONE hidden field is submitted, and you'll get the proper id value showing up in your PHP code.
put form code in each table row not on the whole table a single form.
another problem is u login from admin account and u are making changes of the admin session variable so declare another session variable for it.
or u can also put the update code at the starting of the page that either the form is submited so update the user data than no need of making changes in the session variable.
This is great. Thank you Marc B. Exactly what I was looking for. This is the html code:
<?php foreach($rows as $row): ?>
<tr>
<td> <form action="" method="post"> <?php echo $row['id']; ?> </form> </td>
<td> <form action="" method="post"> <?php echo $row['roleid']; ?> </form> </td>
<td> <form action="" method="post"> <?php echo htmlentities($row['username'], ENT_QUOTES, 'UTF-8'); ?> </form> </td>
<td> <form action="" method="post"> <?php echo htmlentities($row['email'], ENT_QUOTES, 'UTF-8'); ?> </form> </td>
<td> <form action="" method="post"> <input name="Edit" type="submit" value="Edit" /> <input name="id" type="hidden" value="<?php echo $row['id']; ?>" /> </form> </td>
</tr>
<?php endforeach; ?>
And I can successfully set a session using:
if (isset($_POST['Edit'])) {
$_SESSION['id'] = $_POST['id'];
header("Location: edit_account.php");
}
But it seems I have ran into another problem:( I also want to add a delete button on each row to delete that user account. Right now this is how it looks:
<td> <form action="" method="post"> <input name="Delete" type="submit" value="Delete" /> <input name="id" type="hidden" value="<?php echo $row['id']; ?>" /> </form> </td>
And the php code used is:
if (isset($_POST['Delete'])) {
// Everything below this point in the file is secured by the login system
// We can retrieve a list of members from the database using a SELECT query.
// In this case we do not have a WHERE clause because we want to select all
// of the rows from the database table.
$query = "
DELETE
FROM user
WHERE
id = :id
";
// The parameter values
$query_params = array(
':id' => $_POST['id']
);
try
{
// These two statements run the query against your database table.
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code.
die("Failed to run query: " . $ex->getMessage());
}
// Finally, we can retrieve all of the found rows into an array using fetchAll
$rows = $stmt->fetch();
// This redirects the user back to the members-only page after they register
header("Location: ../adminindex.php");
// Calling die or exit after performing a redirect using the header function
// is critical. The rest of your PHP script will continue to execute and
// will be sent to the user if you do not die or exit.
die("Redirecting to adminindex.php.php");
}
My problem is the redirection. When I click on the Delete button it actually runs the query but afterwards it just redirects to memberlist.php but the page is blank!? Why would this be happening? Is there something I am missing?I have tried changing the header location with no success. Thanks for the help!
Hi I'm trying to update a single field from a HTML form, for some reason one of the session variables I am passing to the update query is not being accepted. I have already echoed the variable in the page so am fairly certain it exists in memory.
NB, I know my code is horrifically insecure but I'm learning PHP and once I've got the basics working Ill go over it and bring it upto best practice standards.
E2A: If I do var_dump($filename); before trying to run the query it returns string(6) "356/18", after the query it returns NULL. I'm not unsetting the variable anywhere so where could it be going!
Here is my form:
<form method="post" action="">
<p>Your username is: <?php echo $_SESSION['userid'] ?> Your company ID is: <?php echo $companyid['id']?></p>
<h3>Please enter note for file: <?php echo $filename; ?></h3>
<table width="200" cellpadding="5">
<tr>
<th width="18%" align="right" nowrap>Add Note: </th>
<td width="82%" nowrap>
<input type="text" name="note" />
</td>
</tr>
<tr>
<td colspan="2" width="100%" nowrap>
<input type="submit" value="Submit" name="Submit" />
</td>
</tr>
</table>
</form>
Here is my UPDATE query:
$sql = "UPDATE fields SET Notes = ('".mysql_real_escape_string(stripslashes($_REQUEST['note']))."')
WHERE companyId='".$companyid['id']."' AND fileNumber ='".$filename."'";
if($result = mysql_query($sql)) {
echo "<h1>Thank you</h1>Your information has been entered into our database<br><br>";
echo $sql;
echo $filename;
} else {
echo "ERROR: ".mysql_error();
}
} else {
echoing $sql produces the following:
UPDATE fields SET Notes = ('asdasda') WHERE companyId='11' AND fileNumber =''
and here is the bit where I instantiate the POST vars.
include "header.php";
$checkFiles = "checkFiles.php";
// Catches form input from previous page and stores it into session variable called filename for future reference;
$_SESSION['filename']=$_POST['filename'];
$filename = $_SESSION['filename'];
//User id stuff from previous page too;
$userid = $_SESSION['userid'];
$id = mysql_query("SELECT id FROM users WHERE DXNumber='".$userid."'");
// Returns pointer so fetch it as an array and insert it into variable $companyid for later use;
$companyid = mysql_fetch_array($id);
You need to include session_start() on the top of each file.
Just do:
AND fileNumber ='".$_SESSION[filename]."'";
In your update query.
If that doesn't work, make sure that a value for $_SESSION[filename] is being set.
<h3>Please enter note for file: <?php echo $filename; ?></h3>
Create a input box
<input type="text" name="filename" value="<?php echo $filename; ?>"/>
Then filename value will be pass to $_POST array
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...