update MySQL row based on values passed on URL using PHP - php

I am trying to update a Mysql row based on value passed to url of a page.
But i am getting an error Notice: Undefined index: id_store in C:\xampp\htdocs\store\php\update.php on line 29 when i submit the button in html form.
Here is my code:
<?php
require 'db.php';
if(isset($_GET['id_store'])){
$id_store=$_GET['id_store'];
$sql ="SELECT store_name,heading FROM store ORDER BY id_store='$id_store'";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$store_name = $row['store_name'];
$heading = $row['heading'];
}
if(isset($_POST['btn-update']))
{
// variables for input data
$store_name_ = $_POST['store_name'];
$heading_ = $_POST['heading'];
// variables for input data
$id=$_GET['id_store'];
// sql query for update data into database
$sql_query = "UPDATE store SET store_name='$store_name_',heading='$heading_' WHERE id_store='$id'";
$conn->query($sql_query);
// sql query for update data into database
}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>CRUD Operations With PHP and MySql - By Cleartuts</title>
</head>
<body>
<center>
<div >
<form method="post" action="update.php">
<table align="center">
<tr>
<td><input type="text" name="store_name" placeholder="Store Name" value="<?php echo $store_name; ?>" required /></td>
</tr>
<tr>
<td><input type="text" name="heading" placeholder="Store Heading" value="<?php echo $heading; ?>" required /></td>
</tr>
<tr>
<td>
<button type="submit" name="btn-update"><strong>UPDATE</strong></button>
</td>
</tr>
</table>
</form>
</div>
</center>
</body>
</html>
I am getting an error at line $id=$_GET['id_store'];
I think when I submit then button the form is directed to update.php without id_store due to which SQL query gets null value. Is there any thing that i need to change?

Note:
Make sure that there is an id_store value in your URL.
Your first query is wrong. You are using ORDER BY like a WHERE.
You try to update and submit the page, but you didn't pass the id_store. Your form will go to update.php. Remove the URL attribute in your ACTION.
Revised select query code:
$sql ="SELECT store_name,heading FROM store WHERE id_store='$id_store' ORDER BY id_store";
Your form should be:
<form method="post" action="">
So that when your from localhost/store/php/update.php?id_store=36, and you press the submit button, it will still go to localhost/store/php/update.php?id_store=36, instead of just localhost/store/php/update.php.
After you submit, the undefine error will be gone because you retain the id_store in your URL.
And inside your isset(), so that user can't refresh the page and re-submit the form, just put this before the closing bracket:
header("LOCATION:update.php?id_store=".$_GET["id_store"]);

Please check these errors:-
Your all coding stuff along with form code is in one file then why you give action. Remove action attribute from your form.
form method is POST but you are using $_GET change it to $_POST every where you use that.
Also change query like this:-
$sql ="SELECT store_name,heading FROM store WHERE id_store='$id_store' ORDER BY id_store";
Note:- check and do all this thing and tell what happen

Related

PHP passing data using form

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

Why doesn't my PHP code return any results?

