:)
I'm new here and I'm very new with php.
I am trying to make a search form with:
a dropdown list with two items: category and location;
a text field;
a search button.
It should work like this:
When "category" is selected, you enter a text and it will be searched only into categories.
When "location" is selected, your term will be searched among countries, states, zip codes.
I have a table with columns: id, name, category, country, zipcode, state.
Could somebody help me to understand why it doesn't display any results?
Here is my code:
<form action='search4.php' method='POST' name='form_filter'>
<b>Search</b><br>
<select name="selectVal">
<option value="category">category</option>
<option value="location">Country, state or zipcode</option>
</select>
<input type='text' name='search' placeholder='Enter text here...' size='50'><br>
<input type='submit' value='Send'>
</form>
<?php
// database connection
$db_host = "myhost";
$db_user = "myuser";
$db_password = "mypsw";
$db_name = "myname";
//connecting to database
$db = mysql_connect($db_host, $db_user, $db_password) or die ('Error - connection failed');
mysql_select_db($db_name, $db) or die ('Database selection error');
// retrieving search value we sent using get
$research = $_GET['research'];
// check if it has been sent, then it is ok
if ( $research == 'ok' ) {
// retrieving search value we sent using post
$search = $_POST['search'];
// check if the field has been filled
if ( $search == TRUE && $search != "" ) {
// character lenght more than 3
if ( strlen($search) >= 3 ) {
$search = mysql_escape_string(stripslashes($search));
}
if(isset($_POST['value'])) {
if($_POST['value'] == 'category') {
// query to get all categories
$query = "SELECT * FROM table_name WHERE category='$search'";
}
elseif($_POST['value'] == 'location') {
// query to get all country/state/zipcode records
$query = "SELECT * FROM table_name WHERE country='$search' OR zip_code='$search' OR state='$search'";
} else {
// query to get all records
$query = "SELECT * FROM table_name";
}
$sql = mysql_query($query);
while ($row = mysql_fetch_array($query)){
$Id = $row["Id"];
$country = $row["country"];
$category = $row["category"];
$name = $row['name'];
$zip_code = $row['zip_code'];
$state = $row['state'];
echo "Name: $name<br>";
echo "Zip_code : $zip_code<br>";
echo "State : $state<br>";
echo "Country: $country<br>";
echo "Category: $category<hr>";
}
}
}
}
?>
Thank you very much for your help.
You need to understand how to use <select> with php.
if you have this form:
<form method='post'>
<select name='example'>
<option value='e1'>example1</option>
<option value='e2'>example2</option>
</select>
</form>
You need to print it like that:
echo $_POST['example'];
In case the user selcted example1, the value will be e1.
In case the user selcted example2, the value will be e2.
You are using in your script $_POST['value']. It's just dosen't exist.
Try this, instead:
HTML FORM:
<form action='search4.php' method='POST' name='form_filter'>
<b>Search</b><br>
<select name="selectVal">
<option value="category">category</option>
<option value="location">Country, state or zipcode</option>
</select>
<input type='text' name='search' placeholder='Enter text here...' size='50'><br>
<input type='submit' value='Send'>
</form>
FORM PROCESSING:
<?php
// database connection
$db_host = "myhost";
$db_user = "myuser";
$db_password = "mypsw";
$db_name = "myname";
//connecting to database
$db = mysql_connect($db_host, $db_user, $db_password) or die ('Error - connection failed');
mysql_select_db($db_name, $db) or die ('Database selection error');
/*********************************************/
/***WHY DO YOU NEED THIS RESEARCH VARIABLE?***/
/*****WHAT IS ITS PURPOSE IN THIS SCRIPT?*****/
/*********************************************/
//GET CLEAN VERSIONS OF ALL NECESSARY VARIABLES:
$search = isset($_POST['search']) ? htmlspecialchars(trim($_POST['search'])) : null;
$catLocation = isset($_POST['selectVal']) ? htmlspecialchars(trim($_POST['selectVal'])) : null;
$query = "SELECT * FROM table_name WHERE ";
//YOU INDICATED YOU'D NEED TO RUN THE SEARCH-QUERY IF THE SEARCH-TERM AND SEARCH-SCOPE ARE DEFINED IE: NOT NULL; HOWEVER IF THE SEARCH TERM IS NOT GIVEN, YOU SELECT EVERYTHING IN THAT TABLE... (BAD PRACTICE, THOUGH)
if($catLocation){
if($search){
if($catLocation == "category"){
$query .= " category LIKE '%" . $search . "%'";
}else if($catLocation == "location"){
$query .= " country LIKE '%" . $search . "%' OR zip_code LIKE '%" . $search . "%' OR state LIKE '%" . $search . "%'";
}
}else{
$query .= "1";
}
$sql = mysql_query($query);
//HERE AGAIN WAS AN ERROR... YOU PASSED mysql_fetch_array A STRING $query INSTEAD OF A RESOURCE: $sql
while ($row = mysql_fetch_array($sql)){
$Id = $row["Id"];
$country = $row["country"];
$category = $row["category"];
$name = $row['name'];
$zip_code = $row['zip_code'];
$state = $row['state'];
echo "Name: $name<br>";
echo "Zip_code : $zip_code<br>";
echo "State : $state<br>";
echo "Country: $country<br>";
echo "Category: $category<hr>";
}
}
Related
The user suppose to input first name or last name into a search bar in a web-page and it suppose to list attributes from the table into the web-page. No matter what I type into the search bar, nothing is outputted. I followed this video on how to search in php. I tried looking at it over an hour but I can't find anything wrong. I get no error messages in my webpage.
<?php
$serverName = 'localhost';
$userName = 'root';
$password = '';
$databaseName = 'project3';
$connection = mysqli_connect($serverName, $userName, $password,
$databaseName);
if (!$connection) {
die("Connection Failed: " . mysqli_connect_error());
}
echo "Connected Successfully!! <br>";
$output = '';
if (isset($_Post['search'])) {
$searchq = $_Post['search'];
$searchq = preg_replace("#[^0-9a-z]#i", "", $searchq);
$query = mysqli_query("SELECT * from employee WHERE fname LIKE
'%$searchq%' OR"
. "lname LIKE '%$searchq%") or die("failed");
$count = mysqli_num_rows($query);
if ($count == 0) {
$output = 'No search results';
} else {
while ($row = mysqli_fetch_array($query)) {
$firstname = $row['fname'];
$lastname = $row['lname'];
$id = $row['id'];
$output .= '<div>' . $firstname . '' . $lname . '</div>';
echo "hi";
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Database Webpage</title>
<font color ="white">
<h1 style="background-color:black; text-align: center">Datebase Website</h1>
<font color ="black">
</head>
<body>
<form action = "index.php" method = "POST">
<input type = "text" name ="search" placeholder="Search"/>
<input type= "submit" value = ">>"/>
</form>
<?php print("$output"); ?>
</body>
</html>
The mysqli_query does need 2 parameters, as the PHP api shows with the procedural form that you have.
So, for that part, the call should look like this:
$query = mysqli_query($connection, "SELECT * from employee WHERE fname LIKE
'%$searchq%' OR"
. "lname LIKE '%$searchq%") or die("failed");
However, there will be trouble with the query. Note this portion of the query:
'%$searchq%' OR" <--- No space after the OR
. "lname LIKE '%$searchq%")
^--- No space before lname
Either one of the those 2 areas needs a space.
That last part of the query string will ultimately look like this:
'%$searchq%' ORlname LIKE '%$searchq%
^--- trouble (no space) ^---and trouble here (missing a closing single quote)
Sometimes it is useful to set the query separately, so that you can echo it out to check that it is syntactically correct as far as spacing around keywords, columns, values, comma usage (when needed), proper quoting, etc.
Consider this difference:
$query = "SELECT * from employee WHERE fname LIKE '%$searchq%' OR "
. "lname LIKE '%$searchq%'";
// query check (delete after validation, or comment-out)
echo $query;
$result = mysqli_query($connection, $query);
// I like to use $result, as the query call will return a result set with SELECT
// or false with failure. (though it can return true for other query types, see the api link)
It can also helpful to output the error as part of the die message:
if (!$result) { // Doh! something wrong...
die('failed: ' . mysqli_error($connection));
} else {
$count = mysqli_num_rows($result); // check the result count
if ($count == 0) {
$output = 'No search results';
} else {
while ($row = mysqli_fetch_array($result)) { // fetch a row
$firstname = $row['fname'];
$lastname = $row['lname'];
$id = $row['id'];
$output .= '<div>' . $firstname . '' . $lname . '</div>';
echo "hi";
}
}
}
HTH
So I have search bar that I'm hoping searches records in a mysql database and show them on a webpage. It should allow the user to choose the field they are searching under but it is is not showing the records the other end. Any ideas?
html:
<form action='recordresult.php' method='POST' name='form_filter' class="form-style-1" >
<b>Search</b><br>
<select name="selectVal">
<option value="category" >Select a category</option>
<option value="first_name">First Name</option>
<option value="surname">Surname</option>
<option value="address">Address</option>
<option value="phonenumber">Telephone</option>
</select>
<input type='text' name='search' placeholder='Enter text here...'><br>
<input type='submit' value='Send'>
</form>
PHP
<?php
include("config.php");
$link = mysqli_connect($server, $db_user, $db_pass)
or die ("Could not connect to mysql because ".mysqli_error($link));
// select the database
mysqli_select_db($link, $database)
or die ("Could not select database because ".mysqli_error($link));
$search = isset($_POST['search']) ? htmlspecialchars(trim($_POST['search'])) : null;
$catLocation = isset($_POST['selectVal']) ? htmlspecialchars(trim($_POST['selectVal'])) : null;
$query = "SELECT * FROM $table WHERE ";
//YOU INDICATED YOU'D NEED TO RUN THE SEARCH-QUERY IF THE SEARCH-TERM AND SEARCH-SCOPE ARE DEFINED IE: NOT NULL; HOWEVER IF THE SEARCH TERM IS NOT GIVEN, YOU SELECT EVERYTHING IN THAT TABLE... (BAD PRACTICE, THOUGH)
if($catLocation){
if($search){
if($catLocation == "category"){
$query .= " category LIKE '%" . $search . "%'";
}
else if($catLocation == "first_name"){
$query .= "first_name LIKE '%" . $search . "%'";
}
else if($catLocation == "surname"){
$query .= "surname LIKE '%" . $search . "%'";
}
else if($catLocation == "address"){
$query .= "address LIKE '%" . $search . "%'";
}
else if($catLocation == "phonenumber"){
$query .= "phonenumber LIKE '%" . $search . "%'";
}
}
else{
$query .= "1";
}
$sql = mysqli_query($query);
//HERE AGAIN WAS AN ERROR... YOU PASSED mysql_fetch_array A STRING $query INSTEAD OF A RESOURCE: $sql
while ($row = mysqli_fetch_array($sql)){
$firstname = $row["first_name"];
$surname = $row["surname"];
$address = $row["address"];
$phonenumber = $row['phonenumber'];
echo "First Name : $firstname<br>";
echo "Surname : $surname<br>";
echo "Address : $address<br>";
echo "Phone Number: $phonenumber<br>";
}
}
?>
The code doesn't provide any errors just a blank area where it should be. Also wondering if anyone know if it's possible to have first_name and surname as fields and search say "Emma Watson" and to be able to return results from both fields if one of the words are in there?
Thanks for all your help!
Please check below updated code
include("config.php");
$link = mysqli_connect($server, $db_user, $db_pass) or die ("Could not connect to mysql because ".mysqli_error($link));
// select the database
mysqli_select_db($link, $database)
or die ("Could not select database because ".mysqli_error($link));
$search = isset($_POST['search']) ? htmlspecialchars(trim($_POST['search'])) : null;
$catLocation = isset($_POST['selectVal']) ? htmlspecialchars(trim($_POST['selectVal'])) : null;
$query = "SELECT * FROM $table WHERE ";
//**If you want to merge for first name and surname then you need to merge both query with OR condition as below**
if($catLocation){
if($search){
if($catLocation == "category"){
$query .= " category LIKE '%" . $search . "%'";
}
else if($catLocation == "name"){
$query .= " ( first_name LIKE '%" . $search . "%' OR surname LIKE '%" . $search . "%' ) ";
}
else if($catLocation == "address"){
$query .= "address LIKE '%" . $search . "%'";
}
else if($catLocation == "phonenumber"){
$query .= "phonenumber LIKE '%" . $search . "%'";
}
}
else{
$query .= "1";
}
$sql = mysqli_query($link, $query); // **Adding reference connection variable**
while ($row = mysqli_fetch_array($sql)){
$firstname = $row["first_name"];
$surname = $row["surname"];
$address = $row["address"];
$phonenumber = $row['phonenumber'];
echo "First Name : $firstname<br>";
echo "Surname : $surname<br>";
echo "Address : $address<br>";
echo "Phone Number: $phonenumber<br>";
}
}
Merge 2 fields (Firstname and surname) in single (name) for search in both fields
<form action='recordresult.php' method='POST' name='form_filter' class="form-style-1" >
<b>Search</b><br>
<select name="selectVal">
<option value="category" >Select a category</option>
<option value="name">name</option>
<option value="address">Address</option>
<option value="phonenumber">Telephone</option>
</select>
<input type='text' name='search' placeholder='Enter text here...'><br>
<input type='submit' value='Send'>
</form>
i'm having some trouble passing Form checkbox array as mysql_query in order to delete multiple rows from table.
The structure is as follows:
HTML
<form action="usunogrod.php" method="POST" enctype="multipart/form-data">
<?php
$ogrodysql = "SELECT id_ogrodu, nazwa FROM ogrody";
$result = mysqli_query($con, $ogrodysql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "• " . $row["id_ogrodu"]. " " . $row["nazwa"]. "<input type='checkbox' name='removegarden[]' value=" .$row["id_ogrodu"]." <br><br>";
}
}
else {
echo "0 results";
}
?>
<br><br>
<input type="submit" value="Usuń zaznaczony ogród."/>
</form>
PHP for processing form in usunogrod.php
<?php
$db_host = 'xxxxx';
$db_user = 'xxxxx';
$db_pwd = 'xxxxx';
$con = mysqli_connect($db_host, $db_user, $db_pwd);
$database = 'xxxxx';
if (!mysqli_connect($db_host, $db_user, $db_pwd))
die("Brak połączenia z bazą danych.");
if (!mysqli_select_db($con, $database))
die("Nie można wybrać bazy danych.");
function sql_safe($s)
{
if (get_magic_quotes_gpc())
$s = stripslashes($s);
global $con;
return mysqli_real_escape_string($con, $s);
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$ogrod_id = trim(sql_safe($_POST['removegarden[]']));
if (isset($_POST['removegarden[]'])) {
mysqli_query($con, "DELETE FROM ogrody WHERE id_ogrodu='$ogrod_id'");
$msg = 'Ogród został usunięty.';
}
elseif (isset($_GET['removegarden[]']))
$msg = 'Nie udało się usunąć ogrodu.';
};
?>
MySQL table
ogrody
# id_ogrodu nazwa
1 garden1
How may i process an array from checkboxes form so that i will be able to pass a query to delete all checked elements?
EDIT:
I have been able to make it work to a moment where it only deleted one of the checked positions, or the other time just got an error saying i can't pass and array to mysqli_query.
I think this should help you:
Change this line:
echo "• " . $row["id_ogrodu"]. " " . $row["nazwa"]. "<input type='checkbox' name='removegarden[]' value=" .$row["id_ogrodu"]." <br><br>";
For this one:
echo '• ' . $row["id_ogrodu"]. ' ' . $row["nazwa"]. '<input type="checkbox" name="removegarden['.$row["id_ogrodu"].']" value="'.$row["id_ogrodu"].'" /> <br/><br/>';
Then this one:
if (isset($_POST['removegarden[]'])) {
To
if (isset($_POST['removegarden'])) {
And finally your query:
$gardens = implode(',',$_POST['removegarden']);
mysqli_query($con, "DELETE FROM ogrody WHERE id_ogrodu IN($gardens)");
You can get your data in $_POST['removegarden']. no need [] at last.
Then convert this array to ',' seperated string which can be then used in query
if (isset($_POST['removegarden'])) {
$ids_to_delete = implode(",",$_POST['removegarden']);
mysqli_query($con, "DELETE FROM ogrody WHERE id_ogrodu IN ($ids_to_delete)");
$msg = 'Ogród został usunięty.';
}
I'm trying to create a search bar for my website on my local server, but when I submit the page generated is just blank. I've been following a couple of guides online but can't seem to figure out why it is not connecting to my MySQL db and getting the results. This is my first time attempting db and PHP so appreciate all advice.
<form action="./search.php" method="get">
<input type="text" name="q">
<input type="submit" value="Search">
</form>
Search.php
<?php
$conn = mysqli_connect("localhost", "root", "root", "womendig_search");
if(mysqli_connect_errno()){
echo "Failed to connect: " . mysqli_connect_error();
}
error_reporting(0);
$output = '';
if(isset($_GET['q']) && $_GET['q'] !== ' '){
$searchq = $_GET['q'];
$q = mysqli_query($conn, "SELECT * FROM search WHERE keywords LIKE '%$searchq%' OR title LIKE '%$searchq%'") or die(mysqli_error());
$c = mysqli_num_rows($q);
if($c == 0){
$output = 'No search results for <b>"' . $searchq . '"</b>';
} else {
while($row = mysqli_fetch_array($q)){
$id = $row['id'];
$city = $row['city'];
$country = $row['country'];
$descriptions = $row['descriptions'];
$output .= '<h3>' . $title . '</h3>
<p>' . $desc . '</p>
';
}
}
} else {
header("location: ./");
}
print("$output");
mysqli_close($conn);
?>
The $title and $desc were not defined so you have empty <h3> and empty <p> tags.
Also i think it's better to make a few changes in your code.
Use !empty($_GET['q']) instead of $_GET['q'] !== ' ' and use extract($row); instead of
$id = $row['id'];
$city = $row['city'];
$country = $row['country'];
$descriptions = $row['descriptions'];
I've created drop down list with value name from the database. When I select the value from the drop down list, other data will appear in other textfield based on the database. The submit process was doing fine except when I check on the list. The drop down list value didn't appear in the list but other data did.
This is my adding form:
<tr><td width="116">Medicine name</td><td width="221">
<center>:
<select name="name" id="name" >
<option>--- Choose Medicine ---</option>
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("arie");
$sql = mysql_query("SELECT * FROM tabelmedicine ORDER BY name ASC ");
if(mysql_num_rows($sql) != 0){
while($row = mysql_fetch_assoc($sql)){
$option_value = $row['priceperunit'] . ',' . $row['stock'];
echo '<option value="'.$option_value.'">'.$row['name'].'</option>';
}
}
?>
</select ></center>
This is a script to display other database value in other textfield when the drop down list is selected:
<script>
var select = document.getElementById('name');
var priceperunit = document.getElementById('priceperunit');
var stock = document.getElementById('stock');
select.onchange = function()
{
var priceperunit_stock = select.value.split(',');
priceperunit.value = priceperunit_stock[0];
stock.value = priceperunit_stock[1];
}
</script>
This is my inserted data into database process:
<?php
$host = "localhost";
$user = "root";
$pass = "";
$db = "arie";
$connect = mysql_connect($host, $user, $pass) or die ('Failed to connect! ');
mysql_select_db($db);
$name=$_POST['name'];
if ($name === "")
{
echo "Please fill all the data";
}
else
{
$query="INSERT INTO `tabelout`(`name`)
VALUES ('$name');";
$result = mysql_query($query) OR die (mysql_error());
echo "You have successfully added new medicine to the database.";
}
?>
This is my list page, where the name didn't show up:
<?php
$con=mysqli_connect("localhost","root","","arie");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM tabelout");
echo "<table border='1'>
<th>name</th>";
while($row = mysqli_fetch_array($result))
{
echo "<td><center>" . $row['name'] . "</center></td>";
}
echo "</table>";
mysqli_close($con);
?>
Make sure your database table has records, If it has records, then change the table structure, Add tr tags where required.
echo "<table border='1'>
<tr><th>name</th></tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr><td><center>" . $row['name'] . "</center></td></tr>";
}
echo "</table>";