我试图制作一些插入功能,但是出了点问题,可以找到问题所在。基本上只是设置一些信息,这同样应该插入数据库中。消息错误是:
注意:未定义的变量:第21行的/Applications/AMPPS/www/teste/index.php中的conn
致命错误:在第21行的/Applications/AMPPS/www/teste/index.php中调用非对象的成员函数query()
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";
}
答案 0 :(得分:0)
你没有将$conn
传递给你的函数,你需要这样做才能让它在范围内:
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);
}