I have a PHP search form for searching in a SQL table.
All together it works great, but there is one thing I like to change.
The whole table is visible on the screen BEFORE the search.
I would like to mention only the records after a search.
Does anybody know to hide the table in PHP?
Many thanks in advance!
HTML
<form action="" method="post">
<input type="text" name="search" placeholder="Search">
<input type="submit" value="Submit" />
</form>
PHP
<?php
$host = "******";
$user = "******";
$password = "******";
$database_name = "vangsten";
$pdo = new PDO("mysql:host=$host;dbname=$database_name", $user, $password, array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
));
$search=$_POST['search'];
$query = $pdo->prepare("select * FROM meldingen WHERE soort LIKE '%$search%' OR zone LIKE '%$search%' LIMIT 0 , 10");
$query->bindValue(1, "%$search%", PDO::PARAM_STR);
$query->execute();
if (!$query->rowCount() == 0) {
echo "<table style=\"margin:50px auto;\">";
echo "<tr><td>VISSOORT</td><td>LENGTE</td><td>AANTAL</td><td>ZONE</td></tr>";
while ($results = $query->fetch()) {
echo "<tr><td>";
echo $results['soort'];
echo "</td><td>";
echo $results['lengte'];
echo "</td><td>";
echo $results['aantal'];
echo "</td><td>";
echo $results['zone'];
echo "</td></tr>";
}
echo "</table>";
} else {
echo 'Nothing found';
}
?>
This is because even when there is no search passed you will end up running the query: with WHERE sort LIKE '%%'
You should check if a search has been passed first
if(array_key_exists('search',$_POST) && !empty($_POST['search'])){
$search=$_POST['search'];
$query = $pdo->prepare("select * FROM meldingen WHERE soort LIKE '%$search%' OR zone LIKE '%$search%' LIMIT 0 , 10");
$query->bindValue(1, "%$search%", PDO::PARAM_STR);
$query->execute();
if (!$query->rowCount() == 0) {
echo "<table style=\"margin:50px auto;\">";
echo "<tr><td>VISSOORT</td><td>LENGTE</td><td>AANTAL</td><td>ZONE</td></tr>";
while ($results = $query->fetch()) {
echo "<tr><td>";
echo $results['soort'];
echo "</td><td>";
echo $results['lengte'];
echo "</td><td>";
echo $results['aantal'];
echo "</td><td>";
echo $results['zone'];
echo "</td></tr>";
}
echo "</table>";
} else {
echo 'Nothing found';
}
}
array_key_exists('search',$_POST) checks that there is a value with
the key 'search;'
!empty($_POST['search']) checks it is not just
an empty string. (You may want to allow this)
You could use isset($_POST['search']) instead of array_key_exists('search',$_POST) but array_key_exists is better practice as isset still returns false if the value is NULL
You can check if the user has clicked on the search button:
if (isset($_POST['search'])) {
// do your table generation here
}
Related
I do not understand PHP and SQL. We are just barely scraping it at the end of the semester, and its frustrating me. I am trying to get my results page to show the correct info, but for the life of me, it won't grab anything. I clearly have something wrong and was wondering if I could get some help.
Initial page
(normal top of basic webpage here)
<form id="ClubForm" action="ClubMembersResults.php" method="get">
<?php
require_once ('dbtest.php');
$query= "SELECT * FROM tblMembers ORDER BY LastName, FirstName, MiddleName;";
$r = mysqli_query($dbc, $query);
if (mysqli_num_rows($r) > 0) {
echo '<select id="memberid" name="memberid">';
while ($row = mysqli_fetch_array($r)) {
echo '<option value="'.$row['LastName'].'">'
.$row['LastName'].", ".$row['FirstName']." ".$row['MiddleName']. '</option>';
}
echo '</select>';
} else {
echo "<p>No Members found!</p>";
}
?>
<input type="submit" name="go" id="go" value="Go" />
</form>
<div id="results"></div>
</body>
results page currently written as:
<?php
$memid = 0;
$memid = (int)$_GET['memberid'];
if ($memid > 0) {
require_once ('dbtest.php');
$query = "SELECT * FROM tblMembers WHERE MemID = $memid;";
$r = mysqli_query($dbc, $query);`enter code here`
if (mysqli_num_rows($r) > 0) {
$row = mysqli_fetch_array($r);
echo "<p>Member ID: ".$row['MemID']."<br>";
echo "Member Name: ".$row['LastName'].", ".$row['FirstName']." ".$row['MiddleName']."<br>";
echo "Member Joined: ".$row['MemDt']."<br>";
echo "Member Status: ".$row['Status']."<br></p>";
}else {
echo "<p>Member not on file.</p>";
}
//table for inverntory
echo "<table border='1'>";
echo "<caption>Transaction History</caption>";
echo "<tr>";
echo "<th>Purchase Dt</th>";
echo "<th>Trans Cd</th>";
echo "<th>Trans Desc</th>";
echo "<th>Trans Type</th>";
echo "<th>Amount</th>";
echo "</tr>";
$query2 = "SELECT p.Memid, p.PurchaseDt, p.TransCd, c.TransDesc, p.TransType, p.Amount
FROM tblpurchases p, tblcodes c
WHERE p.TransCd = c.TransCd AND p.MemId = 'member id'
ORDER BY p.MemId, p.PurchaseDt, p.TransCd
";
$r2 = mysqli_query($dbc, $query2);
while ($row = mysqli_fetch_array($r2)) {
echo "<tr>";
echo "<td>".$row['PurchaseDt']."</td>;";
echo "<td>".$row['TransCd']."</td>";
echo "<td>".$row['TransDesc']."</td>";
echo "<td>".$row['TransType']."</td>";
echo "<td>".$row['Amount']."</td>";
echo "</tr>";
}
echo "</table>";
} else {
echo '<p>No Member ID from form.</p>';
}
?>
the results page should be showing tables with the info in the TH and TR/TD areas. Both those areas are coming from a separate SQL table, and teh the only similar field between the tblmembers and tblpurchases is MemID.
You need to use a join in your sql request to show purchases by members.
SELECT m.Memid, p.PurchaseDt, p.TransCd,
FROM tblpurchases p join
tblmembers m on p.MemId=m.MemId
This is an example of a join
Okay guys, I'm newbie here but
1. I want to UPDATE my sql after I input number on the text box. it echos correctly but doesn't change the DB.
2. I want to remove the first submit button and make it onchange event.
I'm really confused here. Thanks guys! This work is almost done. been doing it for a long time already. I'm still learning php, please bear wit me. thanks
<?php
$conn = new mysqli('localhost', 'root', 'jared17', 'hbadb')
or die ('Cannot connect to db');
$result = $conn->query("select * from english");
echo "<html>";
echo "<body>";
echo "<form name='form' method = POST>";
echo "<select name = 'Students'>";
while ($row = $result->fetch_assoc()) {
$LRN = $row['LRN'];
$Last = $row['Last_Name'];
$First = $row['First_Name'];
echo '<option value="'.$LRN.'">'.$Last.', '.$First.'</option>';
}
echo "</select>";
echo "<input type='submit' name='submit' value='Show'>";
if (isset($_POST['Students'])) {
$lrn = $_POST['Students'];
$stmt = $conn->prepare("SELECT Last_Name, First_Name, Level, Q1, Q2, Q3, Q4, FINAL FROM english WHERE LRN = ?");
$stmt->bind_param('i', $lrn);
$stmt->execute();
$stmt->bind_result($last, $first, $level, $q1, $q2, $q3, $q4, $final);
$stmt->fetch();
echo "<table><tr><th>LRN</th><th>Name</th><th>Level</th><th>Q1</th><th>Q2</th><th>Q3</th><th>Q4</th><th>Final</th></tr>";
echo "<tr><td>$lrn</td><td>$last, $first</td><td>$level</td><td>$q1</td><td>$q2</td><td>$q3</td><td>$q4</td><td>$final</td></tr></table>";
}
///////////EDIT DATA
echo "Edit Data: ";
echo "<select name = 'Edit'>";
echo '<option value=Q1>Q1</option>';
echo '<option value=Q2>Q2</option>';
echo '<option value=Q3>Q3</option>';
echo '<option value=Q4>Q4</option>';
echo '<option value=FINAL>FINAL</option>';
echo '<input type="number" name="editdata">';
echo "</select>";
echo "<input type='submit' name='submit2' value='Edit Now'>";
if (isset($_POST['Edit'])) {
$upd = $_POST['Edit'];
$txt = $_POST['editdata'];
$now = "UPDATE english SET $upd=$txt WHERE LRN=$lrn";
$result2 = $conn->query($now);
echo $now;
}
echo "</form>";
echo "</body>";
echo "</html>";
?>
You need to wrap your input in quotes or else SQL thinks you're trying to reference columns instead of strings.
$now = "UPDATE english SET $upd=\"$txt\" WHERE LRN=\"$lrn\"";
or if you prefer single quotes to avoid escaping w backslash then this should work the same:
$now = "UPDATE english SET $upd='$txt' WHERE LRN='$lrn'";
Also, this is not best practice, as mentioned by chris85 you are subject to injection attacks, if you want best practice then you want to use this: http://php.net/manual/en/mysqli-stmt.bind-param.php
as the title states I am trying to write a code that will update a boolean data in column (I called 'status') for a specific row. I used while loop in table to display the rows of new registered and where the status is NULL, I've put two buttons (accept, reject) each in td so they'll be displayed to each name, What I want is when the accept button clicked, it sets the status of its row in the table to 1, and when reject is clicked, same thing but sets 0 instead of 1.
I've did a lot of research over this but hit a road block after road block, so I really hope your help in this, many thanks!
Here is my code:
<table id="sHold" style="border:none;">
<?php
$conn = mysqli_connect('localhost', 'root', '', 'srs-db') or die('ERROR: Cannot Connect='.mysql_error($conn));
function getStudent () {
global $conn;
$query = "SELECT * FROM student_table WHERE status IS NULL;";
$result = mysqli_query($conn, $query);
$i = 1;
while ($row = mysqli_fetch_array($result)) {
$sId = $row['student_id'];
$sName = $row['student_name'];
echo "<tr id='sNew".$i."'>";
echo "<td>".$i." - </td>";
echo "<td>$sId</td>";
echo "<td>$sName</td>";
echo "<td><button name='sAcc".$i."'>Accept</button></td>";
echo "<td><button name='sRej".$i."'>Reject</button></td>";
echo "</tr>";
$i++;
}
if (isset($_POST['sAcc'.$i])) {
$row['status'] = 1;
}
}
getStudent();
?>
</table>
First of all, you miss <form> element. Your form inputs are useless without it, or without ajax.
Secondly, your $_POST check will only check last item. Since after you exit loop $i is set to last value in the loop. So your example will only work on last item.
<button> will now send $_POST with one of indexes sAcc or sRej. And it's value will be ID of your entry.
<table id="sHold" style="border:none;">
<form method="post" action="">
<?php
$conn = mysqli_connect('localhost', 'root', '', 'srs-db') or die('ERROR: Cannot Connect='.mysql_error($conn));
function getStudent () {
global $conn;
$query = "SELECT * FROM student_table WHERE status IS NULL;";
$result = mysqli_query($conn, $query);
$i = 1;
while ($row = mysqli_fetch_array($result)) {
$sId = $row['student_id'];
$sName = $row['student_name'];
echo "<tr id='sNew".$i."'>";
echo "<td>".$i." - </td>";
echo "<td>{$sId}</td>";
echo "<td>{$sName}</td>";
echo "<td><button type='submit' name='sAcc' value='{$sId}'>Accept</button></td>";
echo "<td><button type='submit' name='sRej' value='{$sId}'>Reject</button></td>";
echo "</tr>";
$i++;
}
}
if (isset($_POST['sAcc']) && intval($_POST['sAcc'])) {
$user_id = (int) $_POST['sAcc'];
// Do the database update code to set Accept
}
if (isset($_POST['sRej']) && intval($_POST['sRej'])) {
$user_id = (int) $_POST['sRej'];
// Do the database update code to set Reject
}
getStudent();
?>
</form>
</table>
Tip: I assume you're beginner. I remade your code. But you dont need to put this code into function. Use functions to handle data retrieval for example. Dont use it to display html.
<table id="sHold" style="border:none;">
<?php
$conn = mysqli_connect('localhost', 'root', '', 'srs-db') or die('ERROR: Cannot Connect='.mysql_error($conn));
function getStudent () {
global $conn;
$query = "SELECT * FROM student_table where status='NULL'";
$result = mysqli_query($conn, $query);
$i = 1;
while ($row = mysqli_fetch_array($result)) {
$sId = $row['student_id'];
$sName = $row['name'];
echo "<tr id='".$sId."'>";
echo "<td>".$i." - </td>";
echo "<td>$sId</td>";
echo "<td>$sName</td>";
echo "<td><button name='sAcc' id='acc-".$sId."' onclick='approveuser(this.id)'>Accept</button></td>";
echo "<td><button name='sRej' id='rec-".$sId."' onclick='approveuser(this.id)'>Reject</button></td>";
echo "</tr>";
$i++;
}
}
getStudent();
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
function approveuser(id){
trid=id.split('-')[1];
//alert(trid);
$.ajax({
url: "update.php",
type:"post",
data:{ val : id },
success: function(result){
//alert(result);
$('table#sHold tr#'+trid).remove();
alert('Updated');
}
});
}
</script>
//The code give below this update.php pge(ajax page)
<?php
$data=$_POST['val'];
$status =explode('-',$data);
$user_id=$status[1];
if($status[0]=='acc'){
$value=1;
}
elseif($status[0]=='rec'){
$value=0;
}
$conn = mysqli_connect('localhost', 'root', '', 'srs-db') or die('ERROR: Cannot Connect='.mysql_error($conn));
mysqli_query($conn,"update student_table set status='$value' where student_id=$user_id");
?>
I have a little problem where i try to search for a product and the user can choose to click on a full search or a partial search. Problem is when the user click on full search and type in something, the whole table is printing out and the word of the product is not (i want instead printing out the product and not the whole table) And with partial search, its just print outs it dont find a match. Below here is my code so far:
// DB configuration //
if (!isset($_POST["searchtype"])) {
echo "<form method='POST'>";
echo "Search for product:<br>";
# using html5 input type search
echo "<input type='text' name='searchtext' size='15' placeholder='search' results='5' autosave='saved-searches'>";
echo "<br><br>";
echo "Full search";
echo"<input type='radio' value='FULL' checked name='searchtype'><br>";
echo "Partial search ";
echo "<input type='radio' name='searchtype' value='PARTIAL'>";
echo "<br><br>";
echo "<input type='submit' value='Search' name='submit'>";
echo "</form>";
}
else {
$searchtext = $_POST["searchtext"]; # Retrieve from the form
$searchtype = $_POST["searchtype"]; # Retrieve from the form
$searchtext_san = sanitize_form_text($searchtext); # Prevents SQL injections!
try{
if($DBH == null)
$DBH = new PDO($dsn, $dbuser, $dbpass);
$sql = "select name, price, details from products where name='$searchtext_san'";
if ($searchtype == "FULL"){
$sql .= " = :searchtext_san";
$STH = $DBH->prepare($sql);
$STH->execute(array(':searchtext_san' => $searchtext_san));
}
if ($searchtype == "PARTIAL"){
$sql .= " LIKE ':searchtext_san'";
$STH = $DBH->prepare($sql);
$STH->execute(array(':searchtext_san' => '%'.$searchtext_san.'%'));
}
$STH->setFetchMode(PDO::FETCH_ASSOC);
$total = $STH->rowCount();
if ($total == 0){
echo "Sorry, no matches found!";
}
if ($total > 0){
while ($row = $STH->fetch()){
echo "{$row["name"]} {$row["price"]} {$row["details"]}<br>";
}
}
$DBH = null;
}
catch (PDOException $e){
echo '<b>PDOException: </b>',$e->getMessage();
die();
}
}
function sanitize_form_text($t)
{
$t = strip_tags($t);
$t = ereg_replace("[^A-Za-z0-9#._-]", "", $t);
return $t;
}
?>
try this for fulltext search
SELECT * FROM articles WHERE MATCH (title,body)
AGAINST ('+MySQL -YourSQL' IN BOOLEAN MODE);
Full text Search description
for partial search you can us like
SELECT name FROM products WHERE name RLIKE '[yourtext]'
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.