2

I am trying to Query a MySQL table to to bring any result that matches data that the user has input. The database,table and column names are also dynamically stored in variables. var_dump produces a bool(false) which means my query is wrong.

My Code

if (isset ( $_POST ['name'] )) {
            $name = trim ( $_POST ['name'] );
            $tblName = $_REQUEST ['tbl'];
            $colqry = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '$dbName' AND TABLE_NAME = '$tblName'";
            echo "<ul>";
            $col_names = mysqli_query ( $link, $colqry );
            while ( $col = mysqli_fetch_array ( $col_names, MYSQL_ASSOC ) ) {
                $colName = $col ['COLUMN_NAME'];
                $tblQry = "SELECT * FROM $tblName WHERE $colName=$name LIMIT 10";
                $query2 = mysqli_query ($link, $tblQry);
                echo $query2;
                while ( $query3 = mysqli_fetch_array ( $query2 ) ) {

                    echo "<li onclick=fill'" . $query3 [0] . "'>" . $query3 [0] . "</li>";
                }
            }
        }

What I want to achieve is list a table where the search terms matches something on the table either the column name or the data inside the columns

15
  • Add error reporting to the top of your file(s) right after your opening PHP tag for example <?php error_reporting(E_ALL); ini_set('display_errors', 1); then the rest of your code, to see if it yields anything, as well as or die(mysqli_error($link)) to mysqli_query(). You'll see errors in your query. Commented Mar 18, 2015 at 11:53
  • WHERE '$colName'='%$name%' you're looking to use LIKE when using % signs. I.e.: WHERE '$colName' LIKE '%$name%'. Otherwise, do WHERE '$colName'='$name' for an exact match. Commented Mar 18, 2015 at 11:54
  • This kind of problem can be symptomatic of poor design! Commented Mar 18, 2015 at 11:54
  • If i use LIKE it will list all the data in that column, but I want to specific data in the column not the actual column name. Commented Mar 18, 2015 at 11:55
  • 1
    You're quoting the table and column names as if they were strings, e.g. SELECT * FROM '$tblName' WHERE '$colName'='%$name%' Commented Mar 18, 2015 at 11:55

1 Answer 1

2

This line:

$tblQry = "SELECT * FROM $tblName WHERE $colName=$name LIMIT 10";

Quote the $name variable:

so it reads as WHERE $colName='$name'

You can then use $query3[$colname] to get the search match you're looking for.

For more information on identifer qualifiers, visit:

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.