1

I need to find a result from all columns of a table starting with a specific value, regardless the column and assuming I don't know the columns's name, something like this:

$sql = "SELECT * FROM $myTable WHERE AllTheColumns LIKE '{$theValue}%'";

I know after the "WHERE" I have to specify the column name, but any other solution will be ok (if exists).

davejal
  • 6,009
  • 10
  • 39
  • 82
  • You could look for about column names in metadata information. – Shondeslitch Nov 29 '15 at 01:01
  • 1
    @todd's answer should get you the required result. However I am wondering why you are trying to do it this way? I think you may have better success refining your process and maybe adjusting your table structure. –  Nov 29 '15 at 01:07
  • @Dijon I'm trying to optimice my code because i'm working with tables with 15 - 23 columns, using the @ яша method. – Roberto Sepúlveda Bravo Nov 29 '15 at 02:51

3 Answers3

2

There's any other way you can do it.

SELECT * FROM $myTable 
    WHERE Column1 LIKE '%$search%' 
        OR Column2 LIKE '%$search%' 
        OR Column2 LIKE '%$search%'  
        OR Column3 LIKE '%$search%'
Yehia Awad
  • 2,898
  • 1
  • 20
  • 31
2

You could first select all the column names from the table:

SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'my_database' AND TABLE_NAME = 'my_table';

// store resulting column names in $column_names var;

Then, with an array of column names, create a loop that adds each column name to the query:

$query = "SELECT * FROM $table_name WHERE ";

foreach($column_names as $i => $colname) {
  $query .= "$colname LIKE %$search_string% ";
  if ($i+1 < $column_names.length()) {
    $query .= " OR ";
  }
}

// do stuff with query
Todd
  • 2,824
  • 2
  • 29
  • 39
  • I trying this way but I think I'm not creating correctly that array of column names, I have this: $sql="SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '$db' AND TABLE_NAME = 'personal';"; $thenames = mysql_query($sql, $db); $column_names=array(); while($fila = mysql_fetch_object($thenames)) { array_push($column_names,$fila); } and the error: Warning: mysql_fetch_object(): supplied argument is not a valid MySQL result resource in C:\xampp\htdocs\ ... – Roberto Sepúlveda Bravo Nov 29 '15 at 02:38
1

possibly, there are two options.

1) You can get all column names and perform operation accordingly.

2) You can reffere specific column by typing index.

Community
  • 1
  • 1
Ali Shan
  • 334
  • 3
  • 11