views:

214

answers:

4

I was hoping to change one of the variables of a query, from inside the while loop, is it possible to do this? EG.

$query = mysql_query('SELECT column1, column2 FROM table1 WHERE column1 = "'.$variable.'";', $conn);
while ($data = mysql_fetch_assoc($query)) {
    if($data['column2'] == 'original') {
        $variable = 'altered';
    }
}

I just want to see if this is possible, or is the $data array already fully generated, before stepping through the while statement?

Thanks

A: 

The query has been executed, changing the variables would have no difference even if it worked. When the query is executed with mysql_query, the data it returns is just that and won't change no matter how much you change the variables you used in the query.

Also I do not understand why you'd want to even do something like that and what your purpose is, if you could elaborate a bit, perhaps we could find a better solution to your problem.

Tatu Ulmanen
+1  A: 

i believe what you are trying to do is change the query that you are running by changing the variable?

by the time you are changing the variable, you have already executed the query, and $data is 'fully generated' as you say.

contagious
A: 

The query has already been performed when you use mysql_query(), the mysql_fetch_assoc() just interprets the return data. So no.

You could theoretically do something along the lines of:

$query = mysql_query('SELECT column1, column2 FROM table1 WHERE column1 = "'. $variable.'";', $conn);
while ($data = mysql_fetch_assoc($query)) {
    if($data['column2'] == 'original') {
        $variable = 'altered';
        // Run the query with the new $variable value.
        $query = mysql_query('SELECT column1, column2 FROM table1 WHERE column1 = "'. $variable.'";', $conn);
    }
}

To rerun the query every time, but that might not really be what you want to do a it could get stuck in the loop.

zipcodeman
A: 

No. The query has been executed and the return array made. But I think this code might interest you (very safe, efficient method to make queries):

// Make an instance of the PDO object to connect to database. $db = new PDO('mysql:unix_socket=/tmp/mysql.sock', $user, $password);

// load query into object using ? as the placeholder. $q = $db->prepare("SELECT column1, column2 FROM table1 WHERE column1 = ?");

// give a value to the placeholder inside an array and execute once. $q->execute(array('foo'));

while ($row = $q->fetch()) { if ($row['column2'] == 'original') {$v = "altered"; $q->execute(array($v)); break;} // execute new query using new value. }

Cian E