I am trying to use the logic below to take the data from the select statement and insert it into a table called a_metacourses. I know the syntax is right because it is running ok, but it is giving me my error message 'Error, query failed' rather than populating the table. I know the sql is right, I've run it in mysql successfully. Any thoughts on why this is not working?

<?php

//database configuration file
include('config.php');

//first delete all data from the table because maybe redunancy 
$qq=mysql_query(" TRUNCATE TABLE `a_metacourses`");

//select all data needed to populate table
$sql = " SELECT mdl_course_meta.parent_course, mdl_role_assignments.roleid, mdl_role_assignments.userid, '
    . ' mdl_course_meta.child_course, mdl_course.shortname'
    . ' FROM mdl_context INNER JOIN'
    . ' mdl_role_assignments ON mdl_context.id = mdl_role_assignments.contextid INNER JOIN'
    . ' mdl_course_meta ON mdl_context.instanceid = mdl_course_meta.child_course INNER JOIN'
    . ' mdl_course ON mdl_course_meta.child_course = mdl_course.id'"; 
$result=mysql_query($query) or die('Error, query failed');
while($data=mysql_fetch_array($result))

{
$parent_course = $data['parent_course'];
print_r($parent_course);
$roleid = $data['roleid'];
print_r($roleid);
$userid = $data['userid'];
print_r($userid);
$child_course = $data['child_course'];
print_r($child_course);
$shortname = $data['shortname'];
print_r($shortname);

for ($i = 0; $i < $size; $i++)
{
$sql="insert into a_metacourses (parent_course,roleid,userid,child_course,shortname) values('".$parent_course."','".$roleid."','".$userid."','".$child_course."','".$shortname."')";
			$res=mysql_query($sql);
}

}

?>

    You might consider adding a $link variable to your mysql_query() statement. I personally haven't had good luck with leaving the database link to chance.

    I'm assuming that if you do:

    echo $sql;

    ...then paste the resulting SQL query into MySQL Administrator, the query works.

    For better troubleshooting in the future, you might even consider revising your die() statement to:

    die("Some error.<br>".$sql);

    ...or even:

    die(mysql_error()."<br>My error statement.<br>".$sql);
      Write a Reply...