searching all fields in mysql database

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
getseen
Forum Newbie
Posts: 14
Joined: Thu Jul 23, 2009 8:50 pm

searching all fields in mysql database

Post by getseen »

Hi there, hoping someone can help me.

Ive got my database and I want to be able to search all fields in a certain table.

Ive got code that can retrieve data from one specific table field, but I need it to be able to search through ALL of the fields in my table and then use an array to list the data.

Im not going to include all the code as Im hoping its just these snippets.

this gets the variable from the previous form

$var = @$_GET['q'] ;
$trimmed = trim($var);

and this bit is the mysql query

$query = "select * from listed_properties where county like \"%$trimmed%\"
order by county"
User avatar
akuji36
Forum Contributor
Posts: 190
Joined: Tue Oct 14, 2008 9:53 am
Location: Hartford, Connecticut

Re: searching all fields in mysql database

Post by akuji36 »

Hello

This should be fine. It connects mysql with php

then selects and returns all the data.

Code: Select all

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
 
mysql_select_db("my_db", $con);
 
$result = mysql_query("SELECT * FROM Persons");
 
while($row = mysql_fetch_array($result))
  {
  echo $row['FirstName'] . " " . $row['LastName'];
  echo "<br />";
  }
 
mysql_close($con);
?>

Note: the table name is Persons/

the names of the columns:

FirstName And LastName

and database names is my_db

thanks

Rod
User avatar
Apollo
Forum Regular
Posts: 794
Joined: Wed Apr 30, 2008 2:34 am

Re: searching all fields in mysql database

Post by Apollo »

Here's what you need:

Code: Select all

$fields = array();
$result = mysql_query("SHOW COLUMNS FROM dinertable");
if (mysql_num_rows($result) > 0) 
{ 
    while ($row = mysql_fetch_assoc($result)) $fields[] = $row['Field'];
}
$like = " LIKE '%".mysql_real_escape_string($var)."%' ";
$where = implode($like.' OR ',$fields).$like;
$result = mysql_query('SELECT * FROM dinertable WHERE '.$where);
// have fun with $result
Post Reply