gpt4 book ai didi

php - 在 pdo pql 语句中使用对象属性值

转载 作者:行者123 更新时间:2023-11-29 06:31:43 24 4
gpt4 key购买 nike

我对这个很陌生。我希望有人能够告诉我为什么以下代码不起作用。

我正在尝试将来自 Ajax 请求的数据发布到 PHP 脚本。我正在将值作为“用户”对象的属性加载。我希望然后使用它们来调用数据库函数,但我不明白为什么我不能在 PDO 语句中使用对象属性值。他们即将到来未定义...

谢谢

    <?php

class Userclass{
public $id;
public $forename;
public $surname;
public $greeting = "Mr";
public function f(){
call_user_func("dbinsert");
}
};


try {
$user = new Userclass;
$user->id = $_POST["id"];
$user->forename = $_POST["forename"];
$user->surname = $_POST["surname"];
$user->f();
} catch (Exception $e) {
echo "failed";
exit;
}


function dbinsert(){
Require("dbconnect.php");

try {
$sql = "INSERT INTO testtable (id, forename, surname)
VALUES (:id, :forename, :surname)";
$insert = $db->prepare($sql);
$insert->bindValue(':id', $user->id);
$insert->bindValue(':forename', $user->forename);
$insert->bindValue(':surname', $user->surname);
$insert->execute();
//$insert->execute(array(':id' => $user->id, ':forename' => $user->forename, ':surname' => $user->surname));
//$insert->execute(array(':id' => "16", ':forename' => "Bill", ':surname' => "Gates"));
echo $user->forename . " sucessfully added to database";

} catch (Exception $e) {
echo "Database insertion failed" . var_dump($e);
};
}

?>

最佳答案

您的 $user 变量未在 dbinsert() 范围内定义。您可以将 dbinsert() 函数添加到用户类中。或者将 $user 设置为 dbinsert() 的参数。

   <?php
Require("dbconnect.php");

class Userclass{
public $id;
public $forename;
public $surname;
public $greeting = "Mr";

public function dbinsert(){


try {
$sql = "INSERT INTO testtable (id, forename, surname)
VALUES (:id, :forename, :surname)";
$insert = $db->prepare($sql);
$insert->bindValue(':id', $this->id);
$insert->bindValue(':forename', $this->forename);
$insert->bindValue(':surname', $this->surname);
$insert->execute();
echo $this->forename . " sucessfully added to database";

} catch (Exception $e) {
echo "Database insertion failed" . var_dump($e);
};
}
};


try {
$user = new Userclass;
$user->id = $_POST["id"];
$user->forename = $_POST["forename"];
$user->surname = $_POST["surname"];
$user->dbinsert();
} catch (Exception $e) {
echo "failed";
exit;
}

?>

关于php - 在 pdo pql 语句中使用对象属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27568427/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com