php mysql search continues forever - php

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";
}

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) {
...
}

With your current while loop, you are opening a new database connection, running the query and getting the first row again and again.
This can be easily fixed by moving your query out of database, and then iterating over the result
Here is the code with changes
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 />";
// Run the query once
$result = databaseconnection($sql);
// Now iterate over the results
while ($row = mysql_fetch_assoc($result)){
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";
}

posting as an answer, to make it easier to format the corrected function:
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 />";
$results = databaseconnection($sql);
while($row = mysql_fetch_assoc($results)) {
print_variable($row);
}
//while ($row = mysql_fetch_assoc(databaseconnection($sql))){
// print_variable($row);
//}
}
}

Man, you are providing an array into while which will always remain true. Please use foreach instead.
$row = mysql_fetch_assoc(databaseconnection($sql))
foreach ($row as $r){
print_r ($r)//extract associative elements
}

Related

MySQL, while Loop & comparison with in_array

here is the code:
$sql = "SELECT * FROM example";
$query = mysql_query($sql);
while ($array = mysql_fetch_array($query)) {
if (in_array($array['ipsum'], $page1)) {echo "<h2>correct</h2>"; break;}
else {echo "<h2>not correct</h2>";} }
echo "<div id=\"nucleo\"><h3>lorem ipsum</h3><h1>";
echo $page1;
echo "</h1>";
I have a table with 2 rows in the database: first one is lorem the second one is ipsum (both are INT).
The table is manually compiled when it is needed.
What I want to do is to get the second row (ipsum) and create an array. I don't need to echo values of the array, but I need to compare it with a variable ($page1. this variable is a integer number and it changes continuously).
How could I fix it?
I think this should do what you are after. You should look into switching from the mysql functions/driver to the mysqli or PDO drivers.
<?php
$page1 = (int)$page1;//force $page1 to be an int to avoid SQL injections
$sql = "SELECT * FROM example where ipsum = " . $page1;
$query = mysql_query($sql);
if(mysql_num_rows($query) > 0) {
echo "<h2>correct</h2>";
} else {
echo "<h2>not correct</h2>";}
}
echo '<div id="nucleo">
<h3>lorem ipsum</h3>
<h1>' . $page1 . '</h1>';
http://php.net/manual/en/faq.databases.php#faq.databases.mysql.deprecated
http://php.net/manual/en/function.mysql-num-rows.php
You are using in_array() to compare two integer values. you should simply use the === operator like so:
$sql = "SELECT * FROM example";
$query = mysql_query($sql);
while ($array = mysql_fetch_array($query)) {
if ($array['ipsum'] === $page1) {
echo "<h2>correct</h2>";
break;
} else {
echo "<h2>not correct</h2>";
}
}
echo "<div id=\"nucleo\"><h3>lorem ipsum</h3><h1>";
echo $page1;
echo "</h1>";
I fixed it this way:
$array = array();
while ($row = mysql_fetch_array($query)) {
array_push($array, $row["ipsum"]);
}
if (in_array($page1, $array)) {echo "correct";}
else {echo "not correct"; }
I realized by using print_r that the array was not really how I though it was. This way above use all the row of a colums to compose the array... array([0] => row1 [1] => row2 and so on.
Thanks everyone for the help...I apologize for not being very clear about my problem.

mysql search using for loop from php

i am a beginner. but I'm practicing a lot for few days with php mysql, and I am trying to use for loop to search an exploded string, one by one from mysql server.
Till now I have no results.
I'm giving my codes,
<?php
// Example 1
$var = #$_GET['s'] ;
$limit=500;
echo " ";
echo "$var";
echo " ";
$trimmed_array = explode(" ", $var);
echo "$trimmed_array[0]"; // piece1
echo " ";
$count= count($trimmed_array);
echo $count;
for($j=0;$j<$count;$j++)
{
e cho "$trimmed_array[$j]";;
echo " ";
}
echo " ";
for($i=0; $i<$count ; $i++){
$query = "select * from book where name like \"%$trimmed_array[$i]%\" order by name";
$numresults=mysql_query($query);
$numrows =mysql_num_rows($numresults);
if ($numrows == 0)
{
echo "<h4>Results</h4>";
echo "<p>Sorry, your search: "" . $trimmed_array[i] . "" returned zero results</p>";
}
if (empty($s)) {
$s=0;
}
$query .= " limit $s,$limit";
$result = mysql_query($query) or die("Couldn't execute query");
echo "<p>You searched for: "" . $var . ""</p>";
echo "Results<br /><br />";
$count=1;
while ($row= mysql_fetch_array($result)) {
$name = $row["name"];
$publisher=$row["publisher"];
$total=$row["total"];
$issued=$row["issued"];
$available=$row["available"];
$category=$row["category"];
echo "<table border='1'><tr><td>$count)</td><td>$name </td><td>$publisher </td><td>$total </td><td>$issued </td><td>$available </td><td>$category </td></tr></table>" ;
$count++ ;
}
}
?>
In your case, you do for every record in your array ($trimmed_array) a new select. Thats not really good.
It would be better when you create just one select...
For example this:
// you need 1=1 for example when $i<count is false...
$baseQuery = "select * from book where 1=1";
$query = $baseQuery;
for($i=0; $i<$count ; $i++){
$query .= " OR name like ?";
}
// do your ordering:
$query.= " order by name";
But what does this "?" mean?
--> Do you know what sql-injection means? somebody could really easy put some information in this array wich could give any information about your database.. therefore you have to escape every userinput...
i like the mysqli package in php5. watch this example:
$query = "SELECT `id` FROM employees WHERE `name`=?";
// Setup parameter to be bound into query
$name = "Joey";
// Get instance of statement
$stmt = $mysqli->stmt_init();
// Prepare Query
if($stmt->prepare($query)){
// Bind Parameters [s for string]
$stmt->bind_param("s",$name);
// Execute statement
$stmt->execute();
// Bind result variables
$stmt->bind_result($employee_id);
// Fetch Value
$stmt->fetch();
// Echo results
echo "$name has an ID of $employee_id";
// Close Statement
$stmt->close();
}
Damn, your code really extremely crazy. Here you example about how to work with this:
<?php
$var = $_GET['s'];
$exp = explode(" ",$var);
$total = count($exp) - 1;
for($i = 0; $i <= $total; $i++) {
echo "Search for: " . $exp[$i] ."\n";
$sql = mysql_query("SELECT * FROM `book` WHERE `name` LIKE '%" . mysql_real_escape_string($exp[$i]) ."%'") or die(mysql_error());
if (mysql_fetch_num($sql) != 0) {
// Somthing found
}
}
?>
You have an error on line 25,
e cho "$trimmed_array[$j]";;
should be
echo "$trimmed_array[$j]";
Also, it seems that you are using $GET_[] variables, which are passed via the url string, which does not allow spaces. On line 15, you are splitting the array with explode(" ", $var);
I would also urge you, if you have not, look into sanitizing your database queries.

this program strip would output a searched directory but if not found must output a message

this program must output a directory that you searched for how ever if its not found a message must appear that the org_name is not found,i don't know how to do that, i keep trying on some if-else but it just won't output it.
<?php
$con=mysql_connect("localhost","root","");
if(!$con) {
die('could not connect:'.mysql_error());
}
mysql_select_db("final?orgdocs",$con);
$org_name = $_POST["org_name"];
$position = $_POST["position"];
$result = mysql_query("SELECT * FROM directory WHERE org_name = '$org_name' OR position = '$position' ORDER BY org_name");
echo '<TABLE BORDER = "1">';
$result1 = $result;
echo '<TR>'.'<TD>'.'Name'.'</TD>'.'<TD>'.'Organization Name'.'</TD>'.'<TD>'.'Position'.'</TD>'.'<TD>'.'Cell Number'.'</TD>'.'<TD>'.'Email-Add'.'</TD>';
echo '</TR>';
while ( $row = mysql_fetch_array($result1) ){
echo '<TR>'.'<TD>'.$row['name'].'</TD>'.'<TD>'.$row['org_name'].'</TD>';
echo '<TD>'.$row['position'].'</TD>'.'<TD>'.$row['cell_num'].'</TD>'.'<TD>'.$row['email_add'].'</TD>';
echo '</TR>';
}
echo '</TABLE>';
?>
What you want is mysql_num_rows to check your query for how many result rows it has.
http://de2.php.net/manual/en/function.mysql-num-rows.php
if (mysql_num_rows($result)>0) {
// your thing above with mysql_fetch_array($result1) etc
} else {
echo 'nor found';
}

Retrieving values from MySQL

I have a very simple table that contains a list of 'victims' and the corresponding number of that type destroyed. I'm trying to make an output page of this information, using this code:
foreach( $victims as $vic )
{
$hits = mysql_query("SELECT amount
FROM victims
WHERE victim = ".$vic );
echo $hits;
print "$vic: $hits <br /><hr>";
}
However, hits comes out empty. What's wrong with my SQL query?
foreach($victims as $vic)
{
$hits = mysql_query('SELECT amount
FROM victims
WHERE victim = "' . mysql_real_escape_string($vic) . '"');
if($hits && mysql_num_rows($hits)>0) {
while($row = mysql_fetch_array($hits)) {
echo '<p>' . $row['amount'] . ' hits</p>';
}
} else {
echo '<p>' . mysql_error() . '</p>';
}
}
mysql_query() doesn't return the actual result of your query, but rather a resource with which you can then access the results.
This is a typical pattern:
$result = mysql_query(...);
$row = mysql_fetch_assoc($result);
print($row['amount']);
Each call to mysql_fetch_assoc returns the next row of the result set. If you were expecting multiple rows to be returned, you can call this in a while loop:
$result = mysql_query(...);
while ($row = mysql_fetch_assoc($result)) {
print($row['amount']);
}
Since there's no sane error checking in any of the answers, I'll put the whole thing in here:
foreach( $victims as $vic )
{
$sql = "SELECT amount
FROM victims
WHERE victim = '".mysql_real_escape_string($vic)."'";
$result = mysql_query($sql);
$result or die('Query Error: '.mysql_error() . ' - ' . $sql);
$hitsarray = mysql_fetch_assoc($result);
if ($hitsarray) {
$hits = $hitsarray['amount'];
} else {
// No row was found
$hits = 0;
}
echo $hits;
print "$vic: $hits <br /><hr>";
}
Oh, and this fixes the query error that caused the issue in the first place. Note the quotes wrapping the $vic variable in the string, as well as the proper escaping of the string...

Checking querystring values in PHP

http://localhost/?area=characters&name=Michal+Stroganof
$result = mysql_query("SELECT * from players WHERE name = '$_GET[name]'");
while ($row = mysql_fetch_assoc($result)) {
echo "Name: " .$row['name']. "<br>";
echo "Level: " .$row['level']. "<br>";
}
This is all code of my characters.php
If the get variable "name" is not included in the URL i want to show a search form that searches the table players. How would I do this?
Do you mean just to change your SQL string like so?
$sql = 'SELECT * from players';
if (isset($_GET['name'])) {
$safename = mysql_real_escape_string($_GET['name']);
$sql .= " WHERE name='$safename'";
}
$result = mysql_query($sql);
Be sure to sanitize your SQL!
Use isset():
if (isset($_GET['name'])) {
// your above code
} else {
// display form
}
Quick and dirty:
<?php
if (!isset($_GET['name']))
{
echo '<form action="'. $_SERVER['PHP_SELF'] .'" method="GET">'
.'<input type="text" name="name" />'
.'</form>';
}
else
{
// your current code that queries your database here
}
?>

Categories