how to store button's value inside while - php

I have two php pages and I'd like to check which button is
checked in the fist one so be able to use its value in the next php
page.The problem is that the submit button is into a while loop so I
can't use different values, may it can be using an i variable but I
don't know how. form of the first page is:
<form name="myForm" action="admin.php" method="post">
<table BORDER=1....... > <?php $link = mysql_connect('localhost', 'root', ''); if
(!$link) {
die('Could not connect: ' . mysql_error()); }
mysql_select_db("nowdeal");
$query = mysql_query("SELECT * FROM application ORDER BY date");
WHILE($rows = mysql_fetch_array($query)):
$date = $rows['date'];
$username = $rows['username'];
$advers = $rows['advers'];
$id = $rows['id'];
echo '<tr>';
echo "$date";
echo "</br>";
echo "$username";
echo "</br>";
echo "$advers";
echo "</br>";
echo "$address";
echo "</td>";
echo '<td align="left">';
echo '<input type="submit" name="action" value="edit" />';
$_SESSION["id"]=$id;
echo '</td>';
echo '</tr>';
endwhile; ?> </table> </form>
in the next page, php code is like:
<?php session_start();
$con = mysql_connect("localhost","root",""); if (!$con) {
die('Could not connect: ' . mysql_error()); }
mysql_select_db("nowdeal", $con);
mysql_query("SET names 'utf8'");
if(isset($_POST['paid']))
{ if($_POST['paid']=="yes") ///is a value from a drop down list
{mysql_query("UPDATE application SET paid='yes' WHERE .....");}
///i want to be like : WHERE id=session[id], but when it works it
takes only //the last id ,so be upadated the last row only
?>

If you want to pass a value over to your new form, insert the value into a hidden form element:
echo '<input type="hidden" name="sessionId" value="' . $id . '"/>';
So that in your next page, you can access this value using:
$_POST['sessionId'];
P.S. You really need to change the way you're accessing your data. Access the data first, preferably using an external class, and then use the data in your rendered output. Don't mix HTML and PHP data logic as if they're best buds.

Related

Getting data to display in a form

I'm trying to use HTML, PHP and MYSQL to pull data from a database and display it in a form (to later be edited). At this point I'm only trying to pull that data and display it in a form. (I'll worry about updating later). I pull the data but nothing displays in my textboxes:
<?php
$con = mysqli_connect("XXXXX"); //removed for privacy
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query="select * from VOLUNTEER";
echo '$query';
$result = mysqli_query($con, $query);
echo "<table>";
if ($result)
{
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
echo '<form method = "post" action="insertvolunteer.php">';
echo '<tr>';
echo '<td>First Name:</td>';
echo '<td>' . '<input type=text name=FirstName' . $row["FirstName"] . '</td>';
echo '<td>' . '<input type=hidden name=VolunteerId' . $row["VolunteerId"] . '</td>';
echo '</tr>';
}
}
echo "</form>";
echo "</table>";
mysqli_close($con);
?>
Text box data needs to be displayed on value as
echo '<td><input type="text" name="FirstName" value="'.$row["FirstName"].'"></td>';
connect.php
<?php
$server = "server";
$user = "user";
$password = "password";
$bd = "yourbd";
$connect = mysql_connect($server, $user, $password);
$connect = mysql_select_db("$bd", $connect);
if (!$connect){
echo mysql_error(); exit;
}
?>
namefile.php
<?php
include('connect.php');
$select = mysql_query("select * from VOLUNTEER");
while ($show = mysql_fetch_assoc($select)):
echo "<table>";
echo "<form method = 'post' action='insertvolunteer.php'>";
echo '<tr>';
echo '<td>First Name:</td>';
echo '<td><input type="text" name="FirstName" value="'.$show["FirstName"].'"></td>';
echo '<td><input type="text" name="FirstName" value="'.$show["VolunteerId"].'"></td>';
echo '</tr>';
echo "</form";
echo "</table>";
endwhile;
?>
When you create an MySQL query, you need to declare this. How?
$var = "SELECT * FROM SOMEWHERE"; wrong
$var = mysql_query("SELECT * FROM SOMEWHERE"); right
'n in echo '<td>' . '<input type=text name=FirstName' . $row["FirstName"] . '</td>';, you need to close the tag. And also have no need of separate <td> of <input>.
Try something like :)
#update I realized that you've got what was wished. Cheers.

