0

I'm trying to make some insert function, but something is wrong, and can find where is the problem. Basically o just set some informations, and this same should be insert in database. The message errors are:

Notice: Undefined variable: conn in /Applications/AMPPS/www/teste/index.php on line 21

Fatal error: Call to a member function query() on a non-object in /Applications/AMPPS/www/teste/index.php on line 21

    ini_set('display_errors',1);
    ini_set('display_startup_erros',1);
    error_reporting(E_ALL);

    $dbtype     = "mysql";
    $dbhost     = "XXXXXXXXXX";
    $dbname     = "XXXXXXXXXX";
    $dbuser     = "XXXXXXXXXX";
    $dbpass     = "XXXXXXXXXX";
    $conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
    function Insertdata($table,$field,$data){

        $field_values= implode(',',$field);
        $data_values=implode(',',$data);
        $sql = "INSERT into". " ".$table." ".$field_values. "VALUES(".$data_values.")";
        $result = $conn->query($sql);

      }
      $table="teste";
      $field_values=array("nome","idade","email","cidade");
      $data_values=array("Teste","14","teste@yahoo.com","Rio de Janeiro");
      $sample = Insertdata($table,$field_values,$data_values);
      if($result)
      {
        echo "inserted";
      }
      else
      {
        echo "not inserted";
      }
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141

1 Answers1

0

You didn't pass $conn to your function, you'll need to do that in order to have it in scope:

function Insertdata($table, $field, $data, $conn){

    $field_values= implode(',',$field);
    $data_values=implode(',',$data);
    $sql = "INSERT into". " ".$table." ".$field_values. "VALUES(".$data_values.")";
    $result = $conn->query($sql);

}
Adam
  • 1,149
  • 2
  • 14
  • 21