PHPSuperBlog.com

Include PHP variable in a MySQL query

Editor’s note: In cases, we have to include PHP variables within a MySQL query, here is how it is done:

Here is an example PHP file to demonstrate how to do so:

$query = "SELECT * FROM table1";
$result = mysql_query($query)or die(mysql_error());
while ($line = mysql_fetch_assoc($result)) {
mysql_query("UPDATE table2 SET name = ???")or die(mysql_error());
}

In the case above we have “???” which is a field called “name” from table1 stored with a PHP variable $line['name'].

To include the PHP variable into the query, we have to add

'".        ."'

between it, ie:

'".$line['name']."'

All together we get:

$query = "SELECT * FROM table1";
$result = mysql_query($query)or die(mysql_error());
while ($line = mysql_fetch_assoc($result)) {
mysql_query("UPDATE table2 SET name = '".$line['name']."'")or die(mysql_error());
}
VN:F [1.9.3_1094]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.3_1094]
Rating: 0 (from 0 votes)

Similar Posts:

Leave a comment