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]'
Related
I have a problem with updating value with PHP, it can get the data that I input but it cannot update it and render it to the read page.
<?php
require_once("session.php");
require_once("included_functions.php");
require_once("database.php");
new_header("VinceT");
$mysqli = Database::dbConnect();
$mysqli->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if (($output = message()) !== null) {
echo $output;
}
echo "<h3>Update A Order</h3>";
echo "<div class='row'>";
echo "<label for='left-label' class='left inline'>";
if (isset($_POST["submit"])) {
$stmt = $mysqli->prepare("UPDATE VTCustomer SET CustomerFName=? WHERE CustomerID=?");
$stmt->execute([$_POST["CustomerFName"],$_POST["CustomerID"]]);
$stmt1 = $mysqli->prepare("UPDATE VTCustomer SET CustomerLName=? WHERE CustomerID=?");
$stmt1->execute([$_POST["CustomerLName"],$_POST["CustomerID"]]);
if($stmt) {
$_SESSION["message"] = $_POST["CustomerFName"]." has been updated";
} else {
$_SESSION["message"] = "Error! Could not update ".$_POST["CustomerFName"];
}
redirect("read.php");
} else {
if (isset($_GET["id"]) && $_GET["id"] !== "") {
$stmt = $mysqli->prepare("SELECT OrderID FROM OrderVinceT WHERE OrderID=?");
$stmt->execute([$_GET["id"]]);
if ($stmt) {
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "<h3>Order ".$row["OrderID"]." Information</h3>";
}
echo "<form method='POST' action='update.php'>";
echo "<input type = 'hidden' name = 'OrderID' value = ' ".$row['OrderID']." ' />";
$stmt1 = $mysqli->prepare("SELECT CustomerFName FROM VTCustomer WHERE CustomerID=?");
$stmt1->execute([$_GET["id"]]);
if ($stmt1) {
while ($row1 =$stmt1 -> fetch(PDO::FETCH_ASSOC)) {
echo "<p>Customer First Name: <input type='text' name='CustomerFName' value='".$row1["CustomerFName"]."'></p>";
}
}
$stmt5 = $mysqli->prepare("SELECT CustomerLName FROM VTCustomer NATURAL JOIN OrderVinceT WHERE OrderVinceT.CustomerID=?");
$stmt5->execute([$_GET["id"]]);
if ($stmt5) {
while ($row5 =$stmt5 -> fetch(PDO::FETCH_ASSOC)) {
echo "<p>Customer Last Name: <input type='text' name='CustomerLName' value='".$row5["CustomerLName"]."'></p>";
}
}
echo "<input type='submit' name='submit' value='Update Order' class='tiny round button'/>";
echo "</form>";
echo "<br /><p>«:<a href='read.php'>Back to Main Page</a>";
echo "</label>";
echo "</div>";
} else {
$_SESSION["message"] = "Order could not be found!";
redirect("read.php");
}
}
}
new_footer("VinceT");
Database::dbDisconnect($mysqli);
?>
Do you guys have any idia why I cannot update this? I test queries in the console and it works just fine. The if statement that render out the message still receive the value of the input but it cannot update the database that render out in read.php
Is this possible? I want to be able to select only the column that i specify in my html form, but i am not sure how to do this. I have searched for quite a while but wasn't able to find anything that matches my idea.
Any help would be greatly appreciated.
echo "<select name='test'><option value='column1'>Column1</option></select>"
echo "<input type='submit' name='grafiek' value='Maak grafiek'>";
if(isset($_POST['checkvakje']) && $_POST['test'] && $_POST['grafiek']) {
$tijd = $_POST['checkvakje'];
foreach($tijd as $time) {
try {
$stmt = $pdo->prepare("SELECT [the column i selected] FROM statistieken WHERE tijd = :tijd AND poortid = :poort");
$stmt->execute(array(":tijd" => $time, ":poort" => $poort));
if($stmt->rowCount() > 0) {
while($row = $stmt->fetch()) {
echo "<tr>";
echo "<td>".$row['column i selected']."</td>";
echo "</tr>";
}
}
}
catch(PDOexception $e) {
echo "Query ging fout: " . $e->getMessage() ."";
}
}
}
Not via parameter binding.
Knowing the column names, you have to validate if the input matches a whitelist, so that there are no errors and more importantly - that it is secure.
For example:
$allowedColumns = ['foo', 'bar', 'baz'];
if (in_array($_POST['column'], $allowedColumns, true)) {
$column = $_POST['column'];
} else {
// Error: Invalid input
}
$sql = "SELECT {$column} FROM dummy WHERE whatever = 'example'";
select all column and just control it in php side like this
while($row = $stmt->fetch())
{
echo "<tr>";
echo "<td>".$row[$_POST['test']]."</td>";
echo "</tr>";
}
note : using user data as column name looks have so much of security issue
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
}
I'm having problems to find how to create an hyperlink in a table column result and then, on click, open another page with all fields (textboxes) filled. Imagine when a click an ID, i do a select * from table where column_id = ID... Is there a way to do it?
Thanks.
Best regards
I'm not completely sure what you are asking, but this may help you a bit.
First make a Javascript.
<script type="text/JavaScript">
function selectID() {
var ID = document.getElementById("ID").value;
document.location.href ="yoursite.php?ID="+ID;
}
</script>
Then connect to your database to query the table for a link ID (or more) for example by changing the variable $value.
<?php
//Connect to database
mysql_connect("host", "user", "pass");
mysql_select_db("db_name");
$value = 'something';
$ID = $_GET['ID'];
if (!$ID) {
$ID = 0;
}
if ($ID == 0) {
$query = "SELECT * FROM table WHERE `column_1` = '$value'";
$result = mysql_query($query);
echo "<table>";
while($myrow = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>";
echo "ID";
echo "</td>";
echo "</tr>";
}
echo "</table>";
}
elseif ($ID > 0) {
$query2 = "SELECT * FROM table WHERE `column_id` = '$ID'";
$result2 = mysql_query($query2);
while($myrow2 = mysql_fetch_array($result2)) {
$value1 = $myrow2['column_1'];
$value2 = $myrow2['column_2'];
}
echo "<form type=\"GET\" action=\"$PHP_SELF\">";
echo "<input type=\"text\" id=\"ID\" name=\"ID\" value=\"$ID\"><br>";
echo "<input type=\"text\" id=\"value1\" name=\"value1\" value=\"$value1\"><br>";
echo "<input type=\"text\" id=\"value2\" name=\"value2\" value=\"$value2\"><br>";
echo "<input type=\"hidden\" id=\"search\" name=\"search\" value=\"searching\">";
echo "<input type=\"submit\" id=\"submitbutton\" name=\"submitbutton\" value=\" Search \">";
echo "</form>";
}
?>
Hi I'm working on making a form to connect to a database. It works good so far. It displays information. However I want to include more then one field.
Like if I were only to enter "Oakland" in the "Location" form.
I think the isset field is the part I'm getting stuck at. I tried include '&!' or '||' to no effect. Or maybe its my html. I tried to include some code in the "isset" and it came up a "No data retrieved from server" error came up on browser. Because I only entered one field. I want to do it based on where the user enters information. BTW I do have a include in it to include the other files. Its just a snippet. It just I think that this is where my errors at.
Here is my html code. If you guys could help me figure out how to do this.
echo "<html>";
echo "<head>";
echo "<title>Your Title Here</title>";
echo "<link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\" />";
echo "</head>";
echo "<body onLoad=\"self.focus();document.searchform.search.focus()\">";
echo "<center>";
echo "<br /><form name=\"searchform\" method=\"GET\" action=\"search.php\">";
echo "<input type=\"text\" name=\"search\" size=\"20\" TABINDEX=\"1\" />";
echo "<input type=\"text\" name=\"Institution\" size=\"20\" TABINDEX=\"1\" />";
echo "<input type=\"text\" name=\"Location\" size=\"20\" TABINDEX=\"1\" />";
echo "<input type=\"text\" name=\"ProjectNotes\" size=\"20\" TABINDEX=\"1\" />";
echo "<input type=\"text\" name=\"TotalFunding\" size=\"20\" TABINDEX=\"1\" />";
echo "<input type=\"text\" name=\"ActiveYear\" size=\"20\" TABINDEX=\"1\" />";
echo " <input type=\"submit\" value=\"Search\" />";
echo "</form>";
//search variable = data in search box or url
if (isset($_GET['search'])) {
$search = $_GET['search'];
Investigator($search);
}
Investigator function
function Investigator($search)
{
$search = trim($search);
$search = preg_replace('/\s+/', ' ', $search);
//seperate multiple keywords into array space delimited
$keywords = explode(" ", $search);
//Clean empty arrays so they don't get every row as result
$keywords = array_diff($keywords, array(
""
));
//Set the MySQL query
if ($search == NULL or $search == '%') {
} else {
for ($i = 0; $i < count($keywords); $i++) {
$query = "SELECT * FROM Studies " . "WHERE Investigator LIKE '%$keywords[$i]%'" . " OR Location LIKE '%$keywords[$i]%'" . " OR TotalFundingAmount LIKE '%$keywords[$i]%'" . " OR Institution LIKE '%$keywords[$i]%'" . " ORDER BY Location";
}
//Store the results in a variable or die if query fails
$result = mysql_query($query) or die(mysql_error());
}
if ($search == NULL or $search == '%') {
} else {
//Count the rows retrived
$count = mysql_num_rows($result);
echo $count;
}
//If search variable is null do nothing, else print it.
if ($search == NULL) {
} else {
echo "You searched for <b><FONT COLOR=\"blue\">";
foreach ($keywords as $value) {
print "$value ";
}
echo "</font></b>";
}
echo "<p> </p><br />";
echo "</center>";
//If users doesn't enter anything into search box tell them to.
if ($search == NULL) {
echo "<center><b><FONT COLOR=\"red\">Please enter a search parameter to continue.</font></b><br /></center>";
} elseif ($search == '%') {
echo "<center><b><FONT COLOR=\"red\">Please enter a search parameter to continue.</font></b><br /></center>";
//If no results are returned print it
} elseif ($count <= 0) {
echo "<center><b><FONT COLOR=\"red\">Your query returned no results from the database.</font></b><br /></center>";
//ELSE print the data in a table
} else {
//Table header
echo "<center>";
echo "</center>";
//Colors for alternation of row color on results table
$color1 = "#d5d5d5";
$color2 = "#e5e5e5";
//While there are rows, print it.
while ($row = mysql_fetch_array($result)) {
//Row color alternates for each row
$row_color = ($row_count % 2) ? $color1 : $color2;
//table background color = row_color variable
echo "<center><table bgcolor=" . $row_color . ">";
echo "<tr>";
echo "<td>" . $row['Investigator'] . "</td>";
echo "<td>" . $row['TotalFundingAmount'] . "</td>";
echo "<td>" . $row['Institution'] . "</td>";
echo "</tr>";
echo "</table></center>";
$row_count++;
//end while
}
//end if
}
echo "</body>";
echo "</html>";
if ($search == NULL or $search == '%') {
} else {
//clear memory
mysql_free_result($result);
}
}
?>
isset() only checks to see if a variable is defined. empty() may be what you want to use in this case, because it will specifically check to see if the form input is empty.
Using this you can then construct a query which will be executed--in fact, it might eliminate the need for a separate function. I haven't looked too much at the function code you posted. But it would go something like this:
Say you have input fields x, y, and z. You want to be able to run a query that returns all the information matching any of these fields that are filled out. The script, then, would run the same pattern of code for each input, with $datax being the data from the form.
if (empty($datax) == false) //If the data is NOT empty...
{
$stringx = "column = {$datax}"; //Assign a chunk of a mySQL query requesting matching info to a string.
}
else //If the data IS empty...
{
$stringx = "1"; //Create the same variable, but make it 1. You'll see why.
}
//Repeat the above for $datay and $stringy, $dataz and $stringz, etc. Next is another if to make sure the entire form isn't left blank.
if (empty($datax) == true && empty($datay) == true && empty($dataz) == true)
{
//Code to return an "Empty form!" error
}
else
{
$query = "SELECT * FROM table WHERE " . $stringx . " AND " . $stringy . " AND " . $stringz;
//Continue to run query
}
What this does is construct a query from the data results. If, for example, a user searches for USA, a blank field, and industrial, (with fields being location, weather, and type respectively--again, all just an example) the query looks like:
SELECT * FROM table WHERE location = 'USA' AND 1 AND type = 'industrial'
Any fields left blank result in an AND 1 statement inserted, not affecting the query. Hope that clears things up a little, let me know if I can make further edits to help.