I have created a simple search engine to display results from database,but i need it to display all results with similar characters in them,not the whole exact word.Soo for example user types eng-- it should return result engine and all other words with eng in them,but at the moment it will return something only when you type whole word,engine.Guess i have a mistake somewhere but cannot really find it:There is my code.
<?php
$fsearch = "";
if (!empty($_GET['fsearch'])){
$fsearch=$_GET['fsearch'];
$query = "SELECT * FROM food_data_bg WHERE ";
$terms = explode (" ",$fsearch);
$i=0;
foreach($terms as $each){
$i++;
if($i == 1){
$query .= "title LIKE '$each'";
}
else{
$query .= "OR title LIKE '$each'";
}
}
$hostname = "localhost";
$username = "name";
$password = "pass";
$databaseName = "dbName";
$connect = new mysqli($hostname, $username, $password, $databaseName);
$connect->set_charset("utf8");
$query = mysqli_query($connect,$query);
$num_rows = mysqli_num_rows($query);
if($num_rows > 0){
while($row = mysqli_fetch_assoc($query)){
$title = $row["title"];
$fimage = $row["fimage"];
$carbs = $row["carbohydrates"];
$fats = $row["fats"];
$proteins = $row["proteins"];
$CaloriesTotal = $row["calories total"];
echo "
<table id='table1'>
<tbody>
<tr class='Table1-row2'>
<td><a><img src='$fimage'</a></td>
<td>$title</td>
<td>$carbs</td>
<td>$fats</td>
<td>$proteins</td>
<td>$CaloriesTotal</td>
</tr>
</tbody>
</table>";
}
} //got "else" claim here,but i don't think the mistake is in it...
}
?>
Any help,advice is appreciated <3 Thanks !
LIKE has to include wildcards if you want it to behave properly. So if you're looking for that word in the string, you could do something like this...
$query .= "title LIKE '%".$each."%'";
The percent (%) will match with anything (zero or more characters of any kind).
Related
**Edited for more info
I'm having issues creating a search page to display results from a SQL Server database. My SQL is correct because it outputs what I want in SSMS. My connection info is also correct as I've tested that. My issue is coming from tying it into the search form - I can't get it to find any results. If I want it to print a table it prints just fine, however, I really need this to work as a search. I'm still pretty new at PHP and SQL in general but this is what I have so far:
$serverName = "myserver";
$connectionInfo = array( "Database"=>"mydb", "UID"=>"myuser", "PWD"=>"mypass");
$conn = sqlsrv_connect( $serverName, $connectionInfo) OR die ('broke:' .sqlsrv_errors());
$output = '';
if(isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i", "", $searchq);
$query = sqlsrv_query($conn, "SELECT columns_I_need
FROM tables_I_need
WHERE col_1 LIKE '%$searchq%'") or die('broke:' .sqlsrv_errors());
$count = sqlsrv_num_rows($query);
if($count == 0) {
$output = 'There was nothing';
} else {
while($row = sqlsrv_fetch_array($query)) {
$stname = $row['streetname'];
$stno = $row['streetnumber'];
$apno = $row['permitnumber'];
$output .= '<div> '.$stname.' '.$stno.'</div>';
}
}
}
My search form looks like this:
<form> action="" method="post">
<input type="text" name="search" placeholder="Search for address...">
<input type="submit" value="Submit">
</form>
<?php print("$output"); ?>
Every time I search I get no results. So I guess my question is: is my search form correct and is my WHERE col_1 LIKE '%$searchq%' correct? What am I missing? Also, does the preg_replace not help in preventing sql injection?
If this isn't descriptive enough, please let me know.
I think the problem is to do with this line:
$count = sqlsrv_num_rows($query);
From the documentation for sqlsrv_num_rows() on php.net (emphasis mine).
Parameters
The statement for which the row count is returned. The statment resource must be created with a static or keyset cursor.
Parameters - sqlsrv_num_rows
and
Return Values
Returns the number of rows retrieved on success and FALSE if an error occurred. If a forward cursor (the default) or dynamic cursor is used, FALSE is returned.
Return Values - sqlsrv_num_rows
Because you have failed to specify a cursor in your query, the default cursor is used and false is returned, regardless if the query had returned results.
Then in your if statement, you check $count == 0. This check will return true, as 0 can be evaluated to false and you are not using strict type comparison (===). Therefore you will always see "There was nothing".
To fix this, you will need to specify a static or keyset cursor for your query. I'm going to use SQLSRV_CURSOR_STATIC as my cursor as an example, but you could use SQLSRV_CURSOR_KEYSET. See here for more information about the different cursors.
The general syntax is:
$stmt = sqlsrv_query($conn, $query, $params, array("Scrollable" => SQLSRV_CURSOR_STATIC));
I think I have this nailed down. It displays everything I need, I believe it's set up as a parameterized query, and with my class tags I'm able to style the output.
My only issue is if someone enters the street number AND the street name or the street name is two or more words, I don't get any results. It's probably something simple with my $sql statement. I tried:
WHERE (STNO LIKE '%$search_term%' AND STNAME LIKE '%$search_term%') OR APNO LIKE '%$search_term%'
but that doesn't get me anything either.
$serverName = "myserver";
$connectionInfo = array( "Database"=>"mydb", "UID"=>"myuser",
"PWD"=>"mypass");
$conn = sqlsrv_connect( $serverName, $connectionInfo) OR die ('broke:'
.sqlsrv_errors());
$search_term = $_GET['query'];
$sql = "SELECT my rows FROM my tables
WHERE STNO LIKE '%$search_term%' OR STNAME LIKE '%$search_term%' OR APNO LIKE '%$search_term%'
ORDER BY STNO";
echo "<div class='search-term-display'>You searched for: ", $search_term, "</div>";
if(isset($_GET['query'])) {
$search_term = $_POST['query'];
$search_term = preg_replace("#[^0-9a-z]#i", "", $search_term);
$query = sqlsrv_query($conn, $sql, array(), array("Scrollable" => 'static'));
while($data = sqlsrv_fetch($query)) {
while($row = sqlsrv_fetch_array($query)){
$stno = $row['STNO'];
$stname = $row['STNAME'];
$apno = $row['APNO'];
$suffix = $row['SUFFIX'];
$hseptyp = $row['HSEPTYP'];
$dttm = $row['COMPDTTM']->format('d/m/Y');
$partial = $row['PARTIAL'];
$waived = $row['WAVIED'];
$failed = $row['FAILED'];
$inspcomments = $row['INSPECTIONCOMMENTS'];
$fcomments = $row['FAILEDCOMMENTS'];
$descript = $row['DESCRIPT'];
echo "<hr>";
echo "<div class='insp_address'>".$stno.' '.$stname.' Permit Number: '.$apno."</div>";
echo "<div class='insp_date'>".'Inspection Date: '.$dttm."</div>";
echo "<div class='sys_type'>".'Septic System Type: ' .$hseptyp."</div>";
echo "<div class='code_violation_status'>".'Code Violation Status: ' .$descript."</div>";
echo "<div class='code_violation'>".'Code: '.$failed."</div>";
echo "<div class='insp_comments_title'>Inspection Comments:</div>";
echo "<div class='insp_comments'>".$fcomments."</div>";
}
sqlsrv_free_stmt( $query);
}
}
echo "</div>";
This is how I used the query and fetch with keyset:
$this->result = SQLSRV_QUERY($this->conn, $this->sql, Array(), Array( "Scrollable" => SQLSRV_CURSOR_KEYSET ));
SQLSRV_FETCH($this->result,SQLSRV_SCROLL_RELATIVE,$this->offset);
for($row = 1; $row <= $this->items_per_page; $row++) {
$rows[] = SQLSRV_FETCH_ARRAY($this->result);
}
return $rows;
Then you can use foreach like this:
<?php foreach ($result as $rows) {
if ($rows != NULL) { ?>
<tr>
<td><?php echo $rows['TerritoryID']?></td>
<td><?php echo $rows['TerritoryDescription']?></td>
<td><?php echo $rows['RegionID']?></td>
</tr>
<?php } ?>
<?php } ?>
Forgot to add a good rowcount block:
Function get_total_rows() {
$row_count = SQLSRV_QUERY($this->conn, $this->sql, Array(), Array( "Scrollable" => SQLSRV_CURSOR_KEYSET ));
return SQLSRV_NUM_ROWS($row_count);
SQLSRV_FREE_STMT($row_count);
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have a search engine that does not work, I want the engine to fetch data from a mySQL database and display them in a table, here is my PHP code..
Thank you!
PHP CODE:
<?php
<?php
$connect = new mysqli('localhost', 'root', '', 'supermazad') or die(mysql_error());
$connect->select_db('supermazad');
//collect
if(isset($_POST['search'])){
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i", "", $searchq);
$query = mysqli_query("SELECT * FROM main WHERE title LIKE '%$searchq%'") or die(mysql_error());
$count = mysql_num_rows($query) or die(mysql_error());
if($count == 0){
$output = 'There was no search results.';
}
else{
while($row = mysql_fetch_array($query)){
$id = $row['ref'];
$title = $row['title'];
$desc = $row['description'];
foreach( $id && $title && $desc ){
$output = '<table class="results-tab"><tr></tr><tr><td>'. $id .'</td>'. '<td>' . $title . '</td>' .'<td>'. $desc . '</td></tr>';
}
}
}
}
?>
**NOTE - THIS IS BASED IN YOU SAID, SIMPLE EXAMPLE **
You are mixing mysqli + mysql
The problem is related with your query. You need to index your fields from table you want.
what you need to do?
ALTER TABLE main ADD INDEX title (product_id);
SELECT * FROM main WHERE title LIKE '%".$searchq."%' OR MATCH(field_1, field_2, field_3, field_4) AGAINST('".$searchq."');
The second query is the example for use full-text (https://dev.mysql.com/doc/refman/5.5/en/fulltext-search.html)
Change the code:
<?php
// data
$localhost = 'localhost';
$username = 'username';
$password = 'passw0rd';
$database = 'supermazad';
mysql_connect($localhost,$username,$password) or die(mysql_error());
mysql_select_db($database) or die(mysql_error());
if(isset($_POST['search'])){
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i", "", $searchq);
$query = mysql_query("SELECT * FROM main WHERE title LIKE '%$searchq%'") or die(mysql_error());
$count = mysql_num_rows($query) or die(mysql_error());
if($count == 0){
$output = 'There was no search results.';
}else{
echo '<table class="results-tab">';
while ($row = mysql_fetch_array($query, MYSQL_ASSOC)) {
echo '<tr>
<td>'.$row["ref"].'</td>
<td>'.$row["title"].'</td>
<td>'.$row["description"].'</td>
</tr>';
}
echo '</table>';
}
}
?>
Use prepared statements, it's more secure as they prevent SQL injection.
I commented almost every step so you can learn prepared statements.
<?php
$mysqli = new mysqli('localhost', 'root', '', 'supermazad') or die(mysql_error());
if(isset($_POST['search'])){
$searchq = "%{$_POST[search]}%";
$searchqrep = preg_replace("#[^0-9a-z]#i", "", $searchq);
$stmt = $mysqli->prepare("SELECT * FROM main WHERE title LIKE ?");
$stmt->bind_param('s',$searchqrep); //bind parameters to your statement
$stmt->execute(); //you must execute your statement otherwise no results
$stmt->bind_result(); //bind results to variables, but you must define them after the "Select ... " SQL
$stmt->store_result(); //store results in case of further usage of them
while($stmt->fetch()){ // the while loop will pull out all existing results from your table
if($stmt->num_rows == 0){
echo "No search results";
}else{
// Echo/Print the binded variables from statement
}
}
$stmt->close(); //Still close your prepared statements
}
?>
i'm a newbie to php still.
I'm using phpmyadmin as my database. I have a table called 'lessonno' and a column named 'lesson' in it. I tried using this code to retrieve out the number inside 'lesson'. But it's not printing out anything. Can someone help?
<?php
$server = 'localhost';
$username = '';
$password = '';
$database = 'project';
mysql_connect($server,$username,$password) or die(mysql_error());
mysql_select_db($database) or die(mysql_error());
$sql = "SELECT 'lesson' FROM 'lessonno'";
$lesson = $_POST['lesson'];
$result = mysql_query($sql);
?>
<?php
for($i = 1; $i <= $lesson; $i++) {
echo "<div>
<span>Lesson ".$i."</span>
</div>
<br>";
}
?>
You can use something like this:
$sql = "SELECT lesson FROM lessonno";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
echo $row['lesson'];
}
If you would like to only print out a specific lesson with an certan ID, you can use something along the lines:
$id = $_GET['lessonid']; // If you would have something like index.php?lessonid=36 and you'd like it to only fetch the data for the lesson with the id of 36.
$sql = "SELECT lesson FROM lessonno WHERE id='$id'";
(by looking at the $_POST['lesson'] part, I suppose that's something you might be trying to do as it's in the for loop as well)
Also, I suggest you use mysqli.
And, this:
echo "<div>
<span>Lesson ".$i."</span>
</div>
<br>";
Will just echo the $i as both lesson= and the span with Lesson, which won't grab any information from the actual database but just go with the current number it's at, from the for loop you have.
i have made some changes in your code try this
<?php
$server = 'localhost';
$username = 'root';
$password = '';
$database = 'project';
$conn = mysql_connect($server,$username,$password) or die(mysql_error());
mysql_select_db($database, $conn) or die(mysql_error());
$sql = "SELECT `lesson` FROM `lessonno`";
$lesson = $_POST['lesson'];
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_assoc($result))
{
$lesson_no = $row['lesson'];
echo "<div>
<span>Lesson ".$lesson_no."</span>
</div>
<br>";
}
?>
Note : mysql_* is deprecated. use mysqli_* OR PDO
For getting Values from DB you need to use something like this
while ($row = mysql_fetch_assoc($result)) {
print_r($row);
}
For further reference please visit http://in2.php.net/manual/en/function.mysql-fetch-assoc.php
For counting the number of data in your database, just insert this code
$sql = "SELECT 'lesson' FROM 'lessonno'";
$lesson = $_POST['lesson'];
$result = mysql_query($sql);
$count=mysql_num_rows($result);//this will count the number of rows in your table.
echo "<div>
<span>Lesson ".$count."</span>
</div>
<br>";
I have two rows in my MySQL data that I would like to have code echoed only if the MySQL row data is equal to '1' (as opposed to '0'). Here's the code so far, which seems to have some severe errors:
$query = "SELECT 162, 164 FROM search WHERE title = $title";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_row()) {
if ($row["162"] = 1) {
echo '<div id="162link">1.6.2</div>';
}
}
if ($row["164"] = 1) {
echo '<div id="162link">1.6.2</div>';
}
}
}
$result->close();
}
$mysqli->close();
As it says in the code above the two rows are "162" and "164" in the database.
Use:
if ($row["162"] == 1)
Instead of:
if ($row["162"] = 1)
and:
if ($row["164"] == 1)
I tried for you something like this if it gives you some idea:
$host = "localhost";
$user = "myusername";
$pass = "mypassword";
$database = "WorldEngine";
$mysqli = new mysqli($host, $user, $pass, $database);
$title = "My Good News";
$query = "SELECT `162`, `164` FROM search WHERE title = '$title';";
if ($result = $mysqli->query($query)) {
$i = 0;
while ($row = $result->fetch_row()) {
if ($row["162"] == 1) {
echo '<div id="162link' . $i . '">1.6.2</div>';
}
if ($row["164"] == 1) {
echo '<div id="164link' . $i . '">1.6.4</div>';
}
$i++;
}
$result->free();
}
$mysqli->close();
The index $i is appended to the div ID in order to produce unique DOM element ID's in the HTML document. I would also suggest you to change your numerical column names into alphabet-starting names like c162, c164, ...
Hope this will help you.
ok i make this one but i have 83000 words in mysql database when i execute this script it will take too much time and some time it not runs. i think this script match every title in mysql database wather it is in the $row['full_story'] or not. so this make the opreation unusable if there is any method i can make this process faster ? or it just match those titles which are used $row['full_story'] code is below
$user_name = "root";
$password = "";
$database = "salar";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$SQL = "SET NAMES 'utf8'";
mysql_query($SQL);
$SQL = "SELECT * FROM dle_mylinks ORDER BY LENGTH( title ) DESC";
$result = mysql_query($SQL);
while ($db_field = mysql_fetch_assoc($result)) {
$row['full_story'] = str_replace ($db_field['title'],"" . $db_field['title'] . "" ,$row['full_story']);
$row['short_story'] = str_replace ($db_field['title'],"" . $db_field['title'] . "" ,$row['short_story']);
}
$mydata =$row['short_story'] . $row['full_story'];
mysql_close($db_handle);
}
else {
print "Database NOT Found ";
mysql_close($db_handle);
}
You'll want to iterate through each row in the table in a loop.
Example:
$query = mysql_query("SELECT * FROM `table`");
while($row = mysql_fetch_object($query)){
$mydata = str_replace($row->word,$row->meaning,$mydata);
}
Be careful with str_replace, If you want to replace 'distance' per 'thistance' and after it, replaces 'this' by 'dis' you get 'distance' again (it's a word game, an aproximation to the issue)
Use preg_replace.
Create two arrays (zend framework fetchCol or your favorite lib)
$aWords = $zfDb->fetchCol('select words from table');
$aMeans = $zfDb->fetchCol('select means from table');
And
$mydata = preg_replace($aWords, $aMeans, $mydata);