简体   繁体   中英

how do I loop inside a loop with PHP in MySQL?

table persons

name  |   details
------------------
mathew| tax,home,car,insurance
john  | job,tax,employ
neil  | tax,home,car,job
yancy | consultant,rent,family
lucy  | home,car,insurance

I want loop through this table and search with details then saved result to another table called persons1

name  |   names
------------------
mathew| neil,lucy,john
neil  | mathew,lucy,john
john  | mathew,lucy,neil

so far I coded something like below but not working

mysql_connect("localhost", "root", "pass"); 
mysql_select_db("database");
$query = "SELECT * FROM persons"; 
$result  = mysql_query($query); 
while($r = mysql_fetch_array($result)) 
{ 
    $exp = explode(",",$r["details"]);
    $sql = mysql_query('SELECT * FROM persons WHERE MATCH (tags) AGAINST ("+$exp[0]" "+$exp[1]" "+$exp[2]" IN BOOLEAN MODE)'); 
    $result = array(); 
    while($row = mysql_fetch_assoc($sql))
    {   
        array_push($result,$row['name']);
        $name = implode(",",$result);   
        mysql_query("INSERT INTO person_new (name,names) VALUES (\"".$r["name"]."\", \"".$name."\")");
    } 
}

IT is very sad that nobody can give an answer to my question about my code. instead of looking into my design I request you to look into my code and tell me where I made a mistake..i am doing something different than what it sees and this is why I request you to check my code...

Your problem would be better solved via database normalization .

Storing data like tax,home,car,insurance in a single column, then parsing it to search is a Very Bad Idea.

First of all, it'd be nice if you'd tell us what doesn't work.

Having said that, I suspect (at least one of) your error(s) is here:

'SELECT * FROM persons WHERE MATCH (tags) AGAINST ("+$exp[0]" "+$exp[1]" "+$exp[2]" IN BOOLEAN MODE)'
                                                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

This will literally give you the query AGAINST ("+$exp[0]" "+$exp[1]" "+$exp[2]" IN BOOLEAN MODE) , which is likely not what you want. You need to concatenate the string, or use a double quoted string:

'SELECT ... AGAINST ("+' . $exp[0] . '" "+' . $exp[1] . '" "+' . $exp[2] . '" IN BOOLEAN MODE)'

or

"SELECT ... AGAINST (\"+$exp[0]\" \"+$exp[1]\" \"+$exp[2]\" IN BOOLEAN MODE)"

I'm with @Dolph though, this is not a good database structure, and if you're going to redesign it later anyway (careful with saying "later", that usually never happens), you should just do it now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM