Php 要回显类中的变量吗

Php 要回显类中的变量吗,php,mysql,forms,oop,insert,Php,Mysql,Forms,Oop,Insert,我在php中有一个OOP程序,可以将数据插入mysql数据库。。它工作正常,但问题是我想在插入数据时回显$msg,以显示数据已成功插入或错误 <?php $conn=mysql_connect("localhost","root",""); mysql_select_db("OOP_php",$conn); class insertdata{ function insert($name,$city,$country){ $msg; $sql=mysql_query("i

我在php中有一个OOP程序,可以将数据插入mysql数据库。。它工作正常,但问题是我想在插入数据时回显$msg,以显示数据已成功插入或错误

<?php 
$conn=mysql_connect("localhost","root","");
mysql_select_db("OOP_php",$conn);

class insertdata{
function insert($name,$city,$country){
    $msg;
    $sql=mysql_query("insert into OOP (name,City,Country) values('$name','$city','$country')");
    if($sql){

     $msg= "Successfully inserted"; 
    }
    else{
        $msg="Error!";
    }

}
}

?>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>
<form method="post" action="<?php $_SERVER['PHP_SELF'] ?>">
Name: <input type="text" name="name" /><br /><br />
City: <input type="text" name="city" /><br /><br />
Country: <input type="text" name="country" /><br /><br />
<input type="submit" name="submit" value="Submit" />
</form>

<?php
if(isset($_POST['submit'])){
$name=$_POST['name'];
$city=$_POST['city'];
$country=$_POST['country'];
$in=new insertdata();
$in->insert($name,$city,$country);
echo $in->msg;


}

 ?>

</body>
</html>

无标题文件

您需要返回带有
return$msg的字符串

class insertdata
{
    function insert($name,$city,$country){
        $msg;
        $sql=mysql_query("insert into OOP (name,City,Country) values('$name','$city','$country')");
        if($sql) {
           $msg= "Successfully inserted"; 
        } else {
            $msg="Error!";
        }
        return $msg; // <----------
    }
}
PS 1:mysql_*函数不安全,不推荐使用。在准备好的语句中使用mysqli_*或PDO


PS 2:您可能不希望返回true或false,然后在其他地方相应地显示消息。

将msg设置为类属性,并使用此关键字进行访问


了解
$this
和类属性。或者关于
return
statement您不需要var$msg,只需使用echo即可。警告:不要使用在PHP7中删除的过时接口。替换类和指南类有助于解释最佳实践。这里没有参数,这在代码中有严重的错误。转义任何和所有用户数据,特别是从
$\u POST
$\u GET
转义。解释总是有用的,而不是简单的代码哦,不,不,请不要使用mysql方法。有人修复它,直到孩子们复制它。“PS 1:mysql_u”函数是不安全的。”*-在某些情况下,当然。根据PHP7进行弃用和删除;对
echo $in->insert($name,$city,$country);
<?php 
$conn=mysql_connect("localhost","root","");
mysql_select_db("OOP_php",$conn);

class insertdata{
public $msg;
function insert($name,$city,$country){

$sql=mysql_query("insert into OOP (name,City,Country) values('$name','$city','$country')");
if($sql){

 $this->msg= "Successfully inserted"; 
}
else{
    $this->msg="Error!";
}
return $this->msg;
}
}

?>