Jump to content

PHP errors with SQL query and my exhausted brain


kaisaj

Recommended Posts

Help.  I used the great Simple SQL search tutorial provided by this site, but when I tried to customize it for my site, it keeps falling apart.  I am a newbie, but any disgust at my idiocy is fine as long as I find a ball of string to lead me out of the labyrinth.

 

Here's the code (modified from the tutorial) sans the login information:

 

$con = mysql_connect($dbHost, $dbUser, $dbPass) or trigger_error("Failed to connect to MySQL Server. Error: " . mysql_error());

 

 

mysql_select_db($dbDatabase) or trigger_error("Failed to connect to database {olsendai_ssn}. Error: " . mysql_error());

 

// Set up our error check and result check array

$error = array();

$results = array();

 

// First check if a form was submitted.

// Since this is a search we will use $_GET

if (isset($_GET['search']))

  $searchTerms = trim($_GET['search']);

  $searchTerms = strip_tags($searchTerms); // remove any html/javascript.

 

  if (strlen($searchTerms) < 3) {

      $error[] = "Search terms must be longer than 3 characters.";

  }else {

      $searchTermDB = mysql_real_escape_string($searchTerms); // prevent sql injection.

  }

 

 

  // If there are no errors, lets get the search going.

  if (count($error) < 1) {

      $searchSQL = "SELECT name, ssn FROM simple_search WHERE ";

     

      // grab the search types.

      $types = array();

      $types[] = isset($_GET['name'])?"`name` LIKE '%{$searchTermDB}%'":'';

      $types[] = isset($_GET['ssn'])?"`ssn` LIKE '%{$searchTermDB}%'":'';

 

   

      $types = array_filter($types, "removeEmpty"); // removes any item that was empty (not checked)

     

      if (count($types) < 1)

        $types[] = "`name` LIKE '%{$searchTermDB}%'"; // use the name as a default search if none are checked

     

          $andOr = isset($_GET['matchall'])?'AND':'OR';

      $searchSQL .= implode(" {$andOr} ", $types) . " ORDER BY `ssn`"; // order by ssn.

 

      $searchResult = mysql_query($searchSQL) or trigger_error("There was an error.<br/>" . mysql_error() . "<br />SQL Was: {$searchSQL}");

     

if ($num_rows < 1 ) {

          echo '<b>No Titles Found.</b><br><br><br>';

      }else {

        $results = array(); // the result array

        $i = 1;

        while ($row = mysql_fetch_assoc($searchResult)) {

            $results[] = "{$i}: {$row['ssn']}<br /><br />{$row['name']}<br /><br />";

            $i++;

        }

      }

  }

 

 

function removeEmpty($var) {

  return (!empty($var));

}

?>

<html>

  <title>My Simple Search Form</title>

  <style type="text/css">

      #error {

        color: red;

      }

  </style>

  <name>

      <?php echo (count($error) > 0)?"The following had errors:<br /><span id=\"error\">" . implode("<br />", $error) . "</span><br /><br />":""; ?>

      <form method="GET" action="<?php echo $_SERVER['PHP_SELF'];?>" name="searchForm">

        Search For: <input type="text" name="search" value="<?php echo isset($searchTerms)?htmlspecialchars($searchTerms):''; ?>" /><br />

        Search In:<br />

        name: <input type="checkbox" name="name" value="on" <?php echo isset($_GET['name'])?"checked":''; ?> /> |

        ssn: <input type="checkbox" name="ssn" value="on" <?php echo isset($_GET['ssn'])?"checked":''; ?> /> |

        /><br />

                Match All Selected Fields? <input type="checkbox" name="matchall" value="on" <?php echo isset($_GET['matchall'])?"checked":''; ?><br /><br />

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

      </form>

      <?php echo (count($results) > 0)?"Your search term: {$searchTerms} returned:<br /><br />" . implode("", $results):""; ?>

  </name>

</html>

 

When I try this, it gives me this message:

 

Parse error: syntax error, unexpected '}' in /home/olsendai/public_html/sqlfour.php on line 65.

 

Help.  Please!

 

It seems simple, but when I remove the unexpected '}', it comes back with this error - before I have even used the search feature

 

Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in /home/olsendai/public_html/sqlfour.php on line 60

The following had errors:

Search terms must be longer than 3 characters.

 

 

Link to comment
Share on other sites

  if (strlen($searchTerms) < 3) {

 

haha.. you made a heart :D

 

 

aside from your beautiful heart :) your crazy } needs  to be removed for sure, and your error is probably because that crazy } belonged to an if statement which was to see if the form had been submitted :) which you removed..

Link to comment
Share on other sites

Thank you for your help, but now I've got that danged "Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource".  I've tried to match everything up to make sure the resources are there for fetching, but I cannot get it to work.

 

 

:shrug:I feel like this is something really obvious I am overlooking.  I have just been trying to get this to work for so many days!

Link to comment
Share on other sites

That error means that your query failed, due to either a problem with the database connection, with the table/columns, or a syntax error in the query.

 

Unfortunately, using or trigger_error() (using or anything()) in code is only useful for troubleshooting purposes because it does not address the code execution path when an error does occur. Also, what trigger_error() does is dependent on the error_reporting/display_errors/log_errors settings.

 

Are you doing this on a system with error_reporting set to E_ALL so that all the errors that are detected would be reported (the default for trigger_error() and what the code you are using does would be to generate a NOTICE level error.)

 

Also, your code is not setting $num_rows (you would be getting another NOTICE level error when it is referenced), so the code will always display 'No Titles Found'.

 

And the }else { logic that is retrieving the results from the query (where your current WARNING level error is at) is part of this test if (count($error) < 1) { , so it (the code retrieving the results from the query) will be executed when $error does have a count of 1 or more, and not when the query returned some matching rows.

 

Edit: Actually, based on the last paragraph, the error is because your query has not even been executed at the time you attempt to retrieve the results from the query because of the incorrect logic in your code..

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.