When running this PHP code it works, but doesn't return any results - can anyone tell me why please? I have tried checking the code, but as it runs it's not that obvious. So I think it has a problem with the echoing SQL statement.
<!doctype html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Bed & Breakfast</title>
<style type = "text/css">
</style>
</head>
<body>
<form style = "text-align:center; margin-top:200px;"method="POST" action ="">
<span> Hotel Venue<span><input style ="margin-left:20px;" type="number" Name ="HotelVenueRef"/><br/><br/><br/>
<input style = "margin-left:100px;" type='submit' value='HotelVenueRef' Name ="HotelVenueRef"/>
</form>
<?php
if (isset($_POST['HotelVenueRef']))
{
require_once 'connecttodatabase.php';
$sql=" select * from`B&B` where Hotel_Venue_ref =" .$_POST['HotelVenueRef'];
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result))
{
echo'
<td align="center">'.$row['Delegate_Student_uid'] .' </td>';
echo'
<td align="center">'.$row['Name'] .' </td>';
echo'
<td align="center">'.$row['Event_uid'] .' </td>';
echo'
<td align="center">'.$row['Hotel_Venue_ref'] .' </td>';
}
}
?>
</body>
</head>
I know about the injection vulnerability, that's not a problem at the moment. Just need to get it working for now.
$sql=" select * from `B&B` where Hotel_Venue_ref = '" . mysql_escape_string($_POST['HotelVenueRef']) . "'");
$result = mysql_query($sql);
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
Add this code before while statement
I have a feeling that your issue is a result of the fact that you have 2 input elements with the same name (HotelVenueRef).
Here's your form, I've cleaned up the formatting and taken out some style attributes because they're irrelevant to the problem and it's cleaner without them. I've also lower-cased all attribute names (because consistency is key!!)
<form "method="POST" action ="">
<span>Hotel Venue<span>
<input type="number" name="HotelVenueRef"/>
<br/>
<br/>
<br/>
<input type="submit" value="HotelVenueRef" name="HotelVenueRef"/>
</form>
The issue is that you have both an <input type="number"/> and an <input type="submit"/> that have the same name.
When a form submits to PHP, the $_POST array is populated with key-value pairs, where the key is based off the name attribute of the html input element, and the value is the value of that input.
Let's say you set the number input to have a value of 5, and then submit the form.
PHP will now auto-generate the $_POST array. Behind the scenes, it does something like
$_POST['HotelVenueRef'] = 5;
Based off of the value in the number input. Then it goes and does something like
$_POST['HotelVenueRef'] = 'HotelVenueRef';
This is the part you haven't noticed! The submit button also submits to PHP as part of the form, and its value now overwrites the value you're interested in.
The reason you're not getting any results is that your query resolves to look like:
SELECT * FROM `B&B` WHERE `Hotel_Venue_ref`='HotelVenueRef'
With the value of the submit button, instead of the value of the number input.
You can solve your problem by removing the "name" attribute on the submit button, which will prevent its value from submitting to PHP along with the rest of the form. You also have the option of renaming your submit button.

Losing first 2 session variables after calling a 3rd session variable (php 5)

Here's my case (relatively new on php): I got a page "zoek_form.php" where you can enter 2 search values in a form (naam and categorie). When submitted, page "zoek.php" is loaded and a search will be performed (mysql 5.6). To perform the search the 2 values are obtained from the 2 session variables. So far so good, the search works and the rows are retrieved.
But now I want the user to be able to make a sequence (via ORDER BY) in zoek.php, based on a dropdown list. The selected value will be stored in a 3rd session variable. But now the problem: when selecting a sequence and submit the form, the first 2 session values are lost. I'm puzzled why. The essence of session variables is just storing the values and to be able to use them over and over again? (till they are overwritten or killed).
Of course I use session_start(); at the beginning of the php-script (otherwise it would not have worked at all ;-). Any ideas?
Here's zoek_form.php:
<html>
<head>
<title>Zoeken</title>
</head>
<body>
<?php session_start(); ?>
<form name="form1" method="POST" action="zoek.php">
<table border="0">
<tr><td>Naam product:</td>
<td><input type="text" size="50" name="form_naam"></td></tr>
<tr><td>Categorie:</td>
<td><input type="text" size="50" name="form_cat"></td></tr>
<tr><td></td>
<td align = "right"><input type="submit" name="B1" value="Zoeken">
</td></tr>
</table>
</form>
</body>
</html>
Here's zoek.php:
<html>
<head>
<title>Zoeken</title>
</head>
<body>
<form name="form1" method="POST" action="">
<table border="0">
<tr><td>Sorteer op:</td>
<td><select name="form_sort">
<option value="Naam">Naam</option>
<option value="Categorie">Categorie</option>
</select></td>
<td><input type="submit" name="B1" value="Sorteer"></td></tr>
</table>
</form>
<?php
session_start();
require_once 'test_connect.php';
$_SESSION['form_naam'] = $_POST['form_naam'];
$_SESSION['form_cat'] = $_POST['form_cat'];
$_SESSION['form_sort'] = $_POST['form_sort'];
// The 3 lines below were used to check whether session vars were set
// echo $_SESSION['form_naam'];
// echo $_SESSION['form_cat'];
// echo $_SESSION['form_sort'];
function sorteren() {
global $sorteer;
$sorteer = $_SESSION['form_sort'];
if ($sorteer == "Naam") {
$sorteer = "ORDER BY naam";
}
else {
$sorteer = "ORDER BY categorie";
}
}
// Put values from zoek_form.php in vars.
$naam = $_SESSION['form_naam'];
$cat = $_SESSION['form_cat'];
// Check if user has set a sequence. If yes: call function sorteren(),
// if no: leave var $sorteer empty.
if (isset($_SESSION['form_sort'])) {
sorteren();
}
else {
$sorteer = "";
}
// Get rows from table product
$sql = "SELECT * FROM product WHERE naam LIKE '$naam%' OR categorie
LIKE '$cat%' $sorteer";
$result = $conn -> query($sql);
if ($result->num_rows > 0) {
// here code to retrieve rows etc.
}
// Give result free
$result -> free();
// Close connection
$conn -> close();
?>
</body>
</html>
Your form in zoek.php doesn't contain form_naam and form_cat so when you run
$_SESSION['form_naam'] = $_POST['form_naam'];
$_SESSION['form_cat'] = $_POST['form_cat'];
It sets those values to null. If you want to retain those values you could try passing them back again in the form with hidden input fields
<input type="hidden" name="form_naam" value="<?= $_SESSION['form_naam'] ?>">
<input type="hidden" name="form_cat" value="<?= $_SESSION['form_cat'] ?>">
Another way to prevent overwriting the session values is to only change them if the $_POST values are set
if(isset($_POST['form_naam']) && isset($_POST['form_cat'])) {
$_SESSION['form_naam'] = $_POST['form_naam'];
$_SESSION['form_cat'] = $_POST['form_cat'];
}

