gpt4 book ai didi

PHP OOP 与 MySQL

转载 作者:行者123 更新时间:2023-11-29 04:56:37 26 4
gpt4 key购买 nike

好吧,伙计们遇到了大麻烦,无法理解正在发生的事情。请帮忙。

首先我有一个数据库连接类:

    private $localhost = DB_LOCALHOST;
private $db = DB_DATABASE;
private $user = DB_USER;
private $password = DB_PASSWORD;
protected $link ;


function __construct()
{

$this->link = mysql_connect($this->localhost,$this->user,$this->password) or die(mysql_error()."<br/>".mysql_errno());
mysql_query("SET NAMES ".DB_CHARSET , $this->link) or die(mysql_error()."<br/>".mysql_errno());
mysql_select_db($this->db, $this->link)or die(mysql_error()."<br/>".mysql_errno());
if($this->link===false)
die("Didn't connect to DB");

}

function sql_query($q)
{
$r = mysql_query($q, $this->link) or die ("DATABASE ERROR! Please, contact the administrator.".mysql_error().);
return $r;
}

function __destruct()
{
mysql_close($this->link);
}

}

然后我在另一个函数中使用它的两个不同功能:

     function del_meal($id_meal)
{
$db_s = new DBConnect();
$db_s->sql_query("DELETE FROM `pictures` WHERE `id_target` = '{$id_meal}' AND `type` = 'meal';");
$db_s->sql_query("DELETE FROM `meal_ingredient` WHERE `id_meal` = '{$id_meal}';");
$db_s->sql_query("DELETE FROM `meal` WHERE `id_meal` = '{$id_meal}';");
unset($db_s);
$pictures = $this->select_pictures($id_meal,'meal');
if(count($pictures)>0)
{
foreach($pictures as $pic)
{
if(file_exists("./pictures/meal/{$pic}"))
{
unlink("./pictures/meal/{$pic}");
unlink("./pictures/meal/thumb/{$pic}");
}
}
}
}

function del_category($id_category)
{
$db = new DBConnect();
$id_category = $db->safe_var($id_category);
$q = $db->sql_query("SELECT * FROM `meal` WHERE `id_category` ='{$id_category}' ");
while($res = mysql_fetch_assoc($q))
{
$this->del_meal($res['id_meal']);
}
$db->sql_query("DELETE FROM `meal_category` WHERE `id_category` = '{$id_category}' ");
unset($db);
}

好的 - 这是 safe_var()

   function safe_var($var)
{
$var = stripslashes($var);
$var = trim($var);
$var = strip_tags($var);
$var = mysql_real_escape_string($var);
$var = htmlspecialchars($var);
$var = nl2br($var);

return $var;
}

所以 - 当我只使用 del meal 功能时 - 一切都很好 - 但当我使用 del category -我在第 33 行的 DBConnect.php 中收到“警告:mysql_query(): 7 不是有效的 MySQL-Link 资源数据库错误!请联系管理员。”

可能是什么原因。有人可以帮助我吗?

最佳答案

正如 SkippyChalmers 所说,您需要一个数据库实例。

function db($config)
{
static $db = NULL;
if($db === NULL)
{
$db = new DBConnect($config);
}
return $db;
}

// db()->sql_query(...);

但是,我建议you switch to PDO .

关于PHP OOP 与 MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5983637/

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