0

I make search function in one php file. but after i separate them my coding show undefined index. Any can help me to solve this error the undefine index for the full_name not string

<?php

if ($_REQUEST["string"]<>'') {
    $search_string = " AND (file_name LIKE '%".mysql_real_escape_string($_REQUEST["string"])."%')";
}

if ($_REQUEST["file_name"]<>''){
    $sql = "SELECT * FROM file WHERE file_name'".mysql_real_escape_string($_REQUEST["file_name"])."'".$search_string;
}
else {
    $sql = "SELECT * FROM file WHERE file_id>0 ".$search_string;
}

$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        $id=$row['file_id']?>
        <tr>
            <td><?php echo $row["file_id"]; ?></td>
            <td><?php echo $row["file_reference"]; ?></td>
            <td><?php echo $row["file_name"]; ?></td>
            <td><?php echo $row["file_location"]; ?></td>
            <td><?php echo $row["file_pdf"]; ?></td>
        </tr>
    <?php
    }
} else {
?>
<tr><td colspan="5">No results found.</td>
    <?php
    }
    ?>

any suggestion to solve undefined error on my coding.

Cœur
  • 37,241
  • 25
  • 195
  • 267
  • Please, [stop using `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php). They are no longer maintained and are [officially deprecated](https://wiki.php.net/rfc/mysql_deprecation). Learn about [prepared statements](http://en.wikipedia.org/wiki/Prepared_statement) instead, and consider using PDO, [it's not as hard as you think](http://jayblanchard.net/demystifying_php_pdo.html). – Jay Blanchard May 28 '15 at 19:35

2 Answers2

2

Use isset to check, if variable or key exists.

if (isset($_REQUEST['string']) && $_REQUEST["string"] != '') {
    // $_REQUEST['string'] exists and is non-empty
}

For others it will be the same.

pavel
  • 26,538
  • 10
  • 45
  • 61
1

When you check to see if $_REQUEST["string"]<>'' you are actually trying to access that index. use isset() to check that it is set first.

Also, what line are you getting the error on, because it could also be that you are trying to access a column that isn't in your query response. So there could be multiple places where you'd get that error in this code.

RightClick
  • 1,090
  • 7
  • 12
  • undefine index on file_name – MUHAMMAD SYAMIRUL AMIN BIN AZA May 28 '15 at 19:09
  • that's probably near the top, you should check to see `if(isset($_REQUEST["file_name"]))` before you try to use it in your query. You're doing some check on `full_name` and then using `file_name` before ever checking that it exists – RightClick May 28 '15 at 19:13
  • so I see that you updated the question and changed `full_name` to `file_name`. Maybe the `isset()` check seems unnecessary to you at this point, but trust me you won't be done with this fix until you check that. – RightClick May 28 '15 at 19:19