bradboy bradboy - 1 month ago 20
MySQL Question

php mysql search continues forever

I'm trying to create a basic "search my table columns for all rows that match, and show me the rows" type search. What I ended up with is a query that repeats forever, and the resulting webpage never stops loading. Classic example of a loop that can't end. I don't know why though. I'm trying to keep each little step in it's own function like a good boy, and reusing functions.

A person should be able to search for question or john to return one row, plus or minus looks like two rows, and test will return three rows.

Please help!

function databaseconnection($sql){
$usernm="XXXfooXXX";
$passwd="XXXfooXXX";
$host="XXXfooXXX";
$database="contact_info";
mysql_connect($host,$usernm,$passwd);
mysql_select_db($database);
$result = mysql_query ($sql) or die (mysql_error ());
return $result;
}

function searchtable(){
echo 'searchtable() <br />';
if ($_POST['search'] != "" ){
$search = preg_replace('/[^ \wa-zA-Z0-9_.@()\-+~,?]+/', '', $_POST['search']);
}
if ($search){
$sql = "SELECT * FROM names_numbers WHERE name LIKE \"%{$search}%\"".
" OR phone_address LIKE \"%{$search}%\"".
" OR notes LIKE \"%{$search}%\"";
echo 'attempting sql action<br />';
echo "$sql <br />";
while ($row = mysql_fetch_assoc(databaseconnection($sql))){
print_r($row);
}
}
}

function draw_search_form(){
echo '<form action="./numbers.php" method="post">'."\n";
echo 'notes:<br>'."\n";
echo '<input type="text" name="search"><br>'."\n";
echo '<input type="submit" value="Submit">'."\n";
echo '</form>'."\n";
}

Answer

I believe in your while loop, you are executing the query every time, which resets your result iterator. When you switch to mysqli or PDO you can refactor to run the query once, then iterate over the results.

$results = databaseconnection($sql);
while($row = mysqli_fetch_assoc($results) {
    ...
}