Include PHP variable in a MySQL query

Posted by Shek on October 4, 2009 under MySQL, PHP | Be the First to Comment | Total View: 7,410 views

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:

1
2
3
4
5
$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:

1
2
3
4
5
$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());
}

Not what you want? Try a Search

Add A Comment

*