**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);
}
Related
function getConnection() {
$con = new mysqli('localhost','root','','shop');
if($con->connect_errno!=0){return null;};
$con->query("SET NAMES utf8");
return $con;}
function getRed(){
$con = getConnection();
$sql = "SELECT red FROM colors;";
$result = mysqli_query($con, $sql);
$row = mysqli_num_rows($result);
if($row["red"] == ""){
echo "";
}else{
while($row = mysqli_fetch_assoc($result)){
echo "<input type='image' src=" . $row["red"]. ">";
}
mysqli_close($con);}}
In PHP I have row "red" filled with link to MShirt/redshirt.png. This code should create an input with this image but if is empty shouldn't create input. Now, this doesn't work even with a filled row.
You have a number of problems with your code, but the main one is that mysqli_num_rows() does not return data. It tells you how many records were fetched from the database into PHP.
You don't need mysqli_num_rows() in your code.
You don't need mysqli_close($con);, especially not inside of the loop.
You don't need the while loop. This is an old way of iterating. Use foreach instead.
You don't need if/else and echo "". You only need the positive condition.
Here is your code fixed:
function getConnection() {
// enabler error reporting, create an instance and set the correct charset
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$con = new mysqli('localhost', 'root', '', 'shop');
$con->set_charset('utf8mb4');
return $con;
}
function getRed() {
$con = getConnection();
$sql = "SELECT red FROM colors;";
$result = $con->query($sql);
foreach ($result as $row) {
if ($row["red"] != "") {
echo "<input type='image' src=" . $row["red"] . ">";
}
}
}
The function mysqli_num_rows() returns only the count of results returned by your query, the mysqli_fetch_assoc() is the one going through the results. I would suggest taking the mysqli_close($con); outside the if statement as shown.
<?php
function getConnection() {
$con = new mysqli('localhost','root','','shop');
if($con->connect_errno!=0){return null;};
$con->query("SET NAMES utf8");
return $con;}
function getRed(){
$con = getConnection();
$sql = "SELECT red FROM colors;";
$result = mysqli_query($con, $sql);
$rowCount = mysqli_num_rows($result);
if($rowCount > 0) {
while($row = mysqli_fetch_assoc($result)){
if(isset($row["red"]) && $row["red"] != "") {
echo "<input type='image' src=" . $row["red"]. ">";
}
}
}
mysqli_close($con);
}
I don't know what this input should work for, but I assume you want to simply embed an image. Use it like this:
$result = mysqli_query($con, $sql);
while ($row= mysqli_fetch_assoc($result)) {
echo '<img src="' . $row['red']. '" />';
}
mysqli_num_rows is used to count how many rows are in the result, it returns the number of rows which you can not read like an array...
$result = mysqli_query($con, $sql);
$row_count = mysqli_num_rows($result);
echo $row_count.' rows in result.';
while ($row = mysqli_fetch_assoc($result)) {
echo '<img src="' . $row['red']. '" />';
}
Please make sure to understand basic HTML before getting into PHP and MySQL, also do not do database queries without getting to know proper security standards.
I'm running a query to get the contents for a web slider.
$serverName = "livedata";
$connectionInfo = array( "Database"=>"DB", "UID"=>"User", "PWD"=>"PWD" );
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "SELECT Sliders.DisplayFrom, Sliders.DisplayUntil, Sliders.Sort, Sliders.Image, Sliders.Link, Sliders.Target FROM Sliders WHERE (((Sliders.DisplayFrom)<GetDate()) AND ((Sliders.DisplayUntil)>getdate())) ORDER BY Sliders.sort;";
$stmt = sqlsrv_query( $conn, $sql);
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
$result = sqlsrv_query($conn, $sql);
$maxx = 0;
while($row = sqlsrv_fetch_array($result)) {
$maxx++;
}
while($row = sqlsrv_fetch_array($result)) {
echo “<br>” . $row[‘Image’];
}
The second loop does not output any results. why? Is it because $row is already at the end? If so, how do I move first like in ASP without having to create $result2 and $row2, 3, 4, 5, ...
Would it be better to use for loops like in vb.net?
for ($i = 0; $i <= $maxx; $i++){
}
But then How do I specify the output if I have no $row?
and if I only wanted to output the first row like I do in vb.net, how would I write the following in PHP?
dsqueryResults.tables(0).rows(0).item("Image");
would I still use a while loop and have a variable inside the loop to hold the row number and only output if row = 0?
$WhichRow = 0;
while($row2 = sqlsrv_fetch_array($result2)) {
if ($whichRow == 0){
echo “<br>” . $row2[‘Image’];
}
$WhichRow++;
}
Use the $max++ counter inside the while loop if you really want to use that for other purposes.
If you just want a count then run a count query on MySQL or do an array count of returned result.
If you just want to print 1 row use
LIMIT 0,1
at the end of your query as there's no point in fetching all rows and waste resources.
Based on additional comments you can try this to get your current row number.
$result = sqlsrv_query($conn, $sql);
$rownumber = 0;
while($row = sqlsrv_fetch_array($result)) {
$rownumber = $rownumber + 1;//Your current row number.
echo “<br>” . $row[‘Image’];
}
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);
I have an iOS app which I built an API to extract some data from a SQL Server database. When my app sends a query with an empty string, it doesn't return any rows, even though it should.
$connectionInfo = array( "Database"=>db, "UID"=>$user, "PWD"=>$pass);
$conn = sqlsrv_connect($ip, $connectionInfo);
if ( $conn ) {
//connected
}
else {
echo "Error:"; echo "<br>";
die( print_r( sqlsrv_errors(), true));
}
/**************************************/
/* RETRIEVAL */
/**************************************/
$prod = new StdClass(); $arr = array(); $temp = array();
$search = $_GET['search'];
$search = "%$search%";
$sql = "SELECT
name, qty
FROM
table
WHERE
name LIKE ?";
$stmt = sqlsrv_prepare( $conn, $sql, array($search));
sqlsrv_execute( $stmt );
$i = 0;
if ( $stmt === false ) {
die( print_r( sqlsrv_errors(), true) );
}
else {
while ( $row=sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC) ) {
$newProd = clone $prod;
$newProd->mainInfo = $row['name'];
$newProd->secondInfo = $row['qty'];
$arr[] = $newProd;
}
}
http_response_code(200);
echo json_encode($arr);
sqlsrv_close($conn);
I built the API with PHP and Apache on macOS where it worked as intended. When I copied the files on a Windows server, if my app accessed a link similar to 192.168.0.102/file.php?search= it would return no rows on Windows, and in macOS it would return all the rows of the table, as I wanted to. I know the script works and there are no issues, because if my app accesses a link similar to 192.168.0.102/file.php?search=someName it returns the corresponding rows. I want the app to display all the rows if the variable search is empty. Should I use some other way to achieve this, or is it some mistake on my part.
you can achieve that by not using sql condition when "search" $_GET param is not supplied or is empty.
Example how to achieve that, change your code from:
$search = $_GET['search'];
$search = "%$search%";
$sql = "SELECT
name, qty
FROM
table
WHERE
name LIKE ?";
to something like this:
$search = null;
if (true === array_key_exists('search', $_GET) && false === empty($_GET['search'])) {
$search = '%' . $_GET['search'] . '%';
}
$sql = "SELECT name, qty FROM table";
if (false === is_null($search)) {
$sql .= ' WHERE name LIKE ?';
}
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
}
?>