So basically I'm thinking that adding a search field to my website is out of my league, but internet has so much information that I decided to give it a go.
I started by adding a form to my index pagina, and this is the code I'm using:
<form method="get" action="search.php">
<table cellpadding="0px" cellspacing="0px">
<tr>
<td style="border-style:solid none solid solid;border-color:#4B7B9F;border-width:1px;">
<input type="text" name="q" style="width:100px; border:0px solid; height:17px; padding:0px 3px; position:relative;">
</td>
<td style="border-style:solid;border-color:#4B7B9F;border-width:1px;">
<input type="submit" value="" style="border-style: none; background: url('images/searchicon.gif') no-repeat; width: 24px; height: 19px;">
</td>
</tr>
</table>
</form>
Next up, my search.php code:
<?php
ini_set('display_errors', 0);
$search = $_GET ['q'];
mysql_connect("localhost", "root", "");
mysql_select_db("release");
$query = mysql_query("SELECT * FROM game WHERE name LIKE '%" . $queryString . "%'");
$foundnum = mysql_num_rows($query);
if ($foundnum == 0) {
echo "No results found. Either this game doesn't exist, or we have yet to add it. Please contact us!";
}
else {
echo "$foundnum results found !<p>";
$row = mysql_fetch_assoc($query);
{
echo '<p>'.$row['game_name'].'</p>';
}
}
?>
The query continuously echoes the $foundnum == 0 message even though the data I search for is in the game table.
However, when I try this code:
$query = mysql_query("SELECT game_name FROM game WHERE game_name LIKE '%" . $queryString . "%'");
The query prints '35 results found' on my screen. I have 35 entries in the database, but that doesn't make sense (to me) since I'm searching for one game name which is only entered once...
First of all you are using deprecated version mysql_* need to use mysqli_*. Please check below.
<?php
ini_set('display_errors', 2);
$search = $_GET ['q'];
// see changes from below line
$conn = mysqli_connect("localhost", "root", "","release");
$query = mysqli_query($conn,"SELECT game_name FROM game WHERE game_name LIKE '%". $search ."%'");
$foundnum = mysqli_fetch_array($query);
$count = count($foundnum['game_name']);
if ($foundnum == 0) {
echo "No results found. Either this game doesn't exist, or we have yet to add it. Please contact us!";
}
else {
echo "$count results found !<p>";
echo"<pre/>";print_r($foundnum['game_name']);
}
?>
Note:- remove include code from both index and search file that you write on upside.
From your second code it seems like there is a typo.
Try changing $query to
$query = mysql_query("SELECT * FROM game WHERE game_name LIKE '%" . $queryString . "%'");
and let me know if it works or not :)
Related
I'm using the following code to search the generated table and filter data. My problem is that when I search for lets say 1, it doesn't search & filter only 1 but also the data containing 1 like 11, 21, etc. .
How can I make it search and filter the exact data I enter?
<?php
if(isset($_POST['search']))
{
$valueToSearch = $_POST['valueToSearch'];
// search in all table columns
// using concat mysql function
$query = "SELECT * FROM `tbstats` WHERE CONCAT(`date`, `mode`, `svar`, `sdev`) LIKE '%".$valueToSearch."%'";
$search_result = filterTable($query);
}
else {
$query = "SELECT * FROM `tbstats`";
$search_result = filterTable($query);
}
function filterTable($query)
{
$connect = mysqli_connect("localhost", "root", "", "dbstats");
$filter_Result = mysqli_query($connect, $query);
return $filter_Result;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Stats</title>
<style>
table,tr,th,td
{
border: 1px solid black;
}
</style>
</head>
<body>
<form action="stats_filter.php" method="post">
<input type="text" name="valueToSearch" placeholder="Value To Search"><br><br>
<input type="submit" name="search" value="Filter"><br><br>
<table>
<tr>
<th>Date</th>
<th>Mode</th>
<th>Svar</th>
<th>Sdev</th>
</tr>
<?php while($row = mysqli_fetch_array($search_result)):?>
<tr>
<td><?php echo $row['date'];?></td>
<td><?php echo $row['mode'];?></td>
<td><?php echo $row['svar'];?></td>
<td><?php echo $row['sdev'];?></td>
</tr>
<?php endwhile;?>
</table>
</form>
</body>
</html>
When you do LIKE '%".$valueToSearch."%' you search for value that contain %value%.
If you want to search for value that start with your valueToSearch use LIKE '".$valueToSearch."%', for value that end with your valueToSearch use LIKE '%".$valueToSearch."' and for exact value use = '".$valueToSearch."'.
So in your case just replace LIKE '%".$valueToSearch."%' by = '".$valueToSearch."'
Edit :
In your case, you are doing some CONCAT so I guess you want to find the exact value in one of your field, right?
If yes, try to replace :
$query = "SELECT *
FROM `tbstats`
WHERE CONCAT(`date`, `mode`, `svar`, `sdev`) LIKE '%".$valueToSearch."%'";
by
$query = "SELECT *
FROM `tbstats`
WHERE `date` = '".$valueToSearch."'
OR `mode` = '".$valueToSearch."'
OR `svar` = '".$valueToSearch."'
OR `sdev` = '".$valueToSearch."'";
This way you will return data only if your exact searchValue is present inside one or your four field
Currently you concat all your columns to a single string and then search for an occurance of your search string anywhere in this concatenated string.
What you might actually want is to match each column exactly against your search string and return every row, which has an exact match in any column. To do an exact match, don't use LIKE. A simple = is what you want. To combine them, simply use the OR operator.
$query = "SELECT * FROM tbstats WHERE
date = '" . $valueToSearch . "' OR
mode = '" . $valueToSearch . "' OR
svar = '" . $valueToSearch . "' OR
sdev = '" . $valueToSearch . "'";
On top of that, you should realy escape your input or even better, use prepared statements.
I have a problem that is giving me a headache. I'm fairly new to PHP and MySQL interacting, and coding in general (about 3 months since I first dived into it), so I'm still learning the ropes, so to speak.
The thing is, I have a page that receives data through $_POST from another. All is fine for well. The page receives the data, which is an ID number, and echoes the item's characteristics available in the database corresponding to that ID.
This part of the code works just fine.
$sql = "SELECT nome, preco, `status` FROM produtos WHERE id = $_POST[id]";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
echo "Nome: "."<span style='color: red;'>".$row["nome"].
"</span>".
"<br>"."Preço: "."<span style='color: red;'>".
"R$".$row["preco"]."</span>"."<br><br>".$row["status"];
}
}
What I want, is to turn the values echoed into variables, so that I can set them as default value in another form and send that one to another page. Apparently, $row['nome'], for example, isn't available for re-use outside of the instance above.
<form method="post" action="?p=venda">
<input type="text" name="nome" value="<?php echo $row["nome"]; ?>">
<input type="text" name="preco" value="<?php echo $row["preco"]; ?>">
<input type="submit" name="change" value="Efetuar">
</form>
I know this code is prone to SQL injection, but I'm not looking into it right now. This will be a sort of offline program to help me with organizing some of my stuff, so, for now, I don't have to worry about security (not that I'll keep ignoring these issues).
Thanks in advance.
Assign $row to a variable and treat it as an array() outside the while loop.
$sql = "SELECT nome, preco, `status` FROM produtos WHERE id = $_POST[id]";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
$array = $row; // assign $row a variable.
echo "Nome: "."<span style='color: red;'>".$row["nome"].
"</span>".
"<br>"."Preço: "."<span style='color: red;'>".
"R$".$row["preco"]."</span>"."<br><br>".$row["status"];
}
}
// example
echo($array['nome']);
OK I'll tell you this, its actually unnecessary to sanitize every post. Its only necessary if your authenticated users are web users and there is a blank that they type code in.
In closed production environments, where your users are, you can safe guard the environment in several ways, but this is off topic here.
anyways, you have a DB chart that has a an Id column, the item name, and I am guessing stock or production status.
your display, I don't use spans, but I'll show you how I do it with tables.
So lets make your query for your colums: nome, preco, status
Here are the two methods, the first one is called looped result method which is mostly used for more than one row in the db table:
<?php
//load it in a variable and trim the outside spaces away if you are entering this from a blank form
$id=trim($_POST[id]);
///this should look familiar to you
$sql = "SELECT nome, preco, status FROM produtos WHERE id ='".$id."'";
///but I use the shorthand method here to get my results.
$result = $conn->query($sql);
///Now we loop and shift colum information into variables
/// in a incremental loop, the colums are numbered starting with 0
echo "<table align=center bgcolor=fff2e2 border=1>\n";
while ($data = $result->fetch_row()) {
////I print my table header, and start the data row, if I want it as several ids I will reset here too (which I will do here if you want to play with this)
echo '<tr><th>Nome</th><th>Preco</th><th>Status</th></tr>';
echo '<tr>';
for ($m=0; $m<$result->field_count; $m++) {
if ($m==0){
$nome='';
$nome=$data[$m];
echo '<td bgcolor="#ff0000">'.$nome.'</td>';
} else if ($m==1){
$preco='';
$preco=$data[$m];
echo '<td bgcolor="#ff0000">'.$preco.'</td>';
}else if ($m==2){
$status='';
$status=$data[$m];
echo '<td bgcolor="#ffffff">'.$status.'</td>';
}
}
//////now if I was building a query chart with submit to another I would put my form and my hidden inputs here before i close the table row with /tr, and my submit button would be my first cell value
echo "</tr>";
}
echo "</table>";
You could do the regular colum /row method since it is one ID, which would look like this I used the span format here so you can get the idea of how html is typically expressed in php:
$id=trim($_POST[id]);
$sql = "SELECT nome, preco, status FROM produtos WHERE id ='".$id."'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$nome=stripslashes($row['nome']);
$preco=stripslashes($row['preco']);
$status=stripslashes($row['status']);
echo 'Nome: <span style="color: red;">'.$nome.'</span><br>Preço: <span style="color: red;">'.$preco.'</span><br><br>'.$status;
///notice my quote usage above
here is my table example if I was going to list the whole db table in a scrollable list, and submit it to a file called detail.php
<?php
$sql = "SELECT nome, preco, status FROM produtos";
$result = $conn->query($sql);
echo "<table align=center bgcolor=e3fab5 ><td>";
echo '<div style="width: 500px; height: 450px; overflow: auto; border 5px dashed black; background color: #ccc;">';
echo "<table align=center bgcolor=fff2e2 border=1>\n";
while ($data = $result->fetch_row()) {
echo '<tr><th>Nome</th><th>Preco</th><th>Status</th></tr>';
echo '<tr>';
for ($m=0; $m<$result->field_count; $m++) {
if ($m==0){
$nome='';
$nome=$data[$m];
echo '<td bgcolor="#ff0000"><form action="detail.php" method="post"><input type="submit" name="id" value="'.$nome.'"></td>';
} else if ($m==1){
$preco='';
$preco=$data[$m];
echo '<td bgcolor="#ff0000">'.$preco.'<input type="hidden" name="preco" value="'.$preco.'"></td>';
}else if ($m==2){
$status='';
$status=$data[$m];
echo '<td bgcolor="#ffffff">'.$status.'<input type="hidden" name="status" value="'.$status.'"></td>';
}
}
echo "</form></tr>";
}
echo "</table>";
echo "</div></table>";
?>
I have a problem, small to others, but huge to me. I have been working on a project since March 15 of this year. I am not a web designer but this is just a hobby of mine.
My problems are:
When I call this program for data, I receive records but it only works if I search for the full postcode
(EX 1: n = no results EX 2: nn12ab = 5 results displayed )
I have to arrange the results in some order
(my results = abcdabcdabcdabcdnn12ababcdabcdabcdabcdnn12ababcdabcdabcdabcdnn12ab,
the way I am trying to get them its
first name / last name / email / postcode.
I had checked in w3schools and all other mode but still I am asking this. :(
I am fully aware its no hack protected , I just want to make it work.
any idea where I need to place whatever works ?
TXT IN ADVANCE!
HTML search
<form method="post" action="search.php">
<center>
<h1>My Search Engine</h1>
<input type="text" value="Search..." name="query" />
<input type="submit" value="Find" name="list" />
</center>
</form>
PHP SEARCH and display CODE
<?php
$servername = "localhost";
$username = "abcd";
$password = "******";
$dbname = "abcd";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM wfuk";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><td><tr><th>ID</th></td></tr>
<th>Name</th></td></tr>
<th>postcode</th</td>></tr>
<th>trade</th></td></tr>
<th>telephone</th></td></tr>
<th>comments</th></td></tr></table>
";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<table><tr><td>"
.$row["id"].
"</td><td>"
.$row["first_name"]
.$row["last_name"].
"</td></tr>".
"<tr><td>"
.$row["post_code"].
"</td></tr>".
"<tr><td>"
.$row["trade"].
"</td></tr>".
"<tr><td>"
.$row["telephone"].
"</td></tr>".
"<tr><td>"
.$row["comments"].
"</td></tr></table>"
;
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
Substitute this line:
$sql = "SELECT * FROM wfuk";
by
$sql = "SELECT * FROM wfuk where name like " . $_POST["query"] . " order by first_name, last_name, email, postcode";
I'm assuming that the columns in table wfuk have the names you said. If not, change them by the column names.
This is not the best way to do a search, because it open the possibility for SQL-injection attacks. But at your current level of knowledge you probably aren't ready for other solution.
Later please educate yourself on better prattices on this kind of operation.
Nothing to worry about, just basic confusions .
Answer of first question:
Dont use = sign in query like this :
Select * from table where postcode='.$variable.'
Use like clause this :
Select * from table where postcode like '%.$variable.%'
Answer for Second question:
Place border for your table :
<table border="1">
a few things here
Use some good tutorials, don't trust on w3school (some people call
it w3fool)
Never User Select * from table, rather specify column names
something like Select firstname, lastname from table
if you want search based on integer, user = sign e.g where rollunme=134
if you want to search some text/ character field , use LIKE operator
eg firstname LIKE %zaffar%
these are basic tips which should help you...
PS
question edited, but these tips should still apply as they are very generic in nature and should help you
yes it work unfortunately not whit this code, but from hear i lear the pice that i was missing THX ALL .
CODE I HAVE USE
<?php
//load database connection
$host = "localhost";
$user = "change my";
$password = "change my";
$database_name = "chage my database name";
$pdo = new PDO("mysql:host=$host;dbname=$database_name", $user, $password, array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
));
// Search from MySQL database table
$search=$_POST['search'];
$query = $pdo->prepare("select * from change_table_name where change_title LIKE '%$search%' OR change_author LIKE '%$search%' LIMIT 0 , 10");
$query->bindValue(1, "%$search%", PDO::PARAM_STR);
$query->execute();
// Display search result
if (!$query->rowCount() == 0) {
echo "Search found :<br/>";
echo "<table style=\"font-family:arial;color:#333333;\">";
// if need to multiply check clousley <tr> and </td> make shure they are on the right order
echo "<tr>
<td style=\"border-style:solid;border-width:1px;border-color:#98bf21;background:#98bf21;\">Change_Title_Books</td>
<td style=\"border-style:solid;border-width:1px;border-color:#98bf21;background:#98bf21;\">Change_Author</td>
<td style=\"border-style:solid;border-width:1px;border-color:#98bf21;background:#98bf21;\">change_Price</td></tr>";
while ($results = $query->fetch()) {
// if need to multiply check clousley <tr> and </td> make shure they are on the right order
echo "<tr><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;\">";
echo $results['Chage_title'];
echo "</td><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;\">";
echo $results['Change_author'];
echo "</td><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;\">";
// if not needit delete "$". from bellow
echo "$".$results['change_price'];
echo "</td></tr>";
}
echo "</table>";
} else {
echo 'Nothing found';
}
?>
<html>
<head>
<title> How To Create A Database Search With MySQL & PHP Script | Tutorial.World.Edu </title>
</head>
<body>
<form action="search-database.php" method="post">
Search: <input type="text" name="search" placeholder=" Search here ... "/>
<input type="submit" value="Submit" />
</form>
<p>PHP MySQL Database Search by Tutorial.World.Edu</p>
</body>
</html>
i found a different code i will post it for future references but you guys let me understand the thinks i could not understand
Im making a list with names and links to full info about them. So, I've got simple search engine, which searching by the names or specific numbers. I use $_SESSION to get id of the people. The problem is, when there are more than 1 name and Im moving to the page of specific person appears the page of the last person in the list!
So, code of the search engine is:
if(isset($_POST['search'])){
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9_a-z A-Z]#i","",$searchq);
$query = mysql_query("SELECT * FROM contract WHERE name LIKE '%$searchq%' OR student_code LIKE '%$searchq%'") or die("could not search");
$count = mysql_num_rows($query);
if($count == 0){
$output = 'There was no such results!';
}
else{
while($row = mysql_fetch_array($query)){
$name = $row['name'];
$student_code = $row['student_code'];
$_SESSION['users_id'] = $row['users_id'];
$output = '<table border ="1"><tr><td>'.$name.' '.$student_code.'
</td>
<td>
<form action="cont.php" method="post">
<label>Look at the contract:</label>
<input type="submit" name="submit" value=">>">
</form>
</td>
</tr>
</table><br \>
And another script in the page file:
$users_id = $_SESSION['users_id'];
$result = mysql_query("SELECT * FROM contract WHERE users_id = $users_id");
while($myrow = mysql_fetch_array($result)){
$output1 =
The way I understood your question is that you have two pages. One page that does the search, and another page that show the "more info" about a specific result.
What you're basically doing in the search is this:
Let's assume you have three results that got Id 1,4,7.
This is what's going to happen in your while loop
Set $name $student_code and $_SESSION['user_id'] ($_SESSION['user_id'] is now 1)
Prepare the first result
Set $name $student_code and $_SESSION['user_id'] ($_SESSION['user_id'] is now 4)
Prepare the second result
Set $name $student_code and $_SESSION['user_id'] ($_SESSION['user_id'] is now 7)
Prepare the third result
As you can see you're always overwriting the session key and therefore only the last one will be available when you get to the "cont.php" page (where I'm guessing the other code is?)
One simple solution would be to bake the id into the form and send it along in the request to the cont.php page. Something like this:
<form action="cont.php" method="post">
<label>Look at the contract:</label>
<input type="submit" name="submit" value=">>">
<input type="hidden" name="user_id" value="' . $row['users_id'] . '">
</form>
And then in the cont.php you simply change this:
$users_id = $_SESSION['users_id'];
to this
$users_id = $_POST['users_id'];
Hope that helps :)
This script is supposed to get the content of a text area and submit it to mysql, but it isnt can anyone see why?
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$error = '';
$like = mysql_real_escape_string($_POST['like_box']);
mysql_query("INSERT INTO likes (like) VALUES ($like)");
$id = mysql_query("SELECT id FROM likes WHERE like=$like");
header('Location:like.php?id='.$id.'');
}?>
<form method="post" action="post.php">
<textarea name="like_box" id="like_box" style="border-style: none; border-color: inherit; border-width: 0; width: 458px; height: 65px" class="style11120"></textarea>
<tr>
<td style="height: 53px">
<div class="style11116" style="width: 417px">
<input name="Submit" type="submit" value="submit" />
</form>
Having some error reporting would tell you that you need ' around the $like and you need ` around like in the columns section, since like is a reserved word, inside the insert.
mysql_query("INSERT INTO likes (`like`) VALUES ('$like')") or trigger_error('Query Error: ' . mysql_error());
Should work.
Also you will need to enclose the like in ` for the select:
$id = mysql_query("SELECT id FROM likes WHERE `like`=$like") or trigger_error('Query Failed: ' . mysql_error());
Your first SQL query is wrong. You have to enclose string values with quotation marks in SQL:
mysql_query("INSERT INTO likes (`like`) VALUES ('$like')");
The rest of your PHP part will not perform as you wish either. $id will be a resultset, not a value. You'll have to fetch the row like this:
$result = mysql_query("SELECT id FROM likes WHERE `like`='$like'");
$row = mysql_fetch_assoc($result);
$id = $row['id'];
Or even better, just replace the second SQL query with a call to mysql_insert_id:
$id = mysql_insert_id();
Still more possibilities for improvement:
Don't forget to call exit after you've done a header('Location: ...'); call, otherwise you may get unexpected results since the script will continue running.
Add some error handling of your insert. At least check with an if statement that it succeeded.