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.
Related
This select will display a list of users with their ID, fname and lname.
How to do, so if I chose on user from the list, and then I click the button "send", it will redirect to another page, and in the second page it will display the user that I selected?
$stid = oci_parse($conn, "select user_id, fname,lname from users");
oci_execute($stid);
echo "<select size = '5'>";
while (($row = oci_fetch_array($stid,OCI_ASSOC+OCI_RETURN_NULLS))!= false) {
echo "<option value=$row[user_id]>".$row['user_id'] . " " .$row['fname']
. " " . $row['lname'] . "</option>";
}
echo "</select>";
<form method="post" action="send.php">
<input type="submit" name="send" value="send">
</form>
You should set the form method to get rather than post. You also need to give the select element a name attribute, so it's value is sent.
<form method="get" action="send.php">
<?php
$stid = oci_parse($conn, "select user_id, fname,lname from users");
oci_execute($stid);
echo "<select name='id' size = '5'>";
while (($row = oci_fetch_array($stid,OCI_ASSOC+OCI_RETURN_NULLS))!= false){
echo "<option value=$row[user_id]>".$row['user_id'] . " " .$row['fname'] . " " . $row['lname'] . "</option>";
}echo "</select>";
?>
<input type="submit" name="send" value="send"></p>
</form>
Submitting your form will send you browser to:
send.php?send=send&id=<id>
Then, in send.php you can get the user id from the $_GET superglobal.
$userId = $_GET['id']
Evening everyone, I have a page that updates a mysql table record/row using a form. When you go to page xyz.php there is a drop down list. Upon selecting the artID from the drop down list and hitting submit, a form is displayed. The form is pre-populated using artId and matching to the mysql query that is pulled from at the beginning of the script. The code below works perfectly.
My question however is, can this be down more efficiently? Specifically the pre-populated form. I'm using an if statement to find the index of the array that the 'artId' is nested in. Then using the vars of the indexed array to populate the form. This seams it would be pretty taxing if the sql query is large.
I'm also using 2 foreach constructs for the same data. I'm still working on how to eliminate one of them without botching up the whole form.
Any suggestions or thoughts for a direction to run to are much appreciated as always.
Thanks
JR
$sqllst = "SELECT artId, artName, artSummary, artContent FROM article";
$dba = new PDO($dsn, $usr, $pas);
$dba->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$getlist = $dba->prepare($sqllst);
$getlist->execute();
$res = $getlist->fetchAll();
if ($_SERVER['REQUEST_METHOD'] != 'POST') {
echo '<form method="post">
<select name="dro">';
foreach ($res as $red){
echo '<option name="dro" value=' . $red['artId'] . '>ID# ' .$red['artId'] . '-' . $red['artName'] . '</option>';
}
echo '</select>
<input type="submit" value="Select Article">
</form>';
} else {
$arrayIndex = $_POST ['dro'];
foreach ($res AS $searchValue) {
if ($searchValue['artId'] == $arrayIndex) {
$name = $searchValue['artName'];
$sumry = $searchValue['artSummary'];
$cont = $searchValue['artContent'];
}
}
echo "<form method=post id=setArticle>
Article Id: <input type=text name=id value=" . $arrayIndex . "><br>
Article Name: <input type=text name=name value=" . $name . "><br>
Article Summary: <input type=text name=sum value=" . $sumry . "><br>
Article Content: <textarea name=content rows=4 cols=10>" . $cont . " </textarea><br>
<input type=submit value=SUBMIT>
</form>";
}
Yours else statement is quite strange. Why there isn't parametrized query ?
Foreach statement is useless if you use something like this:
$sth = $dba->prepare('SELECT artId, artName, artSummary, artContent FROM article WHERE artId = :id');
$sth->bindValue(':id', $_POST ['dro'], PDO::PARAM_INT);
$sth->execute();
Prepare statement to avoid SQL injections.
So now it should looks like that:
$sqllst = "SELECT artId, artName, artSummary, artContent FROM article";
$dba = new PDO($dsn, $usr, $pas);
$dba->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
if ($_SERVER['REQUEST_METHOD'] != 'POST') {
$getlist = $dba->prepare($sqllst);
$getlist->execute();
$res = $getlist->fetchAll();
echo '<form method="post">
<select name="dro">';
foreach ($res as $red){
echo '<option name="dro" value=' . $red['artId'] . '>ID# ' .$red['artId'] . '-' . $red['artName'] . '</option>';
}
echo '</select>
<input type="submit" value="Select Article">
</form>';
} else {
$sth = $dba->prepare('SELECT artId, artName, artSummary, artContent FROM article WHERE artId = :id');
$sth->bindValue(':id', $_POST ['dro'], PDO::PARAM_INT);
$sth->execute();
$result = $sth->fetch(PDO::FETCH_ASSOC);
//Please remember to purify everything which is provided by users
echo "<form method=post id=setArticle>
Article Id: <input type=text name=id value=" . $result['artId']. "><br>
Article Name: <input type=text name=name value=" . $result['artName']. "><br>
Article Summary: <input type=text name=sum value=" . $result['artSummary']. "><br>
Article Content: <textarea name=content rows=4 cols=10>" . $result['artContent']. " </textarea><br>
<input type=submit value=SUBMIT>
</form>";
}
O course the next step is to separate view from controller. It looks very ugly when everything is in one file.
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];
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.
I would like to apologize if the duplicate of this question exist. i tried to find and could find anything here that could solve my problem..
I am using a form to get the input and update it in the mysql database, and then retrieve the records in the html form, and have defined the code for deleting the records individually through hyperlinks. however i want to do more, i want to use the checkboxes to delete the multiple records.
my code goes like this.
<?php
//include connection string
include('connection.php');
?>
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="post"/>
Username : <input type="text" name="user"/><br />
Password : <input type="password" name="pass"/><br />
<input type="submit" name="submit" value="Send"/>
</form>
<?php
// query to insert into database
if(isset($_POST['user']) && isset($_POST['pass'])) {
$user = empty($_POST['user']) ? die(mysql_error()) : mysql_escape_string($_POST['user']);
$pass = empty($_POST['pass']) ? die(mysql_error()) : sha1(mysql_escape_string($_POST['pass']));
$query = "INSERT INTO users(name, pass) VALUES ('$user', '$pass')";
$result = mysql_query($query) or die(mysql_error());
}
if(isset($_GET['id'])) {
//query to delete the records
$query = "DELETE FROM users WHERE id = " . intval($_GET['id']);
$result = mysql_query($query);
}
//query to retrieve records
$query = "SELECT * FROM users";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0 ) {
echo "<table cellpadding=10 border=1>";
while ($row = mysql_fetch_row($result)) {
echo "<tr>";
echo "<td>" . $row[0] . "</td>";
echo "<td>" . $row[1] . "</td>";
echo "<td>" . $row[2] . "</td>";
echo "<td>delete";
echo "</tr>";
}
echo "</table>";
}
?>
i would like you to know that i am a newbie to programming world and i am not so sure of how exactly html checkbox work and how do i use it to delete the multiple records. i want to know what extra code do i have to write for it, and i would appreciate a lot if someone explains me that extra code in brief..
thank you..
This is probably a good time for another form:
<?php
// query to insert into database ...
// ... etc...
if(isset($_POST["formDeleteSelected"])) {
//query to delete the records
$query = "DELETE FROM users WHERE id IN (" . implode(", ",$_POST["rowid"]) . ")";
$result = mysql_query($query);
header("Location: mycode.php"); // just so 'refresh' doesn't try to run delete again
exit();
}
?>
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="post">
<?php
//query to retrieve records
$query = "SELECT * FROM users";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0 ) {
echo "<table cellpadding=10 border=1>";
while ($row = mysql_fetch_row($result)) {
echo "<tr>";
echo "<td><input type="checkbox" name="rowid[]" value=\"" . $row[0] . "\" /></td>";
echo "<td>" . $row[0] . "</td>";
echo "<td>" . $row[1] . "</td>";
echo "<td>" . $row[2] . "</td>";
echo "</tr>";
}
echo "</table>";
}
?>
<input type="submit" name="formDeleteSelected" text="Delete Selected" />
</form>
Or something like that (I haven't actually tried that code so there may be a typo). Also note that you should make sure to sanitize any form/get inputs for SQL Injection (plenty of information on that in other Stack Overflow questions).
First of all you need a checkbox and the id you want to delete:
<input id="delete" type="checkbox" name="delete" /><label for="delete">Delete user</label>
<input type="hidden" name="user_id" value="12345" />
You can then test if the checkbox has been set and then manually set the GET parameter to reuse your existing code:
if(isset($_POST['delete'])){
$_GET['id'] = $_POST['user_id'];
}
That's not the most elegant solution but a really simple one that should work with your code.
try an SQL query with a list of IDs
... WHERE id=$sentIds[0] OR id=$sentIds[1] OR ...
or use a set operation
... WHERE id IN ($i1,$i2 ... );
You sure have to send ids in the form for this to work, but You know that ;)