HTML Form button in PHP While loop

I have a while loop in PHP that selects data from a database
I want to have a complete button for each row returned which, when pressed will run an SQL Query to change the value of the status column of that particular row
my while loop is:
$stmt = $pdo_conn->prepare("SELECT * from messages where status = :status and (assigned_to = :assigned_to1 OR assigned_to = :assigned_to2) ");
$stmt->execute(array(':status' => '', ':assigned_to1' => $user_result["sequence"], ':assigned_to2' => ''));
$records = $stmt->fetchAll(PDO::FETCH_ASSOC);
$i=0;
if(count($records) > 0) {
echo '<tr>
<td colspan="7">You have '.count($records).' Messages</td>
</tr>';
foreach($records as $Messages) {
$i++;
echo '<tr>
<td>'.AdminNameLookup($Messages["assigned_to"]).'</td>
<td>'.$Messages["caller_company"].'</td>
<td>'.$Messages["caller_telephone"].'</td>
<td>'.$Messages["caller_email"].'</td>
<td>'.$Messages["caller_message"].'</td>
<td><input type="submit" name="CompleteMessages['.$i.']" value="" /></td>
</tr>';
}
}
but I'm not too sure on how to handle the PHP on submit?
Before sending data you need to create html form tag. And also you have pass values using input tag values.
format tag should be like this below code.
<form action="" method="">
<input type="" value="">
<input type="submit" name="CompleteMessages['.$i.']" value="" />
</form>
I would use this instead:
<td><input type="submit" name="CompleteMessages" value="'.$i.'" /></td>
You can then get the id with:
$Id = $_POST['CompleteMessages'];
Personally I'd have $i set to $Messages["message_id"] to you can find what Id you have actually submitted.
You also need to wrap everything in a form tag:
<form action="submit.php" method="POST">
...
</form>
If you only want to change the value of the row where you clicked the submit button,
then you will need a unique key for each record.
Lets assume that the messages table has a MessageID column.
One approach would be to call a javascript function.
Let's say your javascript function was called UpdateColumn(ID,ColName,Index)
Here's what would need to be added to each input button (pseudocode)
onclick="UpdateColumn($Messages['MessageID'],'Status',$i)"
Then your javascript will need to lookup value from input CompleteMessages[Index]
The Javascript could call your request php via ajax ...
update.php?MessageID=MessageID&Column=Status&Value=CompleteMessages[Index].value
And finally your php which handles the submit would take the values
using
$MessageID=$_REQUEST["MessageID"];
$Column=$_REQUEST["Column"];
$Value=$_REQUEST["Value"];
Then you will want to run a sql query which updates your database accordingly.

PHP MySQL setting session on submit from table generated by MySQL

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!

Categories