Populate form from drop down menu with mysql more efficiently - php

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.

Related

Get selected value and display to another page

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']

search database with php (new to php)

I am brand new to php and I am trying to teach myself to code. I am hoping that someone here can help a newb out. I have a database with 300 client records in it. I am using the following code to access the database. It works great but I am having two issues that I cannot seem to fix.
1) not all clients have a middle name listed and when the middle name field is blank it adds a
2) all 300 client records display at once. Is there a way I can set it to display only 1 to a max of 10 records at a time and use next previous buttons?
additionally, is there a way to search the database? for example a box, and I enter john in it and click search and it returns all records with John? If there is a video or walkthrough that is detailed enough I can figure it out if no one is able to provide me with the code.
Thank you in advance for the help.
<html>
<head>
</head>
<body>
<?php
$con = mysql_connect("localhost", "root", "");
if (!$con) {
die("can not connect: " . mysql_error());
}
mysql_select_db ("new_concepts" ,$con);
if(isset($_POST['update'])){
$UpdateQuery = "UPDATE clients SET ClientID='$_POST[ClientID]', FirstName='$_POST[FirstName]', MiddleName='$_POST[MiddleName]', LastName='$_POST[LastName]', Diagnosis='$_POST[Diagnosis]', Gender='$_POST[Gender]', LevelCare='$_POST[LevelCare]', Counselor='$_POST[Counselor]' WHERE ClientID='$_POST[hidden]'";
mysql_query($UpdateQuery, $con);
};
if(isset($_POST['delete'])){
$DeleteQuery = "DELETE FROM clients WHERE ClientID='$_POST[hidden]'";
mysql_query($DeleteQuery, $con);
};
if(isset($_POST['add'])){
$AddQuery = "INSERT INTO clients (ClientID, FirstName, MiddleName, LastName, Diagnosis, Gender, LevelCare, Counselor) VALUES ('$_POST[uclientid]','$_POST[ufirstname]','$_POST[umiddlename]','$_POST[ulastname]','$_POST[udiagnosis]','$_POST[ugender]','$_POST[ulevelcare]','$_POST[ucounselor]')";
mysql_query($AddQuery, $con);
};
$sql = "SELECT * FROM clients";
$myData = mysql_query($sql,$con);
echo "<table border=1>
<tr>
<th>First Name</th>
<th>Middle Name</th>
<th>Last Name</th>
<th>Client ID</th>
<th>Diagnosis</th>
<th>Gender</th>
<th>Level of Care</th>
<th>Counselor</th>
</tr>";
while($record = mysql_fetch_array($myData)){
echo "<form action=mydata5.php method=post>";
echo "<tr>";
echo "<td>" . "<input type=text name=FirstName value=" . $record['FirstName'] . " </td>";
echo "<td>" . "<input type=text name=MiddleName value=" . $record['MiddleName'] . " </td>";
echo "<td>" . "<input type=text name=LastName value=" . $record['LastName'] . " </td>";
echo "<td>" . "<input type=text name=ClientID value=" . $record['ClientID'] . " </td>";
echo "<td>" . "<input type=text name=Diagnosis value=" . $record['Diagnosis'] . " </td>";
echo "<td>" . "<input type=text name=Gender value=" . $record['Gender'] . " </td>";
echo "<td>" . "<input type=text name=LevelCare value=" . $record['LevelCare'] . " </td>";
echo "<td>" . "<input type=text name=Counselor value=" . $record['Counselor'] . " </td>";
echo "<td>" . "<input type=hidden name=hidden value=" . $record['ClientID'] . " </td>";
echo "<td>" . "<input type=submit name=update value=update" . " </td>";
echo "<td>" . "<input type=submit name=delete value=delete" . " </td>";
echo "</tr>";
echo "</form>";
}
echo "<form action=mydata5.php method=post>";
echo "<tr>";
echo "<td><input type=text name=ufirstname></td>";
echo "<td><input type=text name=umiddlename></td>";
echo "<td><input type=text name=ulastname></td>";
echo "<td><input type=text name=uclientid></td>";
echo "<td><input type=text name=udiagnosis></td>";
echo "<td><input type=text name=ugender></td>";
echo "<td><input type=text name=ulevelcare></td>";
echo "<td><input type=text name=ucounselor></td>";
echo "<td>" . "<input type=submit name=add value=add" . " </td>";
echo "</form>";
echo "</table>";
mysql_close($con);
?>
</body>
</html>
Ok I changed the page to sqli but now when I try to add a record nothing happens and I cannot find the error, I had it working until I started adding more fields then first/last names. I think I have narrowed the error to
if ($stmt = $mysqli->prepare("INSERT clients (FirstName, MiddleName, LastName) VALUES (?,?, ?)"))
{
$stmt->bind_param("ss", $FirstName, $MiddleName, $LastName);
$stmt->execute();
$stmt->close();
}
But I have no idea how to fix it. I found the error!!! Ive only been learning php and MySQL for a week. I still have a lot to learn...
<?php
/*
Allows the user to both create new records and edit existing records
*/
// connect to the database
include("connect-db.php");
// creates the new/edit record form
// since this form is used multiple times in this file, I have made it a function that is easily reusable
function renderForm($first = '', $middle = '', $last = '', $ClientID = '', $error = '', $ID = '')
{ ?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>
<?php if ($ID != '') { echo "Edit Record"; } else { echo "New Record"; } ?>
</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>
<h1><?php if ($ID != '') { echo "Edit Record"; } else { echo "New Record"; } ?></h1>
<?php if ($error != '') {
echo "<div style='padding:4px; border:1px solid red; color:red'>" . $error
. "</div>";
} ?>
<form action="" method="post">
<div>
<?php if ($ID != '') { ?>
<input type="hidden" name="ID" value="<?php echo $ID; ?>" />
<p>ID: <?php echo $ID; ?></p>
<?php } ?>
<strong>First Name: *</strong> <input type="text" name="FirstName"
value="<?php echo $first; ?>"/><br/>
<strong>Middle Name: *</strong> <input type="text" name="MiddleName"
value="<?php echo $middle; ?>"/>
<strong>Last Name: *</strong> <input type="text" name="LastName"
value="<?php echo $last; ?>"/>
<strong>Client ID: *</strong> <input type="text" name="ClientID"
value="<?php echo $ClientID; ?>"/>
<strong>Diagnosis: *</strong> <input type="text" name="Diagnosis"
value="<?php echo $last; ?>"/>
<strong>Gender: *</strong> <input type="text" name="Gender"
value="<?php echo $last; ?>"/>
<strong>Counselor: *</strong> <input type="text" name="Counselor"
value="<?php echo $last; ?>"/>
<p>* required</p>
<input type="submit" name="submit" value="Submit" />
</div>
</form>
</body>
</html>
<?php }
/*
EDIT RECORD
*/
// if the 'ID' variable is set in the URL, we know that we need to edit a record
if (isset($_GET['ID']))
{
// if the form's submit button is clicked, we need to process the form
if (isset($_POST['submit']))
{
// make sure the 'ID' in the URL is valid
if (is_numeric($_POST['ID']))
{
// get variables from the URL/form
$ID = $_POST['ID'];
$FirstName = htmlentities($_POST['FirstName'], ENT_QUOTES);
$MiddleName = htmlentities($_POST['MiddleName'], ENT_QUOTES);
$LastName = htmlentities($_POST['LastName'], ENT_QUOTES);
$ClientID = htmlentities($_POST['ClientID'], ENT_QUOTES);
// check that FirstName and LastName are both not empty
if ($FirstName == '' || $MiddleName == '' || $LastName == '' || $ClientID == '')
{
// if they are empty, show an error message and display the form
$error = 'ERROR: Please fill in all required fields!';
renderForm($FirstName, $MiddleName, $LastName, $ClientID, $error, $ID);
}
else
{
// if everything is fine, update the record in the database
if ($stmt = $mysqli->prepare("UPDATE clients SET FirstName = ?, MiddleName = ?, LastName = ?, ClientID = ?
WHERE ID=?"))
{
$stmt->bind_param("ssi", $FirstName, $MiddleName, $LastName, $ClientID, $ID);
$stmt->execute();
$stmt->close();
}
// show an error message if the query has an error
else
{
echo "ERROR: could not prepare SQL statement.";
}
// redirect the user once the form is updated
header("Location: view.php");
}
}
// if the 'ID' variable is not valid, show an error message
else
{
echo "Error!";
}
}
// if the form hasn't been submitted yet, get the info from the database and show the form
else
{
// make sure the 'ID' value is valid
if (is_numeric($_GET['ID']) && $_GET['ID'] > 0)
{
// get 'ID' from URL
$ID = $_GET['ID'];
// get the recod from the database
if($stmt = $mysqli->prepare("SELECT * FROM clients WHERE ID=?"))
{
$stmt->bind_param("i", $ID);
$stmt->execute();
$stmt->bind_result($ID, $FirstName, $MiddleName, $LastName, $ClientID);
$stmt->fetch();
// show the form
renderForm($FirstName, $MiddleName, $LastName, $ClientID, NULL, $ID);
$stmt->close();
}
// show an error if the query has an error
else
{
echo "Error: could not prepare SQL statement";
}
}
// if the 'ID' value is not valid, redirect the user back to the view.php page
else
{
header("Location: view.php");
}
}
}
/*
NEW RECORD
*/
// if the 'ID' variable is not set in the URL, we must be creating a new record
else
{
// if the form's submit button is clicked, we need to process the form
if (isset($_POST['submit']))
{
// get the form data
$FirstName = htmlentities($_POST['FirstName'], ENT_QUOTES);
$MiddleName = htmlentities($_POST['MiddleName'], ENT_QUOTES);
$LastName = htmlentities($_POST['LastName'], ENT_QUOTES);
$ClientID = htmlentities($_POST['ClientID'], ENT_QUOTES);
// check that FirstName and LastName are both not empty
if ($FirstName == '' || $MiddleName == '' || $LastName == '' || $ClientID == '')
{
// if they are empty, show an error message and display the form
$error = 'ERROR: Please fill in all required fields!';
renderForm($FirstName, $MiddleName, $LastName, $ClientID, $error);
}
else
{
// insert the new record into the database
if ($stmt = $mysqli->prepare("INSERT clients (FirstName, MiddleName, LastName, ClientID) VALUES (?, ?)"))
{
$stmt->bind_param("ss", $FirstName, $MiddleName, $LastName, $ClientID);
$stmt->execute();
$stmt->close();
}
// show an error if the query has an error
else
{
echo "ERROR: Could not prepare SQL statement.";
}
// redirec the user
header("Location: view.php");
}
}
// if the form hasn't been submitted yet, show the form
else
{
renderForm();
}
}
// close the mysqli connection
$mysqli->close();
?>
First, you're not escaping your value attributes. That's probably the cause of your <td that you're seeing.
You've got:
echo "<td>" . "<input type=text name=MiddleName value=" . $record['MiddleName'] . " </td>";
EDIT To demonstrate, the output from this assuming there was no MiddleName ("" should be: <td><input type=text name=MiddleName value= </td>, that doesn't look right. The output from below would be: <td><input type="text" name="MiddleName" value=""></td> now you can see that empty MiddleName value is "" in the HTML - an empty string there as well.
And it should be:
echo "<td><input type=\"text\" name=\"MiddleName\" value=\"" . $record['MiddleName'] . "\"></td>";
That should resolve that issue. Notice that I've placed \" around your attributes. This is not PHP, this is HTML, all attribute values should be enclosed in quotes (I could have used single quotes (') but I prefer double quotes).
The second problem is also a simple solution but again, not PHP - this is a SQL question.
A search is basically where X is like Y. There is actually an operator for this in SQL, LIKE. Now, this example isn't necessarily the most efficient means of searching, but it's definitely useful.
So you're getting the name from the request.
$name = $_REQUEST["query"];
// NEVER DO THE FOLLOWING, NOT EVER. Never trust input from a user, NEVER.
// Don't even think about putting input from the user in a query like this.
// If this input was: "'; DROP TABLE users; --" then you just lost your
// user database.
// $sql = "SELECT * FROM users WHERE FirstName LIKE '%" . $name . "%';";
// Do this instead (with mysqli, not mysql)
$sql = "SELECT * FROM users WHERE FirstName LIKE '%" . mysqli_real_escape_string($conn, $name) . "%';";
// Now search
$results = mysqli_query($conn, $sql);
// Do something with results.
And of course, finally - pagination. You want to paginate. That's a good idea. Here's a simple way to do that. First things first, you'll want to pass a piece of query data along with your request, like ?page=1 on the end of your URLs. This is important.
const PER_PAGE = 30;
if (array_key_exists($_REQUEST, "page")) {
$page = intval($_REQUEST["page"]);
} else {
$page = 1;
}
$offset = PER_PAGE * ($page - 1);
$sql = "SELECT * FROM users LIMIT " . $offset . ", " . PER_PAGE . ";";
$res = mysqli_query($conn, $sql);
// Render your page links:
// leave php, no need to echo every line of HTML.
// Fetch the count of total users with:
// SELECT COUNT(id) FROM users; -- replace id with your primary key field
// and then get your number of pages by '$count / PER_PAGE'
?>
<?php if ($pageCount > 1) { ?>
<div class="pagination">
<?php if ($page > 1) { ?>
Previous
<?php } else { ?>
<span>Previous</span>
<?php } ?>
<?php for ($i = 1; i < $pageCount; $i++) {
if ($page === $i) { ?>
<span class="current-page"><?php echo $i; ?></span>
<?php } else { ?>
<?php echo $i; ?>
<?php }
} ?>
<?php if ($page < $pageCount) { ?>
Next
<?php } else { ?>
<span>Next</span>
<?php } ?>
</div>
<?php } ?>
It is rather ugly with the embedded PHP, my apologies for that. There are other alternatives but I wouldn't want to push too much into one post for a newbie.
EDIT
Obviously you might want to make your pagination smarter. Like, if you have 10 pages you might not want to see: Previous 1 2 3 4 5 6 7 8 9 10 Next if you're onw page 7, you might just want to show: Previous 5 6 7 8 9 Next or some other alternative to keep your list from getting out of control. I didn't demonstrate this, I demonstrated the basic form of Pagination that you can start with and then you can try to modify that with to achieve your desired goals.
For further study I would like to give you some topics to research once you feel you've gotten a grasp on these and other basic tasks.
Prepared statements - while the way I showed you (using mysqli_real_escape_string()) is safer than adding the string directly to the query, prepared statements are even safer than that.
PDO - A seemingly logical next step up the chain of database access is PDO - basically building an ORM for you Database objects (and, I guess, also ORM).
Different pagination techniques, not just of rendering the links. But try your hand with "infinite scrolling." this will require some knowledge of AJAX.
AJAX - need to know some JavaScript and I'd recommend doing this, at first, without something like jQuery.
Something like jQuery, building interactive applications.
From there, I hope you're already finding new things to learn that are referenced when trying to seek the above. This is all basic web development knowledge that would be good to have.
For first part, you don't have quotes outputting correctly.
echo "<td>" . "<input type=text name=MiddleName value=" . $record['MiddleName'] . " </td>";
should be
echo "<td>" . '<input type="text" name="MiddleName" value="' . $record['MiddleName'] . '"/> </td>';
or
echo "<td><input type='text' name='MiddleName' value='{$record['MiddleName']}'></td>";
You can use variables inside double quotes in PHP. You can access array inside if you surround with curly braces, you can also access objects. I feel it is more readable but some like to concatinate.
For second par, you can use GET variables in url, such as index.php?page=1&per_page=10
For searching
$query = "SELECT * FROM clients WHERE FirstName = '$firstName'";
// or
$query = "SELECT * FROM clients WHERE FirstName LIKE '%$firstName%'";
Also, the mysql driver is being removed in the next version of PHP, as it has been deprecated for a while, mysqli should be used instead.
As Xeridea wrote check your html. And if you need to display 10 results change your sql request to
$sql = "SELECT * FROM clients LIMIT 10";
or if you need clienst 10 - 20
$sql = "SELECT * FROM clients LIMIT 10,10";
first 10 - from,
second how many
if you need select clients the name is John
$sql = "SELECT * FROM clients WHERE name = 'John';
Create dinamicly links depends on pages(you can set it in url $_GET request) and use LIMIT to flip pages. Good luck.
You just have to add below code before select query and use my select query.
$SearchString = ''; if(isset($_POST['searchtext']) &&
$_POST['searchtext']!=''){ $searchtext = $_POST['searchtext'];
$SearchString = " WHERE FirstName LIKE "'.$searchtext.' ";
mysql_query($AddQuery, $con); };
$sql = "SELECT * FROM clients".$SearchString;

using data from html forms in php

<form action='main.php' method='POST'>
<select name="Category" class='listbox'>
<?php $cat = mysql_query("select cName from category");
while($drop = mysql_fetch_array($cat))
{
echo '<option value="' . $drop['Category'] . '">' . $drop['cName'] . '</option>';
}
?>
<input type='text' name='search' class='namebox'>
<input type='submit' name='submit' value='Search' class='submitbox'></select>
</select>
i am trying to use this form to create a search engine from my database but just cant get the value from the drop down menu.
$submit = $_POST['submit'];
if($submit)
{
$search = $_POST['search'];
$catval = $_POST['Category'];
echo $catval ;
$searchval = mysql_query("select * from item where iname like '%$search%'and cId in (select cId from category where cName = '$catval')");
while($info = mysql_fetch_array($searchval))
{
echo "Item Name: " . $info['iName'];
}
}
so when i try to search using this method i get no results.
You have placed the selects closing tag wrong :) and I assume you remembered to close your form aswell?
<form action='main.php' method='POST'>
<select name="Category" class='listbox'>
<?php $cat = mysql_query("select cName, Category from category");
while($drop = mysql_fetch_array($cat))
{
echo '<option value="' . $drop['Category'] . '">' . $drop['cName'] .'</option>';
}
?>
</select>
<input type='text' name='search' class='namebox'>
<input type='submit' name='submit' value='Search' class='submitbox'>
</form>
<form action='main.php' method='POST'>
<select name="Category" class='listbox'>
<?php $cat = mysql_query("select cName from category");
while($drop = mysql_fetch_array($cat))
{
echo '<option value="' . $drop['Category'] . '">' . $drop['cName'] .
'</option>';
}
?>
</select>
<input type='text' name='search' class='namebox'>
<input type='submit' name='submit' value='Search' class='submitbox'>
</form>
That should do the trick. Your </select> was in the wrong place.
In the meantime, you might want to look into PDO and bound values instead of using mysql() as it's depreciated (I.E. don't use it anymore) and insecure.

