【发布时间】:2022-01-24 22:43:33
【问题描述】:
我为用户注册和表创建编写了一些脚本。但它给了我这个错误。我有点弄清楚是怎么回事,我错误地将 $ 链接传递给我的脚本,但我仍然无法弄清楚如何正确地做到这一点。请帮帮我。
db.php:
require_once './libs/rb-mysql.php';
require_once 'newUserNotification.php';
R::setup('mysql:host=127.0.0.1;dbname=aboutwork', 'root', '');
$link = mysqli_connect('localhost','root','','aboutwork');
if(mysqli_connect_errno())
{
echo 'Connection to database failed! ('.mysqli_connect_errno().'): '.mysqli_connect_error();
exit();
}
function register_worker($login, $password)
{
$user = R::findOne('users', 'login = ?', array($login));
$id = $user-> id;
create_new_user_notification($id, $GLOBALS["link"]);
}
newUserNotification.php:
<?php
require_once 'db.php';
$db = $link;
if(isset($_POST['RemoveNotification']))
echo remove_new_user_notification($_POST['RemoveNotification']);
else
echo get_new_user_notifications();
function create_new_user_notification($userId)
{
$sql = "INSERT INTO notifications (user_id) VALUES ('$userId')";
if(mysqli_query($GLOBALS['db'], $sql)) //error is here
return 'Successful';
else
return "Error: " .mysqli_error($GLOBALS['db']);//and here
}
function remove_new_user_notification($id)
{
$sql = "DELETE FROM notifications WHERE id='$id'";
if(mysqli_query($GLOBALS['db'], $sql))
return "Successful";
else
return "Error deleting record: ".mysqli_error($GLOBALS['db']);
}
function get_new_user_notifications()
{
$sql = "SELECT * FROM notifications";
$result = mysqli_query($GLOBALS['db'], $sql);
return json_encode($result->fetch_assoc());
}
?>
错误:
<b>Warning</b>: mysqli_query() expects parameter 1 to be mysqli, null given in <b>Z:\home\localhost\www\aboutwork\newUserNotification.php</b> on line <b>32</b><br />
<script language=JavaScript src='/denwer/errors/phperror_js.php'></script><!--error--><br />
<b>Fatal error</b>: Call to a member function fetch_assoc() on a non-object in <b>Z:\home\localhost\www\aboutwork\newUserNotification.php</b> on line <b>34</b><br />
<script language=JavaScript src='/denwer/errors/phperror_js.php'></script>
【问题讨论】:
-
您像这样启动与数据库的连接 $link = mysqli_connect('localhost','root','','aboutwork');并尝试对 $GLOBALS['db']; 执行查询您应该像这样设置连接 $GLOBALS['db']= mysqli_connect('localhost','root','','aboutwork');第二个错误是关于获取结果的。在获取之前始终检查结果是否存在。像这样: if($result) {$data=json_encode($result->fetch_assoc());} return $data;
-
您根本不应该使用 $GLOBALS。将 db 连接作为参数传递给函数...
-
我需要如何将 $GLOBALS['db'] 传递给 newUserNotification.php?我已经按照你说的做了,但我有同样的错误。我只是这样写: function get_new_user_notifications() { $sql = "SELECT * FROM notifications"; $result = mysqli_query($GLOBALS['db'], $sql); if($result) 返回 json_encode($result->fetch_assoc());否则返回“获取通知失败:”.mysqli_error($GLOBALS['db']); }
-
请在您的问题中更加具体,并且不要使用 cmets 进一步提问