PHP deleting from database not working

I'm trying to let the user check off which item to be deleted. When the user check off one or many items and click the Delete button, those data will be erased from the database. I've also added a search box to search for the dvd. The search box works, but the deleting doesn't. This is what it looks like in the browser.
My PHP looks like this (I took out the searching code):
<form action="" method="post">
<p><input type="text" name="search"> <input type="submit" value="Search"></p>
<p><input type="submit" name="deleting" value="Delete"></p>
</form>
<?php
$link = mysqli_connect( $host, $user, $password, $dbname);
if (!$link) {
die('Could not connect: ' . mysqli_connect_error());
}
echo 'Connected successfully<br/>';
//searching code goes here
if (isset ($_POST['deleting']) && isset ($_POST['deleteThese']) )
{
$deleteThese = implode(",", $_POST['deleteThese']);
$queryTwo = "DELETE FROM `$dbname`.`dvds` WHERE `dvds`.`DvdID` IN ($deleteThese)";
$resultTwo = mysqli_query($link, $queryTwo);
}
echo "<table border=\"1\"><tr><th>DvdTitle</th><th>RunningTime</th><th>Delete</th></tr>";
if (mysqli_num_rows($result) == 0)
echo "<tr><td colspan='2'>No records found.</td></tr>";
else {
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>" . $row['DvdTitle'] . "</td>";
echo "<td>" . $row['RunningTime'] . "</td>";
echo "<td>" . "<form>" . "<input type='checkbox' name='deleteThese[]' value='" . $row['DvdID'] . "' >" . "</form>" . "</td></tr>\n";
}
}
echo "</table>";
mysqli_free_result($result);
mysqli_close($link);
?>
Each DvdTitle has an unique Dvd ID, hence the value of each row is the dvd's ID $row['DvdID'].
Adding the parentheses will allow for those ID's to be selected for deletion.
IN($deleteThese)
EDIT
Do not close the form after the submit button. Put that at the end of the code. This will allow the form to include the checkbox values.
<form action="" method="post">
<p><input type="text" name="search"> <input type="submit" value="Search"></p>
<!-- YOUR PHP CODE -->
<p><input type="submit" name="deleting" value="Delete"></p>
</form>
2nd Edit [requested to improve code]
Move the isset on top of the form.
<?php
if (isset ($_POST['deleting']) && isset ($_POST['deleteThese']) )
{
$deleteThese = implode(",", $_POST['deleteThese']);
$queryTwo = "DELETE FROM `$dbname`.`dvds` WHERE `dvds`.`DvdID` IN ($deleteThese)";
$resultTwo = mysqli_query($link, $queryTwo);
}
?>
<form>....
$deletethese might need to have quotes around it.

Updating mysql database using While loop php

