I've created a html+php page wherein it searches in a mysql database. I am able to get output when my table contains a few records but when my table has over 100+ records it would no longer show records when i search and shows my else statement which is "0 records".
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if(!empty($sfname) || !empty($sgen) || !empty($sdoc) || !empty($smisc) || !empty($ssick) || !empty($sothers) ){
$genQueryPart = !empty($sgen) ? "Gender LIKE '%$sgen%'" : "";
$fnameQueryPart = !empty($sfname) ? "FullName LIKE '%$sfname%'" : "";
$docQueryPart = !empty($sdoc) ? "Doctor LIKE '%$sdoc%'" : "";
$miscQueryPart = !empty($smisc) ? "Misc LIKE '%$smisc%'" : "";
$sickQueryPart = !empty($ssick) ? "Sickness LIKE '%$ssick%'" : "";
$othersQueryPart = !empty($sothers) ? "Others LIKE '%$sothers%'" : "";
$arr = array($genQueryPart, $fnameQueryPart,$docQueryPart,$miscQueryPart,$sickQueryPart,$othersQueryPart);
$sql = "select * from index where ";
$needsAnd = false;
for ($i = 0; $i < count($arr); $i++) {
if ($arr[$i] != "") {
if ($needsAnd) {
$sql .= " AND ";
}
$needsAnd = true;
$sql .= " " . $arr[$i];
}
}
//Get query on the database
$result = mysqli_query($conn, $sql);
mysqli_store_result();
//Check results
if (mysqli_num_rows($result) > 0)
{
//Headers
echo "<table border='1' style='width:100%'>";
echo "<tr>";
echo "<th>File ID</th>";
echo "<th>Full Name</th>";
echo "<th>Gender</th>";
echo "<th>Doctor</th>";
echo "<th>Misc</th>";
echo "<th>Sickness</th>";
echo "<th>Others</th>";
echo "</tr>";
//output data of each row
while($row = mysqli_fetch_assoc($result))
{
echo "<tr>";
echo "<td>".$row['FileID']."</td>";
echo "<td>".$row['FullName']."</td>";
echo "<td>".$row['Gender']."</td>";
echo "<td>".$row['Doctor']."</td>";
echo "<td>".$row['Misc']."</td>";
echo "<td>".$row['Sickness']."</td>";
echo "<td>".$row['Others']."</td>";
echo "</tr>";
}
echo "</table>";
}
else {
echo "0 results";
}
} else {
echo "You must enter at least one value";
}
mysqli_close($conn);
?>
Use if condition and paging to show more than 100 records after search. count the number of results after that use paging query to show records per page .This will be good idea for displaying large number of records.
Don't Merge Php and Html together . fetch the record in a function and use is to integrate in HTML
Related
The below code works perfectly and gives me the "id" "firstname" and "lastname". What I want is to use a loop to echo all the field values in the result row without having to quote each column name like
$row["id"]
below is the working code
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<br> id: ". $row["id"]. " - Name: ". $row["firstname"]. " " .
$row["lastname"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
any thoughts please
This should work..
while($row = $result->fetch_array()) {
$i=0;
while($i<count($row)){
echo $row[$i];
$i++;
}
}
just use a foreach loop inside while like this
foreach($row as $key=>$value){
echo "<br> $key: ". $value. "<br>";
}
If I understand what you want to do is automate the output of the name of each column with its value (independent of the number of columns you get).
So do it like this :
if ($result->num_rows > 0) {
foreach($result->fetch_assoc() as $row) { // browse each records
foreach($row as $col => $value) { // browse each columns on a record
echo "<br>$col: $value<br>";
}
}
}
else {
echo "no result";
}
How can I add pagination to a search engine results page?
I have build a search engine but there are hundreds of thousands of results for every search so I want to add pages to it.
The results of the search engine are outputted in a table.
I have started to learn php and sql recently...
How can I add those pages?
I have tried this so far but with no success:
<?php
$con = mysqli_connect(xxxx);
mysqli_select_db($con, 'Data') or die("could not find the database!");
$output = '';
$results_per_page = 1000;
//positioning
if(isset($_GET['search']))
{
$starttime = microtime(true); //TIME
$searchkey = $_GET['search'];
$query = mysqli_query($con, "SELECT * FROM table1 WHERE email LIKE '%$searchkey%'") or die("Could not search") ;
$count = mysqli_num_rows($query);
// count number of pages for the search
$number_of_pages = ceil($count/$results_per_page);
// determine which page number visitor is currently on
if (!isset($_GET['page']))
{
$page = 1;
}
else
{
$page = $_GET['page'];
}
// LIMIT
$this_page_first_result = ($page-1)*$results_per_page;
if ($count == 0)
{
echo "</br>";
$output = 'There are no search results !' ;
}
else
{
echo '<table class="myTable">';
echo "<tr><th>aaa</th><th>bbb</th></tr>";
$query = mysqli_query($con, "SELECT * FROM table1 WHERE email LIKE '%$searchkey%' LIMIT " . $this_page_first_result . ',' . $results_per_page" ") or die("Could not search") ;
while ($row = mysqli_fetch_array($query))
{
$email = preg_replace('/(' . $searchkey . ')/i', '<mark>\1</mark>', $row["aaa"]);
$password = $row['bbb'];
echo "<tr><td>";
echo $aaa;
echo "</td><td>";
echo $bbb;
echo "</td></tr>";
$output = '</table>';
}
//echo "</table>";
$endtime = microtime(true);
$duration = $endtime - $starttime;
echo "</br>";
if ($count == 1)
{
echo "<div class=resinfo>";
echo '<div>'."1 result was found for '$searchkey' in $duration seconds.".'</div>'.'</br>';
echo "</div>";
}
else
{
echo "<div class=resinfo>";
echo '<div>'."$count results were found for '$searchkey' in $duration seconds.".'</div>'.'</br>';
echo "</div>";
}
}
echo $output;
}
//LINKS to other pages
for ($page = 1; $page<=$number_of_pages;$page++){
echo '' . $page . '';
}
?>
What have I done wrong, what can I improve to make it work?
Thanks a lot for your help!
It is not a good idea to build a pagination from scratch, instead use a lib like this: https://github.com/KnpLabs/knp-components/blob/master/doc/pager/intro.md
Basically I'm doing digital signage and I'm trying to get names to be pulled from a MySQL database to a PHP page. Right now its all centered in one column, but I want the results to be in two columns side by side. How can I do this?
$sql = "SELECT * FROM donor WHERE DonationAmount = 5000 AND Category = '1' or DonationAmount = 5000 AND Category IS NULL ORDER BY LastName ASC";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
// test if the DisplayName field is empty or not
if(empty($row['DisplayName']))
{
// it's empty!
if(empty($row['FirstName'])){
echo $row['LastName']. "<br>";
}
else{
echo $row["LastName"]. ", " . $row["FirstName"]. "<br>";
}
}else{
// Do stuff with the field
echo $row["DisplayName"]. "<br>";
}
}
} else {
}
Basically I want this data to be spread across two columns instead of 1 single page.
output the strings like this:
echo "<span style=\"width:50%;float:left;\">".$row['LastName']."</span>";
do not forget to remove <br /> from each output
You can use tables, and count the rows to determine if you need to start a new table row.
$i = 0;
$total_rows = $result->num_rows;
echo "<table><tr>";
while($row = mysqli_fetch_assoc($result)) {
// test if the DisplayName field is empty or not
echo "<td>";
if(empty($row['DisplayName']))
{
// it's empty!
if(empty($row['FirstName'])){
echo $row['LastName'];
}
else{
echo $row["LastName"]. ", " . $row["FirstName"];
}
}else{
// Do stuff with the field
echo $row["DisplayName"]. "";
}
echo "</td>";
$i++;
if($i % 2 == 0 && $i != $total_rows) {
echo "</tr><tr>";
}
}
echo "</tr></table>";
if your content is in <div id="myDiv"> use this JS function and call it after the content loads
function splitValues() {
var output = "";
var names = document.getElementById('myDiv').innerHTML.split("<br>");
for(var i in names) {
output += "<span style=\"width:50%;float:left;display:inline-block;text-align:center;\">"+names[i]+"</span>";
}
document.getElementById('myDiv').innerHTML = output;
}
This script allows the user to choose a table from the dropdown and then displays the contents of the chosen table.
At the moment the DB connection is working.
A list of tables is shown in the dropdown.
Problem: No content from the database table is shown.
I have checked through the code and everything looks OK, but it still only seems to partially work.
<?php
//update this to your DB connection details.
$dbh = "localhost";
$dbn = "dbname";
$dbu = "dbuser";
$dbp = "dbpass";
$conn = mysql_connect($dbh,$dbu,$dbp) or die("Unable to connect do database.");
mysql_select_db($dbn, $conn) or die("Unable to select database.");
//Some vars for Order by and Limit.
if (!isset($ordBy)){
$ordBy = 1;
}
if (!isset($ps)){
$ps = 0;
}
if (!isset($ord)){
$ord = 1;
}
if ($ord == 1){
$tOrder = "ASC";
} else {
$tOrder = "DESC";
}
//Tables drop-down
$result = mysql_query("SHOW TABLES FROM $dbn") or die("Cannot list table names.");
echo "
<form name=\"table_browser\" action=\"".$PHP_SELF."\" method=\"GET\" >
<select name=\"t\" onChange=\"javascript:submit();\">
<option>Select a table</option>
";
while ($row = mysql_fetch_row($result)){
echo " <option value=".$row[0].">".$row[0]."</option>\n";
}
echo " </select>
</form>\n";
if (!isset($t)){
die("Please select a table");
}
//Get number of rows in $t and then select
$result = mysql_query("SELECT COUNT(*) FROM $t") or die("The requested table doesn't exist.");
$total = mysql_result($result,0);
$qry = "SELECT * FROM $t ORDER BY ".$ordBy." ".$tOrder." LIMIT ".($ps*20).",20 ";
if (isset($qry)) {
$result = mysql_query($qry) or die("The requested table doesn't exist.");
$i = 0;
while ($i < mysql_num_fields($result)) {
$meta = mysql_fetch_field($result);
if (!$meta) {
echo "No information available on the table<br />\n";
}
$name[$i] = $meta->name;
$i++;
}
//Display table details
echo "Rows ".($ps*20+1)." to ".((($ps+1)*20 < $total) ? (($ps+1)*20) : ($total))." of $total from table:
<b>$meta->table</b>\n<br /><br />\n";
//Count results
if ($ps > 0) {
echo "20 Previous - ";
} else {
echo "20 Previous - ";
}
if ((($ps+1)*20) < $total ){
echo "Next 20\n";
} else {
echo "Next 20\n";
}
//Column names
echo "<br /><br />\n<table>\n <tr>\n";
for ($j = 0; $j < $i; $j++){
echo " <td><b>$name[$j]</b>";
if ($ordBy == $name[$j]) {
echo "<img src=\"images/arrow$ord.gif\">";
}
echo "</td>\n";
}
echo " </tr>\n";
//Data
while ($row = mysql_fetch_array($result)){
echo " <tr onmouseover=\"this.style.background='#DDDDDD'\" onmouseout=\"this.style.background=''\">";
for ($j = 0; $j < $i; $j++){
echo "<td>".$row[$name[$j]]."</td>";
}
echo "</tr>\n";
}
echo "</table>\n";
}
mysql_close();
?>
#gentlebreeze - my eyes hurt from trying to read that - but I can't see where you are actually setting the variable called $t - which is used to determine the table. You should have
$t = $_GET['t'];
somewhere before the line:
....if (!isset($t)){....
because you need to use it in the line:
....$result = mysql_query("SELECT COUNT(*) FROM $t"....
and you should not be using mysql_query either - old and now deprecated. You should switch to PDO and bound variables.
My search form works when I'm querying in a database with around 10 records only, but when I go more than that, it doesn't show any records and goes to my else "0 records" Please help, below is my php code.
<?php
$sfname = $_POST["fname"];
$sgen = $_POST["gen"];
$sdoc = $_POST["doc"];
$smisc = $_POST["misc"];
$ssick = $_POST["sick"];
$sothers = $_POST["others"];
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if(!empty($sfname) || !empty($sgen) || !empty($sdoc) || !empty($smisc) || !empty($ssick) || !empty($sothers) ){
$genQueryPart = !empty($sgen) ? "Gender LIKE '%$sgen%'" : "";
$fnameQueryPart = !empty($sfname) ? "FullName LIKE '%$sfname%'" : "";
$docQueryPart = !empty($sdoc) ? "Doctor LIKE '%$sdoc%'" : "";
$miscQueryPart = !empty($smisc) ? "Misc LIKE '%$smisc%'" : "";
$sickQueryPart = !empty($ssick) ? "Sickness LIKE '%$ssick%'" : "";
$othersQueryPart = !empty($sothers) ? "Others LIKE '%$sothers%'" : "";
$arr = array($genQueryPart, $fnameQueryPart,$docQueryPart,$miscQueryPart,$sickQueryPart,$othersQueryPart);
$sql = "select * from index where";
$needsAnd = false;
for ($i = 0; $i < count($arr); $i++) {
if ($arr[$i] != "") {
if ($needsAnd) {
$sql .= " AND ";
}
$needsAnd = true;
$sql .= " " . $arr[$i];
}
}
//Get query on the database
$result = mysqli_query($conn, $sql);
//Check results
if (mysqli_num_rows($result) > 0)
{
//Headers
echo "<table border='1' style='width:100%'>";
echo "<tr>";
echo "<th>File ID</th>";
echo "<th>Full Name</th>";
echo "<th>Gender</th>";
echo "<th>Doctor</th>";
echo "<th>Misc</th>";
echo "<th>Sickness</th>";
echo "<th>Others</th>";
echo "</tr>";
//output data of each row
while($row = mysqli_fetch_assoc($result))
{
echo "<tr>";
echo "<td>".$row['FileID']."</td>";
echo "<td>".$row['FullName']."</td>";
echo "<td>".$row['Gender']."</td>";
echo "<td>".$row['Doctor']."</td>";
echo "<td>".$row['Misc']."</td>";
echo "<td>".$row['Sickness']."</td>";
echo "<td>".$row['Others']."</td>";
echo "</tr>";
}
echo "</table>";
}
else {
echo "0 results";
}
} else {
echo "You must enter at least one value";
}
mysqli_close($conn);
?>
Have you tried buffering the results?
$result = mysqli_query($conn, $sql);
mysqli_store_result($conn);
if(mysqli_num_rows($result) > 0) {
...
}
from PHP Manual:
The behaviour of mysqli_num_rows() depends on whether buffered or unbuffered result sets are being used. For unbuffered result sets, mysqli_num_rows() will not return the correct number of rows until all the rows in the result have been retrieved.
May be issue with your empty() function (depends on your data), use isset() instead.
empty() : will return true if the variable is an empty string, false, array(), NULL, “0?, 0, and an unset variable.
isset() : will return true only when the variable is not null.
EDIT
User got answer from my comments below
Try debug like this: print $sql before the mysqli_query, copy sql in phpmyadmin and check the query result and query itself.