Send individual array results to printer based on id table - php

I'm working on a simple PHP script that stores user details in a MySQL database. I can run a query and have it return the individual records as long as the query matches the last name (pre-defined). Once I have the records, I want to be able to echo a print button next to each record so that the user can individually print each record.
The code is a mashup of several snippets of code and is working great, except the "print user data" part. I'm not a newbie in PHP, but I also know enough to navigate around a script. Here's what I've got so far.
<?php
//capture search term and remove spaces at its both ends if the is any
$searchTerm = trim($_GET['keyname']);
//check whether the name parsed is empty
if($searchTerm == "")
{
echo "Enter name you are searching for.";
exit();
}
//database connection info
$host = "localhost"; //server
$db = "users"; //database name
$user = "root"; //dabases user name
$pwd = "password1"; //password
//connecting to server and creating link to database
$link = mysqli_connect($host, $user, $pwd, $db);
//MYSQL search statement
$query = "SELECT * FROM details WHERE lastname LIKE '%$searchTerm%'";
$results = mysqli_query($link, $query);
/* check whether there were matching records in the table
by counting the number of results returned */
if(mysqli_num_rows($results) >= 1)
{
$output = "";
while($row = mysqli_fetch_array($results))
{
echo "<tr valign=bottom>";
echo "<td bgcolor=#ffffff background='img/dots.gif' colspan=6><img src=img/blank.gif width=1 height=1></td>";
echo "</tr>";
echo "<tr valign=center>";
echo "<td class=tabval><img src=img/blank.gif width=10 height=20></td>";
echo "<td class=tabval><b>".htmlspecialchars($row['firstname'])."</b> </td>";
echo "<td class=tabval>".htmlspecialchars($row['lastname'])." </td>";
echo "<td class=tabval>".htmlspecialchars($row['address'])."</td> ";
echo "<td class=tabval>".htmlspecialchars($row['phone'])." </td>";
echo "<button type=\"button\" class=\"formbutton\" onclick=\"printpage('" . $lastname . "'); \">Print User Data</button>";
echo "<td class=tabval></td>";
echo "</tr>";
$i++;
}
echo "<tr valign=bottom>";
echo "<td bgcolor=#fb7922 colspan=6><img src=img/blank.gif width=1 height=8></td>";
echo "</tr>";
echo $output;
}
else
echo "There was no matching record for the name " . $searchTerm;
?>
<br />
Done

echo "<button type=\"button\" class=\"formbutton\" onclick=\"printpage('" . $lastname . "'); \">Print User Data</button>";
This line is calling a javascript function called "printpage". Once you have that javascript function on the page, you'll be closer to your expected result.

Related

How can I pull in field data by ID from MySQL database?

I have two PHP files: itemTransaction.php and recordItemTransaction.php. I can select which row I would like to record a transaction for from a table in itemTransaction, and it links to the correct row in the database in recordItemTransaction.php, leading to a form allowing me to edit the itemQuantity. I have a form that has a hidden ID field and a textbox for the user to enter in an updated itemQuantity, which will be submitted to the database upon submission. I would like to display the current itemQuantity to the user, so when they edit the itemQuantity, they know what the current quantity is before they edit it and record the transaction.
My issue is that in recordItemTransaction.php, I cannot figure out how to pull in both the values for ID and itemQuantity in the same file.
This links to recordItemTransaction.php. Since I am referencing ID here, I can retrieve it in the next file. But I cannot retrieve itemQuantity along with the ID. Only one or the other. So, when I switch it to...
...I can retrieve the itemQuantity value in the textbox, but when I submit the form, it cannot tell which row to update.
itemTransaction.php
$query = "SELECT * FROM `Items` WHERE `isActive` = 'Active'";
$result = mysqli_query($con, $query);
echo "<h1>Record Transaction | Items</h1>";
echo "<a href='../inventoryIndex.php'><button class='button'>Back</button></a>";
//Display Data
echo "<table class='applyFont' cellspacing='0' cellpadding='0'>";
echo "<tr>";
echo "<th></th>";
echo "<th>ITEM</th>";
echo "<th>COST</th>";
echo "<th>RECORD TRANSACTION</th>";
echo "</tr>";
while($row=mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td align='center' width='9%'><img src='/InventoryManager/InventoryManagerImages/Items/{$row['itemImage']}' width='115' height='125' style='display:block'></td>";
echo "<td align='center' width='30%'>{$row['description']}</td>";
echo "<td align='center' width='30%'>$ {$row['unitCost']}</td>";
echo "<td align='center'><a href='recordItemTransaction.php?ID={$row['ID']}'><img src='/InventoryManager/InventoryManagerImages/Icons/couple-of-arrows-changing-places.png' title='Record an update to inventory'></td>";
echo "</tr>";
}
?>
</body>
</html>
recordItemTransaction.php
>
>
<?php
if(isset($_POST['updateQuantity'])) {
//Connect to DB
$hostname = "******";
$username = "******";
$password = "******";
$dbName = "******";
$con = mysqli_connect($hostname, $username, $password, $dbName);
//Get Value From User
$itemQuantity = $_POST["itemQuantity"];
$ID = $_POST["ID"];
//Query to Update Data
$query = "UPDATE `Items` SET `itemQuantity`='$itemQuantity' WHERE ID='$ID'";
$result = mysqli_query($con, $query);
//Check if Query Was Successful
if($result) {
echo "<p style=font-family:'Roboto Condensed', sans-serif>Item quantity has been updated</p>";
} else {;
echo "<p style=font-family:'Roboto Condensed', sans-serif>Error updating the quantity of the item.</p>" . mysqli_error();
}
//Disconnect From DB
mysqli_close($con);
}
?>
<body>
</body>
</html>

