想要在类中的Echo变量

时间:2018-01-19 19:21:25

标签: php mysql forms oop insert

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

<?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>

2 个答案:

答案 0 :(得分:0)

您需要使用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; // <----------
    }
}

然后

echo $in->insert($name,$city,$country);

PS 1:mysql_ *函数不安全且已弃用。将mysqli_ *或PDO与准备好的语句一起使用。

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

答案 1 :(得分:0)

将msg设置为类属性,并使用关键字http://php.net/manual/en/language.oop5.basic.php

进行访问
<?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;
}
}

?>