Getting a value by type="hidden"

In my application I'm printing out searchresults. I want to use those searchresults to send an invite to become a member in that group. I'm printing out those userdata but I'm wondering how I can use those data into another function (sendInvite or something). I have to get the user_id of that people ($row['user_id'] but I don't know how I can get it. I'm thinking about type="hidden" but I never used it before.)
PRINT OUT
<div id="InviteGroupMembers">
<form action="<?php echo $_SERVER['PHP_SELF'] . "?group_id=" .$group_id; ?>" method="post">
<div >
<input type="text" name="btnSearch" placeholder="Add people to group"/>
</div>
<div>
<button type="submit" name="">Add</button>
</div>
</form>
<form action="<?php echo $_SERVER['PHP_SELF'] . "?group_id=" .$group_id; ?>" method="post">
<?php
if (is_object($searchresult))
while ($row = $searchresult -> fetch_array()) {
echo "<div><p class='searchresults'><img src='uploads/" . $row['avatar'] . " " . "' alt='' />" . $row['surname'] . " " . $row['name'] . " " . "<input type='submit' name='btnAddMember'class='addFriendToGroup' value='' /><input type='hidden' name='user_id' value='" . $row['user_id'] . "'/></p></div>"; }
?>
</form>
</div>
PHP
if (isset($_POST["btnSearch"])) {
try {
$searchinput = mysql_real_escape_string($_POST['btnSearch']);
$searchresult = $user -> Search($searchinput);
} catch(exception $e) {
$feedback = $e -> getMessage("no results");
}
}
if (isset($_POST["btnAddMember"])) {
try{
$group_receiver_id = mysql_real_escape_string($_POST['user_id']);
var_dump($group_receiver_id);
}
catch(exception $e) {
$feedback = $e -> getMessage("no results");
}
}
input type hidden would work for you in this instance. The output below is based on it being within php code. Other wise you will need to use php tags within the value attribute.
<input type="hidden" name="user_id" value="$row['user_id']"/>
Then you can just get the post variable on form submission

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.

Categories