Forum Moderators: coopster

Message Too Old, No Replies

how to search using binary search from data from table in php

the data i used in from the table and i have change into array

         

dayanadolce

9:43 am on Dec 21, 2014 (gmt 0)

10+ Year Member



i have update my source code like this.
<form action="" method="post" enctype="multipart/form-data">

<html>
<input name="studentid" type="radio" value="2013234321">2013234321


<br>
<input type="submit" name="submit" value="Search" />

</form>
</html>

<?php
if (isset($_POST['submit']))
{

$se = $_POST['studentid'];
function binarySearch($array, $searchFor)
{
$low = 0;
$high = count($array) - 1;
$mid = 0;

while ($low <= $high)
{
$mid = floor(($low + $high) / 2);
$element = $array[$mid];

if ($searchFor == $element)
{
return $mid;
}
else if ($searchFor < $element)
{
$high = $mid - 1;
}
else
{
$low = $mid + 1;
}

}
echo "Unsuccess";
}

function generateOrderedArray()
{
$db = mysql_connect("localhost", "root", "");
mysql_select_db("dbehomebooking",$db);
$query = "SELECT studentid FROM approval";
$array = mysql_query($query) or die ('<p>' . mysql_error());
while ($row = mysql_fetch_array($array))
{
echo '<br>',$row['studentid'];
}
return $array;
}


$binaryArray = generateOrderedArray();

print (binarySearch($binaryArray, $se));

}
?>


the function generateOrderedArray() is function really well. as it display the data from the table 'approval' However, when i want to search one of the data, example, i want to search '2013234321' , using binarysearch() function, there is an error. why is that?

0
2013234321
2012345431Unsuccess

lammert

1:58 pm on Dec 21, 2014 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



First of all Welcome to WebmasterWorld!

This is not a board where we try to fix specific programming errors in source code of members, but we rather try to discuss possible solutions for more general problems.

In your case, you use a fairly simple lookup of all the student codes from a table and compare these in a PHP loop with a code entered from a web form. This uses significant resources, both on the SQL server side which has to generate all student codes, and on the PHP side where all the codes first have to be stored, and then traversed to search the right one.

In such a case it might be better to use a more intelligent SQL query with the WHERE clause to search for the existence of that specific student code. This will not only eliminate the entire search function you have written in PHP, but the SQL query will also return much faster, assuming you have proper indexes on the table "approval".

You can find more information about the WHERE clause in the MySQL documentation.

dayanadolce

3:44 am on Dec 23, 2014 (gmt 0)

10+ Year Member



thanks for reply. i have fix the code. i already known about Where clause. the reason i want to use binary search is because that's is my homework. but it's alright. i have fixed it.