This has been bugging me for 3 days now.. I'm new to this and trying to get my head round something. I have a form which involves 3 fields. Firstname, Surname, Marks. I have used a while loop to generate the table from a mysql table. I have used a text box and used the loop to call the text box after the 'ID' so each text box is named uniquely. I am then using a post method to send values to a second page which will update the 'marks' column with the value the user has just put in.. this is where I am finding my problem!
This is the initial page.
<html>
<head><title>Please Enter Your Surname</title></head>
<body>
<center>
<h2><font color=blue>Please Enter Your Surname</font></h2><p>
<form action="insert.php" method="POST">
<?php
$db = mysql_connect("localhost","root","");
if (!$db)
{
do_error("Could not connect to the server");
}
mysql_select_db("session6",$db)or do_error("Could not connect to the database");
$result = mysql_query("SELECT * FROM members ORDER BY id",$db);
$rows=mysql_num_rows($result);
if(!$rows)
{
do_error("No results found");
}
else
{
echo "<table border=3 cellspacing=1 cellpadding=1
align=center bgcolor=lightblue>\n";
echo "<caption><h2><font color=blue> Members Details
</font></h2></caption>\n";
echo "<tr><th>Member Id</th><th>Firstname</th><th>Mark</th></tr>\n";
while ($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td strong>" . $row['Id'] . "</td>";
echo "<td strong>" . $row['Firstname'] . "</td>";?>
<td strong><input type="text" name="<?php echo $row['Id']; ?>" size="20"></td>
<tr>
<?php
}
?><input type="hidden" name="no_of_rows" value="<?php echo $rows; ?>">
<?php
echo "</table>\n";
}
mysql_close($db) or do_error("Could not close connection");
function do_error($error)
{
echo $error;
die();
}
?>
<input type="submit" value="Search">
<input type="reset" value="Reset">
</form>
</body></html>
`
Then the update is done here which is where I seem to be having a problem:
<html>
<body>
<?php
$db = mysql_connect("localhost","root","");
if (!$db)
{
do_error("Could not connect to the server");
}
mysql_select_db("marks",$db)or do_error("Could not connect to the database");
$i=1;
while ($i <= $_POST["no_of_rows"])// or $_POST["No_of_Rows"] from form
{
$insertsql = "UPDATE members SET mark = " . $_POST[$i] . " WHERE Id = " . $row['Id'] . ";";
echo $_POST['$i'];
$i++;
}
?>
</body></html>
When I echo $_POST[$i'] it shows the correct values but does not update the DB, and I'm not about ready to throw my laptop in the bin! ha! I know it is prob going to be something stupid I just can't see what, so any help would be appreciated.
You're missing the single quotes in your update query. This would help:
$insertsql = "UPDATE `members` SET `mark` = '" . $_POST[$i] . "' WHERE `Id` = '" . $row['Id'] . "' ;";
you are also not running the mysql_query query command for the update
lastly you are using the mysql php commands which are deprecated. Use mysqli or pdo instead. and don't forget to escape data in your queries to prevent sql injections
Problem is the single quotes here, forcing to literal '$i' which probably isnt a key in $_POST
echo $_POST["$i"];
No need to use quotes when variable is used:
$_POST[$id];

refresh = on submit in php, how to fix it?

I am creating an insert process in php but I have a problem in my code. when I refresh my page, it will also submit and insert the data.
here is my code :
<form action="/drupal/node/1" method="post">
Name: <input type="text" name="name" />
Price: <input type="text" name="price" />
Minutes: <input type="text" name="minutes" />
<input type="submit" />
</form>
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// some code
mysql_select_db("zain", $con);
if (isset($_POST['name']) && isset($_POST['price']) && isset($_POST['minutes']))
{
$val_name = $_POST['name'];
$val_price = $_POST['price'];
$val_min = $_POST['minutes'];
$max_id_sql = mysql_query("SELECT MAX(id) FROM card_category");
$data = mysql_fetch_array($max_id_sql);
if ($data[0]==0)
{
$val_id = 1;
}
else
{
$val_id = $data[0] + 1;
}
mysql_query("INSERT INTO card_category (id, name, price, minutes) VALUES ($val_id,'$val_name',$val_price,$val_min )");
$_POST['name'] == NULL;
$_POST['price'] == NULL;
$_POST['minutes'] == NULL;
}
$result = mysql_query("SELECT * FROM card_category");
echo "<table border='1'>
<tr>
<th>id</th>
<th>name</th>
<th>price</th>
<th>mins</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['price'] . "</td>";
echo "<td>" . $row['minutes'] . "</td>";
echo "</tr>";
}
echo "</table>";
if (isset($_POST['lastname']))
{
print $_POST['lastname'];
}
mysql_close($con);
?>
my question is, how can I handle when I refresh the page and it will not submit the data?
thanks in advance
When you get the POST submission:
Process the data
Return a Redirect response
Get a GET request from the browser on the URL you redirect to
Respond to that with the HTML
If the browser is refreshed, it will resubmit the GET request which your PHP won't use to modify the database.
This is the POST-REDIRECT-GET pattern. There are some more details in this blog entry (which also has example PHP code in the comments).
How to fix refresh the page do not post the value using php:
if ($_SERVER['HTTP_CACHE_CONTROL']=="")
{
// process the data
}
If you look at $_SERVER['REQUEST_METHOD'] variable, it will say 'POST' when the user submitted data and 'GET' when he did not. So:
if($_SERVER['REQUEST_METHOD']=='POST')
{
// process the data
}
By the way, your code is eminently vulnerable to SQLI attacks ...

Session array keeps overwriting rather than adding to itself

Ran into an issue today that I have not been able to resolve. I am trying to set up a very basic shopping cart for a project. I have a searchable form on the page searchFilm.php that will retrieve a list of 10 films based on your search criteria. This works without issue. I also have an "Add" button beside each film in the list, that also works well.
When I click "Add" it redirects to another page, as intended, called addToCart.php. This page will then display the information for the film added, which is Title and Rental Rate.
This also has worked without issue. Both pages use a central page call dbConnect.php to connect to and select from the database.
The issue I have run into is trying to create a session array that will hold the film_id of each film that I add, and add them to a table. It keeps overwriting the last value that was held in the array. I have commented out almost everything on the addToCart page to try and simplify my debugging. At this point it seems like I am perhaps starting a new session every time I click add.
I will provide the code for each page. I have been trying to figure this out for 4-5 hours without success. Hoping that another pair of eyes might see something I am missing.
Thanks.
dbConnect.php:
<?php
function connect($db)
{
if(!$db)
{
die('Could not connect to the Sakila Database: ' . mysqli_error($db));
}
return $db;
}
function select($db, $table, $id)
{
$result = mysqli_query($db, "SELECT * from " . $table . " where film_id = '" . $id . "'");
if(!$result)
{
die('Could not retrieve records from the Sakila Database: ' . mysqli_error($db));
}
return $result;
}
function searchResult($db, $table, $term)
{
$result = mysqli_query($db, "SELECT * from " . $table . " where description LIKE ('%" . $term . "%') LIMIT 0,10");
if(!$result)
{
die('Could not retrieve records from the Sakila Database: ' . mysqli_error($db));
}
return $result;
}
?>
searchFilm.php:
<html>
<head>
<title>TITLE!</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<?php
include'dbConnect.php';
session_start();
if(isset($_POST['search']))
{
$term = $_POST['search'];
//connect to the database
$db = connect(mysqli_connect("localhost","root","","sakila"));
//retrieve results from the database
$result = searchResult(mysqli_connect("localhost","root","","sakila"),'film', $term);
//echo the title and description of each row
echo "<table border=1 bordercolor=red>";
echo "<tr>";
echo "<th>Title</th>";
echo "<th>Description</th>";
echo "<th>Add To Cart</th>";
echo "</tr>";
while($row = mysqli_fetch_assoc($result))
{
echo "<tr>";
echo "<td>" . $row['title'] . "</td> <td>" . $row['description'] . "</td>";
?>
<td>
<form name="addToCart" action="addToCart.php" method="POST">
<input type="hidden" name="filmID" value="<?php echo $row['film_id']; ?>" />
<input type="submit" name="addToCart" value="Add" />
</form>
</td>
<?php
echo "</tr>";
}
echo "</table>";
mysqli_close($db);
}
?>
<form method="post" action="searchFilm.php" name="">
<p>Search:
<input name="search" type="text" value="" />
</p>
<p>
<input name="" type="submit">
</p>
</form>
</body>
</html>
addToCart.php:
<?php
include('dbConnect.php');
if(isset($_POST['filmID']))
{
$id = $_POST['filmID']; //the item selected
$_session['cart'][] = $id;
foreach ($_session['cart'] as $item)
{ //display contents of array
echo "$item<br />";
}
/*$filmid = $_POST['filmID'];
$_SESSION['cart'][$filmid];
$db = connect(mysqli_connect("localhost","root","","sakila"));
$select = select(mysqli_connect("localhost","root","","sakila"),'film', $filmid);
echo "<table border=1 bordercolor=red>";
echo "<tr>";
echo "<th>Film</th>";
echo "<th>Rental Rate</th>";
echo "</tr>";
while($row = mysqli_fetch_assoc($select))
{
echo "<tr>";
echo "<td>" . $row['title'] . "</td> <td>" . $row['rental_rate'] . "</td>";
echo "</tr>";
}
echo "</table>";*/
}
?>
<html>
<head>
<title>TITLE!</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
click to go back
</body>
</html>
Sorry for the length. Just wanted to make sure that all information was there.
Any insight would be appreciated.
Thanks!
PS. I know my database is very insecure. It's just full of dummy data and run every once in a while on a VM, so I don't really care. :P
1) Try starting the session in addToCart.php
2) As far as I know, $_session won't work, it should be $_SESSION
addToCart.php should call session_start(); and it doesn't as far as I can see.
I believe the issue is that there doesn't appear to be a call to session_start() in the addToCart.php file.
Since you aren't starting a session, none of the previous data is available. Essentially you are creating an array called $_SESSION and adding your cart array to it.
This results in using an array with the same name as PHP's session array, but it is not based off of an existing session.

Categories