am developing an online application and i have a php search script that fetches required info from the database.I have managed to include a delete and update buttons to the script such that when a user searches for an item a table display of required data is displayed but then i dont know how to bind the buttons to their functionality. Am new with Php so any help is appreciated. Here is my search code...
<?php
// Get the search variable from URL
$var = #$_GET['s'] ;
$trimmed = trim($var); //trim whitespace from the stored variable
// rows to return
$limit=15;
// check for an empty string and display a message.
if ($trimmed == "")
{
echo "<p>Please enter a search value...</p>";
exit;
}
// check for a search parameter
if (!isset($var))
{
echo "<p>We dont seem to have a search parameter!</p>";
exit;
}
//connect to database
mysql_connect("localhost","root",""); //(host, username, password)
//specify database **
mysql_select_db("archive_sys") or die("Unable to select database"); //select which database we're using
// Build SQL Query
$query = "select * from tbl_archivingdetails where archiveid like \"%$trimmed%\" or buildingid like \"%$trimmed%\" or branchid like \"%$trimmed%\" or study like \"%$trimmed%\" or batchnumber like \"%$trimmed%\" or quantity like \"%$trimmed%\" or archivedate like \"%$trimmed%\" or archivedby like \"%$trimmed%\" or archiveeemail like \"%$trimmed%\" or archiveephone like \"%$trimmed%\" or expecteddestructiondate like \"%$trimmed%\" or currarchholderproj like \"%$trimmed%\" or currexpretdate like \"%$trimmed%\" or returnedby like \"%$trimmed%\" or status like \"%$trimmed%\"";
$numresults=mysql_query($query);
$numrows=mysql_num_rows($numresults);
// next determine if s has been passed to script, if not use 0
if (empty($s)) {
$s=0;
}
// get results
$query .= " limit $s,$limit";
$result = mysql_query($query) or die("Couldn't execute query");
// display what the person searched for
echo "<h2>You searched for: "" . $var . ""</h2>";
// begin to show results set
echo "Results: ";
$count = 1 + $s ;
//the begining of a table with a header
echo " <table border=2>";
echo "<tr align=center>";
echo "<th> Check Code </th>";
echo "<th> Archive ID </th>";
echo "<th> Building ID </th>";
echo "<th> Branch ID </th>";
echo "<th> Study </th>";
echo "<th> Batch Number </th>";
echo "<th> Quantity </th>";
echo "<th> Archive Date </th>";
echo "<th> Archived By </th>";
echo "<th> Archivee Email </th>";
echo "<th> Archivee Phone </th>";
echo "<th> Expected Destruction Date </th>";
echo "<th> currArchHolderProj </th>";
echo "<th> Current Exp Return Date </th>";
echo "<th> Returned By </th>";
echo "<th> Status </th>";
//echo "<th> Action </th><tr><td><input type='submit' name='Submit' value='Delete' /> | <input type='submit' name='Submit' value='Update' /> </td></tr>";
echo " </tr>";
// now you can display the results returned
while ($row= mysql_fetch_array($result)) {
$title = $row["archiveid"];
$title1 = $row["buildingid"];
$title2 = $row["branchid"];
$title3 = $row["study"];
$title4 = $row["batchnumber"];
$title5 = $row["quantity"];
$title6 = $row["archivedate"];
$title7 = $row["archivedby"];
$title8 = $row["archiveeemail"];
$title9 = $row["archiveephone"];
$title10= $row["expecteddestructiondate"];
$title11 = $row["currarchholderproj"];
$title12 = $row["currexpretdate"];
$title13 = $row["returnedby"];
$title14 = $row["status"];
echo" <tr>";
echo "<td><input type='checkbox' name='checkbox' value='".$row['archiveid']."' id='checkbox'/> </td> <td>".$title."</td> <td>".$title1."</td><td>".$title2."</td><td>".$title3."</td><td>".$title4."</td><td>".$title5."</td> <td>".$title6."</td><td>".$title7."</td><td>".$title8."</td><td>".$title9."</td><td>".$title10."</td> <td>".$title11."</td><td>".$title12."</td><td>".$title13."</td><td>".$title14."</td>" ;
echo " </tr>";
}
echo "<tr><tr> <td><input type='submit' name='Submit' value='Delete' /></td> | <td><input type='submit' name='Submit' value='Update' /> </td></tr>";
echo " </tr>";
echo " </table>";
//break before paging
echo "<br />";
?>
You could do this, change input buttons to links and append the archiveid to the link.
echo "<th> Action </th><tr><td><a href='delete.php?archiveid=" . title . '>Delete</a> | <a href='update.php?archiveid=" . title . '>Update</a> </td></tr>";
Now these links will send you to delete.php and update.php respectively
The examples below are sans security for brevity and will assume that you make connections to the db.
//delete.php
$archiveId = $_GET['archiveid'];
//now use your db connection to delete the record according to the archiveid
and in update.php
//update.php
$archiveId = $_GET['archiveid'];
/**
* Use your db connection to retrieve all the data that relates to this archiveid
* Populate a form with all the archive details so you can modify them
* Save the form details to the db when it has been submitted, validated and escaped
* The query should use an UPDATE statement
*/
Related
I am working on a small project, and I have code that contains an "if" statement. However, I noticed whenever I fetch data with the value of 0 it does bring it back (var_dump()) but it doesn't display it because I guess the code thinks it's a useless value?
<?php
include_once 'dbh.inc.php';
$sqli = "SELECT datum, v, vo, nav FROM months;";
$result = mysqli_query($conn, $sqli);
$resultCheck = mysqli_num_rows($result);
echo "<table>";
echo "<tr>";
echo "<th>Datum</th>";
echo "<th> Vakantie uren</th>";
echo "<th> Vakantie uren opgennomen </th>";
echo "<th> Nieuw aantal vakantie uren</th>";
echo "</tr>";
if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
if($row['datum'] AND $row['v'] AND $row['vo'] AND $row['nav']) {
echo "<tr>";
echo "<td>".$row['datum']."</td>";
echo "<td>".$row['v']."</td>";
echo "<td>".$row['vo']."</td>";
echo "<td>".$row['nav']."</td>";
echo "</tr>";
}
}
echo "</table>";
}
?>
please notice the if ($row['datum'] etc.
When I take this piece of code out it renders even the values of 0, however if I end up having values that haven't been filled out (for example u have 5 tables in your database and the user fills 4 in because the fifth one is a useless one for him) it fetches the 5th one back as well and I end up having a very ugly empty spot. It doesn't look very nice.
My question is, is there a possible way to tell php (even with an "if" statement) that the value 0 is a value I want displayed?
If I understand you correctly, You don't want to display the row when there are no values but you want to display it when there are values even if the values are zeros.
Your if statement does not work because 0 = false in php.
Therefore consider modifying your if statement like so:
<?php
include_once 'dbh.inc.php';
$sqli = "SELECT datum, v, vo, nav FROM months;";
$result = mysqli_query($conn, $sqli);
$resultCheck = mysqli_num_rows($result);
echo "<table>";
echo "<tr>";
echo "<th>Datum</th>";
echo "<th> Vakantie uren</th>";
echo "<th> Vakantie uren opgennomen </th>";
echo "<th> Nieuw aantal vakantie uren</th>";
echo "</tr>";
if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
if( (!empty($row['datum']) || $row['datum'] == 0)
&& (!empty($row['v']) || $row['v'] == 0)
&& (!empty($row['vo']) || $row['vo'] == 0)
&& (!empty($row['nav']) || $row['nav'] ==0)
) {
echo "<tr>";
echo "<td>".$row['datum']."</td>";
echo "<td>".$row['v']."</td>";
echo "<td>".$row['vo']."</td>";
echo "<td>".$row['nav']."</td>";
echo "</tr>";
}
}
echo "</table>";
}
?>
Well, in PHP, empty is evaluated as false, so your if condition will be false.
If you want to display 0 where the value is empty, you can use the Ternay Operator:
$foo = '';
echo $foo ? $foo : '0'; // 0
Check it out: https://3v4l.org/Beem1.
The sessions between multiple pages on my site is not persisting. This it the session code I have at the start of each page:
<?php
#session_start();
echo session_id();
?>
I then add the variables to the session:
$_SESSION["CustomerID"]= $IDCustomer;
$_SESSION["PaymentID"]= $IDPayment;
var dumping this directly afterwards shows the correct variable. however, when doing the exact same on the next page, the variables are NULL. The only thing I have done between var dumping the variables on the first page, and var dumping them on the second page is clicking the hyperlink to switch the pages.
This is the code in full for each page:
<?php
require_once("php/init.php");
echo session_id();
$Cat = $_GET['Type'];
//create an instance of the ADO connection object
$conn = new COM ("ADODB.Connection")
or die("Cannot start ADO");
//show the connection string
$connStr = "PROVIDER=Microsoft.ACE.OLEDB.12.0;Data Source= \www\DMG Games Website\DMG Database.accdb";
$conn->open($connStr); //Open the connection to the database
//Read customer + payment from $Get
//Store in session variables
$IDCustomer = $_GET['CustomersDropdown'];
$IDPayment = $_GET['PaymentsDropdown'];
$_SESSION["CustomerID"]= $IDCustomer;
$_SESSION["PaymentID"]= $IDPayment;
//create the Products query
$query = "SELECT * FROM [Product Details]";
if (isset($Cat)) {
$query = "SELECT * FROM [Product Details] Where [Product Type] ='" . $Cat . "'";
}
//execute query
$rs = $conn->execute($query);
//count the number of columns
$num_columns = $rs->Fields->Count();
echo "There are " . $num_columns . " columns." . "<br>";
for ($i=0; $i < $num_columns; $i++) {
$fld[$i] = $rs->Fields($i);
}
//show the information in a table
echo "<table>";
echo "<tr>";
echo "<th> Product ID </th>";
echo "<th> Product Name </th>";
echo "<th> Product Description </th>";
echo "<th> Price </th>";
echo "<th> Quantity In Stock </th>";
echo "<th> Product Type </th>";
echo "<th> Image </th>";
echo "<th> Click to Buy </th>";
echo "</tr>";
while (!$rs->EOF) //carry on looping while there are records to be obtained
{
echo "<tr>";
for ($i=0; $i < $num_columns; $i++) {
echo "<td>" . $fld[$i]->value . "</td>";
}
echo "</tr>";
$rs->MoveNext(); //move on to the next record
}
echo "</table>";
//close the connection
$rs->Close();
$conn->Close();
$rs = null;
$conn = null;
$Customer = $_SESSION["CustomerID"];
var_dump($Customer);
$Payment = $_SESSION["PaymentID"];
var_dump($Payment)
?>
This is the code for the second page:
//create an instance of the ADO connection object
$conn = new COM ("ADODB.Connection")
or die("Cannot start ADO");
//show the connection string
$connStr = "PROVIDER=Microsoft.ACE.OLEDB.12.0;Data Source= \www\DMG Games Website\DMG Database.accdb";
$conn->open($connStr); //Open the connection to the database
// Get the url variables
$Pid = $_GET['newPid'];
// Read the quantity from the address
$Quantity = $_GET['newQuantity'];
//Create a query for retreiving the product image
$queryGetImage = "SELECT [Image] FROM [Product Details] Where [Product ID]=" . $Pid;
//execute the query
$rs = $conn->execute($queryGetImage);
echo "<h2> Add product to basket </h2>";
echo "</br></br>";
echo $rs->Fields("Image");
echo "</br></br>";
//declare the form
?>
<FORM NAME ="QuantityForm" METHOD ="get" ACTION = "">
Product ID:</br> <INPUT TYPE = "TEXT" NAME ="newPid" VALUE = "<?php echo $Pid;?>">
</br></br>
Quantity:</br> <INPUT TYPE = "TEXT" NAME ="newQuantity">
</br></br>
<input type="submit" />
</form>
<?php
//Create the AddToBasket query
if (isset($Quantity)) {
// Add the product and the quantity to the basket table
$AddtoBasketQuery = "INSERT INTO Basket([Product ID], [Quantity])
VALUES ('$Pid', '$Quantity')";
//execute the query
$conn->execute($AddtoBasketQuery);
//close the connection
$conn->Close();
$conn = null;
echo "</br> Your product has succesfully been added to your basket.";
}
?>
I don't see
session_start();
on your second script, you need to put it at the top of each script which wants to use session variables
You need to add session_start(); at start in second script. To access the Session variables this is required to start session before doing anything.
I am working on an synonym/alias manager database where the user has the ability to store an association they feel is right. Say the user types in "rabbit" and no synonyms or aliases are found. The user then decides to associate "rabbit" with "bunny" and stores that into a database. Anytime any other user types in "bunny" the results for "rabbit" will appear. However, I am trying to implement a polling system asking the user if they feel the association is correct. If they think "bunny" fits "rabbit" then they vote yes, otherwise no. This is where I am stuck. As soon as I load the poll and press submit everything disappears and nothing gets sent to the database. Code is below:
$query = "SELECT * from searchtestdb where engname in ( SELECT synonyms.synonym FROM words LEFT JOIN synonyms ON synonyms.word_id = words.word_id WHERE word LIKE '%$searchBox%') "; // Query for animals in db
$query = mysql_query($query);
if(mysql_num_rows($query) == 0)
{
echo "<h2>Aliases: </h2>";
echo "Sorry, but we can not find an alias to match your query.";
echo "<br> ";
}
else
{
echo "<h2> Results using Alias: </h2>";
while($result = mysql_fetch_array($query))
{
$query2 = "SELECT * from searchtestdb where engname LIKE '%".$result['engname']."%';";
$result2 = mysql_query($query2);
while($row = mysql_fetch_array($result2))
{
print "<h4>Latin Name: </h4> ";
echo $row["latname"];
echo "<br> ";
print"<h4>English Name:</h4> ";
echo $row["engname"];
echo "<br>";
print "<h4> Species: </h4> ";
echo $row["spectype"];
print "<h4>Characteristics: </h4> ";
echo $row["charc1"];
echo "<br>";
echo $row["charc2"];
echo "<br>";
echo $row["charc3"];
echo "<br>";
}
}
$self = $_SERVER['PHP_SELF'];
print "<form method='post' action='$self' >\n";
print "<h4>Alias Association Correct? : </h4>";
print "<p>" .
"<input type='radio' name='vote' id='vote' value='1' /> \n" .
"Yes" .
"<input type='radio' name='vote' id='vote' value='2' /> \n" .
"No" .
"</p> \n" .
"<p>" .
"<input type='submit'name='submitVote' value='Submit' />" .
"\n </p> \n" .
"</form> \n" .
$vote=htmlentities($_POST['vote']);
echo $vote;
mysql_connect(----------------------) or die(mysql_error());
mysql_select_db("-----------") or die(mysql_error());
if($vote == 1)
{
mysql_query("INSERT INTO items(yes, uNo, word_id) VALUES ('0', '0', bunny');");
mysql_query("UPDATE items SET yes=yes+1 WHERE word_id='bunny';");
echo 'Thanks for voting Yes!';
}
if($vote == 2)
{ mysql_query("INSERT INTO items(word_id) VALUES ('".$result['engname']."'') ");
mysql_query("UPDATE items SET uNo=Uno+1 WHERE word_id='".$result['engname']."'");
echo "changos";
}
}
In a nutshell I made a small mistake:
$self = $_SERVER['PHP_SELF'];
should be
$self = $_SERVER['POST'];
Thanks Anyway.
I want to have a php file that can be used to edit, view, delete, and add new products. I have the viewing and adding new products parts done, but what I am trying to do now, is when you view the table that contains the database information have a button for editing, deleting, and adding new items. The code that I want to add to the buttons to is as follow:
<html>
<head>
<style type="text/css">
td
{
padding:15px;
}
</style>
</head>
<?php
$mysqli = new mysqli("localhost","herp","lerp","derp");
$search=$_POST['search'];
$searchoption=$_POST['searchoption'];
$query= "SELECT * FROM contacts WHERE $searchoption = '".$search."'";
$result = $mysqli->query($query);
if (!$result) {
printf("Query failed: %s\n", $mysqli->error);
exit;
}
?>
<table>
<th> Information</th>
<?php
while ($contact = $result ->fetch_assoc()) {
echo "<tr>";
echo "<th> Item Number </th>";
echo "<th> Item Name </th>";
echo "<th> Description </th>";
echo "<th> Inventory </th>";
echo "<th> Price </th>";
echo "<th> Active or Non-Active </th>";
echo "<th> Photo </th>";
echo "</tr>";
echo "<tr>";
echo "<td>".$contact['item_number']."</td>";
echo "<td>".$contact['item_name']."</td>";
echo "<td>".$contact['item_description']."</td>";
echo "<td>".$contact['item_inventory']."</td>";
echo "<td>".$contact['item_price']."</td>";
echo "<td>".$contact['item_active_or_nonactive']."</td>";
echo "<td>".$contact['item_photo']."</td>";
echo "</tr><br/>";
}
?>
</table>
</html>
If my question is not specific enough please let me know and I will try and narrow it down, but i am mainly looking for a push in the right direction so i can figure out what to do, because as of right now i am at a loss.
search about php add edit delete
see this tutorial about Basic PHP System: View/Edit/Delete/Add Records
(pagination part are optional)
You should really consider implementing some type of RESTful server. It makes things a lot simpler.
There are lots of resources to get you started if you decide to go down this route.
Here's a very simple framework for implementing REST in php. http://peej.github.com/tonic/
Woah, first of all you should sort out all the MySQL injection vulnerabilities you have.
Secondly, I would do something like this.
<?php
if( isset( $_GET['action'] ) )
{
switch( $_GET['action'] )
{
case "add":
//Display HTML form for adding new entry
break;
case "edit":
if( isset( $_GET['item_number'] ) )
{
//Display HTML form for editing entry
}
break;
case "delete":
if( isset( $_GET['item_number'] ) )
{
//"Are you sure you want to delete $item_number?"
}
else
{
//Display HTML form for selecting which entry you want to delete
}
break;
default:
echo "<td><a href=/products.php?action=add'>Add new item</td>";
$query = 'SELECT ID,Title,Cost FROM tableProducts WHERE CategoryID="'.$id.'" ORDER BY Rank;';
if (($resource = #mysql_query($query, ...)) === false) {
while ($row = #mysql_fetch_assoc($resource)) {
echo "<td>".$row['Title']."</td>";
echo "<td>".$row['Cost']."</td>";
echo "<td><a href=/products.php?action=edit&id='".$row['ID']."'>Edit item?</td>";
echo "<td><a href=/products.php?action=deete&id='".$row['ID']."'>Delete Item ?</td>";
}
}
break;
}
}
?>
i have a system where a user searches for a film and reviews appear on a page with a button next to each review. The button can be selected to look at the individual review but i basically want a button that when selected it will look at all reviews on one page, the code i am using for the individual review is this
<?php
ini_set ('display_errors', 1);
error_reporting (E_ALL & ~E_NOTICE);
$searchfilm=$_POST['searchfilm'];
//Connect to database
//Filter search
$searchfilm = strtoupper($searchfilm);
$searchfilm = strip_tags($searchfilm);
$searchfilm = trim ($searchfilm);
$query = mysql_fetch_assoc(mysql_query("SELECT filmreview FROM review WHERE id = '$id'"));
$data = mysql_query("SELECT film.filmname, review.filmreview, review.reviewtitle, review.id FROM film, review WHERE film.filmid = review.filmid AND filmname = '$searchfilm'");
while($row = mysql_fetch_assoc($data))
{
// echo $row['filmname'];
// echo "<b>Film Name:</b> " .$searchfilm;
echo "<table border=\"2\" align=\"left\">";
echo "<tr><td>";
echo "<b>Review Title:</b> " .$row['reviewtitle'];
echo "<tr><td>";
echo $row['filmreview'];
echo "<p>";
echo "<form method='post' action='analyse1.php'>";
echo "<input type='hidden' name='reviewid' value='".$row['id']."'>";
echo "<input type='submit' name='submit' value='Analyse'>";
echo "</form>";
echo "</table>";
}
?>
you can fetch film reviews since film id inside review table
you could modify your code above and add another form to get all film reviews
when user click on a button it will redirect him/her to film_reviews.php
<?php
if(isset($_POST['submit']) && $_POST['submit'] == "getAllReviews"){
$filmID = mysql_real_escape_string($_POST['filmid']);
$sql = "SELECT * FROM review WHERE filmid = '$filmID'";
$res = mysql_query($sql);
if(is_resource($res)){
while($row = mysql_fetch_array($res)){
echo "<p>".$row['reviewtitle']."</p>";
echo "<p>".$row['filmreview']."</p>";
}
}
}