想要回显类中的变量吗

roejwanj  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(316)

我有一个用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>
isr3a4wc

isr3a4wc1#

将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;
}
}

?>
xwbd5t1u

xwbd5t1u2#

你需要返回字符串 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,然后在其他地方相应地显示消息。

相关问题