Data not required is being displayed

I have a form where the user enters data e.g. AXZAA QS1QS. This data is Posted to my PHP script. The PHP Script connects to a MYSQL database which contains at the moment 2 records.
The idea is that the PHP script will take the input and compare it to the records in the database. If the records exist they are displayed in a table on a web page otherwise, an error message is displayed.
I am having a number of problems with my PHP script and have modified my script a number of times. However, the thing I am having the biggest problem with is this:
When the form appears for the first time, the message record doesn't exist appears twice, this is before the user has entered any data and is seeing the form for the first time. See picture below.
After entering data (when the PHP script was partially working correctly), if there is a match i.e. records existed, along with the records in the table I would receive an error message telling me that records were not found. To see if I could resolve the problem I added code to tell me what records could not be found, the records that couldn't be found were the ones that were found and the other records from the database which I wasn't looking for. I know the SQL query in my PHP script tells the script to get everything from the database however, I would have thought the if statement would have fixed the problem.
Sorry about writing such a long problem and I hope it's not confusing.
enter code here
<?php
//Connect to the database connection file
require 'databaseconnection.php';
$searchBar=(isset($_POST['searchBar']) ? $_POST['searchBar'] :null);
$userdata = trim($searchBar);
$cleaned_data = preg_split('/[\s]+/', $userdata);
$sql = "SELECT DISTINCT * FROM atable_2";
$result = mysqli_query($database_connection, $sql);
echo "<table border>
<tr>
<th>Allocation</th>
<th>Codes</th>
<th>Names</th>
</tr>";
while($putdatabaseanswer_intoarray = mysqli_fetch_array($result)) {
$allocation_id = $putdatabaseanswer_intoarray["allocation"];
$codes_id = $putdatabaseanswer_intoarray["codes"];
$names_id = $putdatabaseanswer_intoarray["names"];
foreach($cleaned_data as $value) {
if($value==$codes_id) {
echo "<tr>";
echo "<td>" . $allocation_id. "</td>";
echo "<td>" . $codes_id . "</td>";
echo "<td>" . $names_id . "</td>";
echo "</tr>";
}
else
{
echo "<br />";
echo "One or more of the records have not been found: $codes_id";
echo"<br />";
}
}
}
echo "</table>";
?>
Wouldn't it be better to assign $searchbar after an if statement like
`<?php
//Connect to the database connection file
require 'databaseconnection.php';
if(isset($_POST['searchBar']))
{
$searchbar = $_POST['searchBar'];
$userdata = trim($searchBar);
$cleaned_data = preg_split('/[\s]+/', $userdata);
$sql = "SELECT DISTINCT * FROM atable_2";
$result = mysqli_query($database_connection, $sql);
echo "<table border>
<tr>
<th>Allocation</th>
<th>Codes</th>
<th>Names</th>
</tr>";
while($putdatabaseanswer_intoarray = mysqli_fetch_array($result)) {
$allocation_id = $putdatabaseanswer_intoarray["allocation"];
$codes_id = $putdatabaseanswer_intoarray["codes"];
$names_id = $putdatabaseanswer_intoarray["names"];
foreach($cleaned_data as $value) {
if($value==$codes_id) {
echo "<tr>";
echo "<td>" . $allocation_id. "</td>";
echo "<td>" . $codes_id . "</td>";
echo "<td>" . $names_id . "</td>";
echo "</tr>";
}
else
{
echo "<br />";
echo "One or more of the records have not been found: $codes_id";
echo"<br />";
}
}
}
echo "</table>";
}
else{
echo "<p>Please enter a search term</p>";
}
?>
You could then execute the MySQL query within that "if" statement rather than having it execute assuming there is a value

How to delete a Mysql-Statement with a specific ID in a form?

I want to delete a entry in a database. So I made a (working!) table with the entries shown. So I want to delete the one entry, which I push a button "delete".
I thought I have to make a second php-file, but I don't know how to catch the ID of the selected entry. Here is my code of the first data:
while ($datensatz = mysqli_fetch_assoc($query))
{
$id = $datensatz['id'];
echo "<form action='PHP/deleteditadmin.php'><tr>";
echo "<input type='hidden' name='iid' value='$id' />";
echo "<td name='id'>" . $id . "</td>";
echo "<td>" . $datensatz['name'] . "</td>";
echo "<td>" . $datensatz['server'] . "</td>";
echo "<td><input type='submit' name='deleteadmin' value='Löschen' /></td>";
echo "<td><input type='submit' name='editadmin' value='Edit' /></td>";
echo "</tr>";
}
And here is the deleteditadmin.php
<?php
$hostname = 'localhost';
$dbname = 'XX';
$username = 'XX';
$password = 'XX';
$con = mysqli_connect($hostname, $username, $password) or DIE('Connection to host isailed, perhaps the service is down!');
mysqli_select_db($con, $dbname) or DIE('Database name is not available!');
if($_POST['deleteadmin'])
{
$idwert = $_POST['$iid'];
$remove= "DELETE FROM admins WHERE id='$idwert'";
$removequery = mysqli_query($con, $remove);
}
mysqli_close($con);
header("location:../adminlist.php");
?>
So, I need the second submit button for another function in the same php-file. I just want to delete only the one datarow in which I clicked the "delete" button.
Thanks
This should do it:
if($_POST['deleteadmin'])
{
$idwert = $_POST['iid'];
$remove= "DELETE FROM admins WHERE id='".$idwert."'";
$removequery = mysqli_query($con, $remove);
}

How can I get a results page using bind params to return query from drop down

I'm working through an online tutorial to rewrite my results page using bind params. I thought I understood it fairly well but I can't get it to work so obviously, I don't. I've tried everything I thought logical plus some things that were not but still all I get is a blank page.
This is the drop down.
<form action="search3.php" method="post" >
<?php
$mysqli = new mysqli(localhost,user,password,database);
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
$query = "SELECT DISTINCT Country FROM engravers ORDER BY Country";
$result = $mysqli->query($query);
?>
<select name="dropdown">
<?php
while ($row = $result->fetch_assoc()) {
echo "<option value=\"{$row['Country']}\">";
echo $row['Country'];
echo "</option>";
}
$mysqli->close();
?>
</select>
<input type="submit" />
</form>
And this is the results page.It is pretty much copied from the tutorial except in the tutorial $queryparam would have been equal to $_POST['Country']. As that didn't work I've changed it to $_POST['dropdown'] which is the name of the drop down.
$hostname = "localhost";
$user = "user";
$password = "password";
$connection = mysqli_connect($hostname, $user, $password,);
if(!$connection){
echo"Could not connect to server";
};
mysqli_select_db($connection,'engraved_stamps');
if(!mysqli_select_db($connection,'engraved_stamps')){
echo"could not connect to database";
};
if(isset($_POST['dropdown']){
}
$stmt=mysqli_prepare($connection,"SELECT Key, Country, Year, Description, Images FROM engravers WHERE Country=?");
$queryParam=$_POST['dropdown'];
mysqli_stmt_bind_param($stmt,"s",$queryParam);
mysqli_stmt_bind_result($stmt,$Key,$Country,$Year,$Description,$Images);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$img_url = "http://www.engravedstamps.net/images/";
print '<table border="1" >';
while($row ->mysqli_stmt_fetch($stmt);
{
print '<tr>';
print '<td>'.$row["Key"].'</td>';
print '<td>'.$row["Country"].'</td>';
print '<td>'.$row["Year"].'</td>';
print '<td>'.$row["Description"].'</td>';
print '<td>'.'<img src="'.$img_url.$row['Images'].'" />'.'</td>';
print '</tr>';
}
print '</table>';
$results->free();
$mysqli->close();
I want to get this working but I also want to know why things work or don't.
Since writing the above, I've found a much neater way to do this which is working so for any other newbies like me, this is the code. The first lines to connect to the database are the same. then...
if(isset($_POST['dropdown'])){
}else{
echo "No input";
}
$stmt = $mysqli->prepare("SELECT ID,Country,Year,Description,Images FROM engravers WHERE Country = ? ORDER BY ID");
$stmt->bind_param('s', $_POST['dropdown']);
$stmt->execute();
$stmt->bind_result($ID,$Country,$Year,$Description,$Images);
$img_url = "http://www.engravedstamps.net/images/";
print "<table border='1' cellpadding='0'>";
while ($stmt->fetch()){
print '<tr><th>ID</th><th>Country</th><th>Year</th><th>Description</th><th>Image</th></tr>';
print '<tr>';
print "<td> " .$ID." </td>";
print "<td> " .$Country. " </td>";
print "<td> " .$Year. " </td>";
print "<td> " .$Description." </td>";
print '<td>'.'<img src="'.$img_url.$row.$Images.'" />'.'</td>';
?>
<td><a href="more.php?ID=<? echo $ID;?>">More Details</td>
<?
print '</tr>';
}
print '</table>';
$stmt->close();
?>
Tha hardest part was getting it to print into a table. There is also a cell now which offers more details for each line. If you click it, it takes you to a new page. I hope this can be of use to someone.

Issue with php/mysql inserting entry with checkbox checked into database

Below is the code from catalog page with the data which has to be inserted to the database. It has some problem and i cant insert that data to the database table, and i think i have not ported variables correctly.
My catalogue page has this code (it is for purchasing photographs):
while ($row=mysql_fetch_assoc($result))
{
echo "<tr><td width=100><img src=".$row['FilePath']." /></td>";
echo "<td width=100 padding=25>".$row['Title']."</td>"; $hour = time() + 3600; setcookie('titlecookie', $row['Title'], $hour);
echo "<td width=100 padding=25>".$row['Cost']."</td>";
echo "<td width=100>".$row['FileSize']."</td>";
echo "<td width=100>".$row['CaptureDate']."</td>";
echo "<td width=100>".$row['Resolution']."</td>";
echo "<td width=100><input type=checkbox name=checked[] value=select />Purchase</td></tr>";
}
echo "</table><input type=submit name=submit value=Purchase></form></center>";
}
else
{
echo "Query not successful";
}
The code for my purchase page appears as follows:
$username = "COOKIE['ID_my_site']";
$title = "COOKIE['titlecookie']";
$Custid = mysql_query("SELECT Custid from Customer Where Username=$username");
$Money = $_POST['Cost'];
$Photoid = mysql_query("SELECT Photoid from Photograph Where Title = $row[Title]");
foreach ($_POST['checked'] as $select) {
if(mysql_query('INSERT INTO Transaction (Money, Custid)
VALUES ($Money, $Custid)'))
{
echo "successfully added to Transaction";
}
else
{
echo "Problems adding data to Transaction";
}
if(mysql_query("INSERT INTO TransPhoto (Photoid, Transid)
VALUES ('$Photoid', '$Transid')"))
{
echo "successfully added to Transphoto";
}
else
{
echo "Problems adding data to Transphoto";
}
}
Could you possible assist me with fixing this code? I am relatively new to this but have searched and could not find an effective solution. Thanks

Categories