1

我试图将登录用户的用户名与他的年龄相关联,但出现以下错误。有人可以帮帮我吗?请帮我插入带有年龄的用户名。

Catchable fatal error: Object of class loggedInUser could not be converted to string 

这是插入查询:

<?php

if ( isset( $_POST['submit'] ) ) { 
require_once("models/config.php");
securePage($_SERVER['PHP_SELF']);

$age = $_POST["age"];
$username = $_SESSION["userCakeUser"];
$stmt = $mysqli->prepare("INSERT INTO test (username, Age) VALUES (?, ?)");

// TODO check that $stmt creation succeeded

// "s" means the database expects a string
$stmt->bind_param("ss",  $username, $age);

$stmt->execute();


$stmt->close();

mysqli->close();
}
?>
<html>
<body>
<form action="" method="post" enctype="multipart/form-data">
Age:<input type="text" name="age" required><br>
<input type="submit" value="Submit" name="submit">
</form>

这是我里面的东西config.php

<?php
require_once("db-settings.php"); //Require DB connection

//Retrieve settings
$stmt = $mysqli->prepare("SELECT id, name, value
FROM ".$db_table_prefix."configuration");   
$stmt->execute();
$stmt->bind_result($id, $name, $value);

while ($stmt->fetch()){
$settings[$name] = array('id' => $id, 'name' => $name, 'value' => $value);
}
$stmt->close();

//Set Settings
$emailActivation = $settings['activation']['value'];;
$mail_templates_dir = "models/mail-templates/";
$websiteName = $settings['website_name']['value'];
$websiteUrl = $settings['website_url']['value'];

$emailAddress = $settings['email']['value'];
$resend_activation_threshold = $settings['resend_activation_threshold']['value'];
$emailDate = date('dmy');
$language = $settings['language']['value'];
$template = $settings['template']['value'];

$default_hooks = array("#WEBSITENAME#","#WEBSITEURL#","#DATE#");
$default_replace = array($websiteName,$websiteUrl,$emailDate);

if (!file_exists($language)) {
$language = "models/languages/en.php";
}

if(!isset($language)) $langauge = "models/languages/en.php";

//Pages to require
require_once($language);
require_once("class.mail.php");
require_once("class.user.php");
require_once("class.newuser.php");
require_once("funcs.php");

session_start();

//Global User Object Var
//loggedInUser can be used globally if constructed
if(isset($_SESSION["userCakeUser"]) && is_object($_SESSION["userCakeUser"]))
{
$loggedInUser = $_SESSION["userCakeUser"];
}

?>
4

2 回答 2

1

我不知道您的 loggedInUser 对象具有哪些属性,但请尝试这样的事情

$user = $_SESSION["userCakeUser"]; // I think this returns an object - loggedInUser
$stmt = $mysqli->prepare("INSERT INTO test (username, Age) VALUES (?, ?)");

// TODO check that $stmt creation succeeded

// "s" means the database expects a string
$stmt->bind_param("ss",  $user->userName, $age); //or $user->getUsername()
于 2013-01-26T22:31:58.407 回答
0

在某些时候——虽然我看不到你的代码在哪里——你把一个对象当作一个字符串。有几种方法可以解决这个问题,具体取决于您要执行的操作:

  • 在课堂上使用__toString()魔法方法$loggedInUser
  • 从类中获取一个字符串属性$loggedInUser并处理它。例如$loggedInUser->getName()
于 2013-01-26T22:31:05.197 回答