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()); }
Similar Posts:
- Merging 2 MySQL tables with PHP – update one table’s field with another table’s field data (both table have one common field)
- Copy one table’s field records into another table’s field in MySQL database with PHP
- Display data from MySQL with PHP
- Display data from MySQL database with HTML form and PHP
- Check how many record in the MySQL database matches the query





