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
}
?>
Related
I'm creating a news website, and want to create a dynamic PHP page that will have the header and footer, and get the content itself (title and text) from the database by calling the article's id via the URL(like 'article.php?id=1'), so that there is no need for creating a new file for each article. However, I don't know what function should I use to make that work. Currently, the code is like this:
<?php
include "header.php";
$query = "SELECT title_article, subtitle_article, content_article FROM tb_article WHERE id_tb_article = 1";
$conn = mysqli_connect('127.0.0.1:3307', 'root', '', 'article') or die("error");
$result = mysqli_query($conn, $query);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<div class='titlediv'><h1 class='title'>" . $row["title_article"]. "</h1></div><div class='titlediv'><h3 class='title'>". $row["subtitle_article"]. "</h3></div><div class='textdiv'><p class='text'>" . $row["content_article"]. "</p></div><br>";
}
} else {
echo "Article not found";
}
include "footer.php";
?>
To get the id value from query string in URL, you can use the PHP's superglobal $_GET['id'].
To select a dynamic value from SQL using this value you must use prepared statements with parameter binding.
Your code with all the fixes would look more or less like this:
<?php
include "header.php";
$query = "SELECT title_article, subtitle_article, content_article FROM tb_article WHERE id_tb_article = 1";
// Enable mysqli error reporting and NEVER die()
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli('127.0.0.1:3307', 'root', '', 'article');
$conn->set_charset('utf8mb4'); // You should always specify the correct charset, which most of the time should be utf8mb4
// prepare -> bind -> execute -> get result
$stmt = $conn->prepare('SELECT title_article, subtitle_article, content_article
FROM tb_article
WHERE id_tb_article = ? ');
$stmt->bind_param('i', $_GET['id']);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows) {
// output data of each row
foreach ($result as $row) {
echo "<div class='titlediv'><h1 class='title'>" . htmlspecialchars($row["title_article"]). "</h1></div>";
echo "<div class='titlediv'><h3 class='title'>". htmlspecialchars($row["subtitle_article"]). "</h3></div>";
echo "<div class='textdiv'><p class='text'>" . htmlspecialchars($row["content_article"]). "</p></div><br>";
}
} else {
echo "Article not found";
}
include "footer.php";
Whenever output values into HTML context always do it via htmlspecialchars
You can use a GET method and the url look like 'article.php?id=2'.
<?php
include "header.php";
//use GET to get the id
$id = $_GET["id"];
// use .$id to concat to the query
$query = "SELECT title_article, subtitle_article, content_article FROM tb_article WHERE id_tb_article = ".$id;
$conn = mysqli_connect('127.0.0.1:3307', 'root', '', 'article') or die("error");
$result = mysqli_query($conn, $query);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<div class='titlediv'><h1 class='title'>" . $row["title_article"]. "</h1></div><div class='titlediv'><h3 class='title'>". $row["subtitle_article"]. "</h3></div><div class='textdiv'><p class='text'>" . $row["content_article"]. "</p></div><br>";
}
} else {
echo "Article not found";
}
include "footer.php";
?>
You want to look at the global variables $_GET and $_POST. In your example ('article.php?id=1') you will find the value of 'id' in $_GET['id'].
URL: article.php?id=42
echo $_GET['id']; // Outputs 42
Remember that anyone can change that value in the URL and even injecting malicious queries into your query. Its better to at least cast your id to an integer first and use always mysqli_real_escape_string() for URL given variables in the query.
URL: article.php?id=42;DROP TABLE tb_article
echo $_GET['id']; // Outputs "42;DROP TABLE tb_article", would delete your table when used directly
// Convert to an integer value
$id = intval($_GET['id']); // Returns 42
$query = "... FROM tb_article WHERE id_tb_article = ".mysqli_real_escape_string($id);
My php While loop run the query, but the results must be print inside html. In this moment I unknow the way to make this:
My php while loop
<?php
include "connect.php";
$username=$_SESSION['Username'];
$result = mysqli_query($dbconn,"
SELECT *
FROM books
WHERE username = '$Username'
");
while($rows = mysqli_fetch_array($result));
?>
After this code there is a Html code where I want print the variables:
Edit
In this moment the variable is empty
How to fix this?
[Resolved] Update
I have resolve my problem. This is the correct php script. Work fine:
<?php
include "connect.php";
$username=$_SESSION['Username'];
$result = mysqli_query($dbconn,"
SELECT *
FROM books
WHERE username = '$Username'
");
global $book_id, $book_name
while($row = mysqli_fetch_array($result)) {
$book_id = row['book_id'];
$book_name = row['book_name'];
?>
Outside while loop. Print variable inside Html:
<?php echo $row['book_id']; ?> <br>
<?php echo $row['book_name']; ?>
Close while loop and connection:
<?php
}
mysqli_close($dbconn);
?>
with prepared statements :
<?php
session_start();
$username = $_SESSION['Username'];
error_reporting(E_ALL);
ini_set('display_errors', 1);
include"config.inc.php";
/* connect to DB */
$mysqli = mysqli_connect("$host", "$user", "$mdp", "$db");
if (mysqli_connect_errno()) { echo "Error connecting : " . mysqli_connect_error($mysqli); }
$query = " SELECT * FROM books WHERE username=? ";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("s", $username);
$results = $stmt->execute();
$stmt->bind_result($book_id, $book_name);
$stmt->store_result();
if ($stmt->num_rows > 0) {
while($stmt->fetch()){
?>
<p><?php echo"$book_name"; ?> > Edit</p>
<?php
}
}
else
{ echo"[ no data ]"; }
?>
(Rewriting)
The real issue is:
while ($rows = ...) ;
This loops until $rows is NULL. So there is nothing to display afterwards.
Since you are fetching the entire array in a single function call, there is no need for the loop!
$rows = ...;
But then you need to reference the first(?) row to get the desired data:
$row = $rows[0];
So, another approach is to just fetch one row, then close the fetch process.
In your html you have to do this
Edit
As there might be multiple books for each user, you have to print the link inside the while loop, or store it in a string:
<?php
include "connect.php";
$username = $_SESSION['Username'];
$result = mysqli_query($dbconn,"
SELECT * FROM books
WHERE username = '$Username'
");
$links = ""; // all links are stored in this string
while($rows = mysqli_fetch_array($result)) {
// I assume that the columns are called `id` and `name`
$links .= 'Edit '. $rows["name"] .'';
}
?>
In the html code simply write
<?php echo $links ?>
Note that you should use prepared statements instead. You should also take a look at the object oriented way to use mysqli using the mysqli class.
**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);
}
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).
I've been trying for days to create a simple search engine to search for information in my database. The table is myisam and I get search results when using mysql to search directly in phpmyadmin. So the problem seams to be with the PHP.
When searching all I get is an empty page. I've tried serveral varieations of code I've found in online tutorials, but nothing seems to work. I hope there is a simple solution that I'm too dumb to see, and I hope someone can explain to me how to do this.
if(!empty($_POST['search'])){
$search = $_POST['search'];
$sqlString = "SELECT * FROM test WHERE MATCH (title, about) AGAINST ('$search')";
$result = mysqli_query($dbLink, $sqlString) or die("Could not search.." . mysqli_error($dbLink));
$row = mysqli_fetch_assoc($result);
if($result-> num_rows > 0){
while($row = mysqli_fetch_assoc($result)){
$title = $row['title'];
echo $title;
}
}else{
echo 'No results';
}
}
if(!empty($_POST['search'])){
$search = $_POST['search'];
$sqlString = "SELECT * FROM test WHERE MATCH (title, about) AGAINST ('$search')";
$result = mysqli_query($dbLink, $sqlString) or die("Could not search.." . mysqli_error($dbLink));
$row = mysqli_fetch_assoc($result); // remove it
if($result-> num_rows > 0){
while($row = mysqli_fetch_assoc($result)){ // already exist
$title = $row['title'];
echo $title;
}
}else{
echo 'No results';
}
}
Change
if($result-> num_rows > 0)
To
if(mysqli_num_rows($result) > 0)