Graham
Graham

Reputation: 155

Basic PHP/mySQL question ... Cycle through every row within a table

I need to cycle through each row for the particular field, grabbing its content, run it through a parser, and place the result back in the field. I rarely have to delve this far into things, so I working example would be greatly appreciated. Here's where I am at so far (please don't laugh!):

<?

    function parse_string($text){
        // do something with $text...
        return $text
    }

    $username="abcd";
    $password="1234";
    $database="abcdefg";
    $table="table2"
    $field="field3"

    mysql_connect(localhost,$username,$password);

    @mysql_select_db($database) or die( "Unable to select database");

    // And for the part I'd like help with...
    // Repeat through each row of $table, parsing the content of $field 
    // via the function parse_string($text) and placing the result back 
    // into the database (replacing $field)


    mysql_close();

?>

Upvotes: 0

Views: 950

Answers (2)

Hamid
Hamid

Reputation: 1760

function parse_string($text){
// do something with $text...
return $text
}

$result = mysql_query("SELECT * FROM [ TABLE NAME ]");
while(($row = mysql_fetch_assoc($result)){
    $myresult[] = $row;
}

array_walk( $myresult, 'parse_string' );

I suggest use "CASE THEN" statement for your update query ( it's just 1 query instead of few like below )!

UPDATE [ TABLE NAME ] SET [FIELD] = CASE `id` WHEN 1 THEN XXXXX ...... END, 
                          [FIELD] = CASE `id` WHEN 1 THEN XXXXX ...... END, 
                          .
                          .
                          .
                          .
                          WHERE ..........

Upvotes: 2

Ilia Choly
Ilia Choly

Reputation: 18557

Here's a simple example:

$result = mysql_query("SELECT * FROM mytable;");
while(($row = mysql_fetch_array() != null){
    echo $row["table_column"];
}

If you want to change the table values efficiently you have to do that inside the query

UPDATE mytables SET mycolumn = mycolumn + 1 WHERE mycolumn < 10;

Upvotes: 0

Related Questions